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":177}],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 <feross@feross.org> <http://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 (value instanceof ArrayBuffer) {
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) || string instanceof ArrayBuffer) {
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 // Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView`
2378 function isArrayBufferView (obj) {
2379 return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj)
2382 function numberIsNaN (obj) {
2383 return obj !== obj // eslint-disable-line no-self-compare
2386 },{"base64-js":3,"ieee754":17}],8:[function(require,module,exports){
2389 module.exports = earcut;
2391 function earcut(data, holeIndices, dim) {
2395 var hasHoles = holeIndices && holeIndices.length,
2396 outerLen = hasHoles ? holeIndices[0] * dim : data.length,
2397 outerNode = linkedList(data, 0, outerLen, dim, true),
2400 if (!outerNode) return triangles;
2402 var minX, minY, maxX, maxY, x, y, size;
2404 if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
2406 // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
2407 if (data.length > 80 * dim) {
2408 minX = maxX = data[0];
2409 minY = maxY = data[1];
2411 for (var i = dim; i < outerLen; i += dim) {
2414 if (x < minX) minX = x;
2415 if (y < minY) minY = y;
2416 if (x > maxX) maxX = x;
2417 if (y > maxY) maxY = y;
2420 // minX, minY and size are later used to transform coords into integers for z-order calculation
2421 size = Math.max(maxX - minX, maxY - minY);
2424 earcutLinked(outerNode, triangles, dim, minX, minY, size);
2429 // create a circular doubly linked list from polygon points in the specified winding order
2430 function linkedList(data, start, end, dim, clockwise) {
2433 if (clockwise === (signedArea(data, start, end, dim) > 0)) {
2434 for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
2436 for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
2439 if (last && equals(last, last.next)) {
2447 // eliminate colinear or duplicate points
2448 function filterPoints(start, end) {
2449 if (!start) return start;
2450 if (!end) end = start;
2457 if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
2460 if (p === p.next) return null;
2466 } while (again || p !== end);
2471 // main ear slicing loop which triangulates a polygon (given as a linked list)
2472 function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
2475 // interlink polygon nodes in z-order
2476 if (!pass && size) indexCurve(ear, minX, minY, size);
2481 // iterate through ears, slicing them one by one
2482 while (ear.prev !== ear.next) {
2486 if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
2487 // cut off the triangle
2488 triangles.push(prev.i / dim);
2489 triangles.push(ear.i / dim);
2490 triangles.push(next.i / dim);
2494 // skipping the next vertice leads to less sliver triangles
2503 // if we looped through the whole remaining polygon and can't find any more ears
2505 // try filtering points and slicing again
2507 earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1);
2509 // if this didn't work, try curing all small self-intersections locally
2510 } else if (pass === 1) {
2511 ear = cureLocalIntersections(ear, triangles, dim);
2512 earcutLinked(ear, triangles, dim, minX, minY, size, 2);
2514 // as a last resort, try splitting the remaining polygon into two
2515 } else if (pass === 2) {
2516 splitEarcut(ear, triangles, dim, minX, minY, size);
2524 // check whether a polygon node forms a valid ear with adjacent nodes
2525 function isEar(ear) {
2530 if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
2532 // now make sure we don't have other points inside the potential ear
2533 var p = ear.next.next;
2535 while (p !== ear.prev) {
2536 if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
2537 area(p.prev, p, p.next) >= 0) return false;
2544 function isEarHashed(ear, minX, minY, size) {
2549 if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
2551 // triangle bbox; min & max are calculated like this for speed
2552 var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x),
2553 minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y),
2554 maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x),
2555 maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
2557 // z-order range for the current triangle bbox;
2558 var minZ = zOrder(minTX, minTY, minX, minY, size),
2559 maxZ = zOrder(maxTX, maxTY, minX, minY, size);
2561 // first look for points inside the triangle in increasing z-order
2564 while (p && p.z <= maxZ) {
2565 if (p !== ear.prev && p !== ear.next &&
2566 pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
2567 area(p.prev, p, p.next) >= 0) return false;
2571 // then look for points in decreasing z-order
2574 while (p && p.z >= minZ) {
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;
2584 // go through all polygon nodes and cure small local self-intersections
2585 function cureLocalIntersections(start, triangles, dim) {
2591 if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
2593 triangles.push(a.i / dim);
2594 triangles.push(p.i / dim);
2595 triangles.push(b.i / dim);
2597 // remove two nodes involved
2604 } while (p !== start);
2609 // try splitting polygon into two and triangulate them independently
2610 function splitEarcut(start, triangles, dim, minX, minY, size) {
2611 // look for a valid diagonal that divides the polygon into two
2614 var b = a.next.next;
2615 while (b !== a.prev) {
2616 if (a.i !== b.i && isValidDiagonal(a, b)) {
2617 // split the polygon in two by the diagonal
2618 var c = splitPolygon(a, b);
2620 // filter colinear points around the cuts
2621 a = filterPoints(a, a.next);
2622 c = filterPoints(c, c.next);
2624 // run earcut on each half
2625 earcutLinked(a, triangles, dim, minX, minY, size);
2626 earcutLinked(c, triangles, dim, minX, minY, size);
2632 } while (a !== start);
2635 // link every hole into the outer loop, producing a single-ring polygon without holes
2636 function eliminateHoles(data, holeIndices, outerNode, dim) {
2638 i, len, start, end, list;
2640 for (i = 0, len = holeIndices.length; i < len; i++) {
2641 start = holeIndices[i] * dim;
2642 end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
2643 list = linkedList(data, start, end, dim, false);
2644 if (list === list.next) list.steiner = true;
2645 queue.push(getLeftmost(list));
2648 queue.sort(compareX);
2650 // process holes from left to right
2651 for (i = 0; i < queue.length; i++) {
2652 eliminateHole(queue[i], outerNode);
2653 outerNode = filterPoints(outerNode, outerNode.next);
2659 function compareX(a, b) {
2663 // find a bridge between vertices that connects hole with an outer ring and and link it
2664 function eliminateHole(hole, outerNode) {
2665 outerNode = findHoleBridge(hole, outerNode);
2667 var b = splitPolygon(outerNode, hole);
2668 filterPoints(b, b.next);
2672 // David Eberly's algorithm for finding a bridge between hole and outer polygon
2673 function findHoleBridge(hole, outerNode) {
2680 // find a segment intersected by a ray from the hole's leftmost point to the left;
2681 // segment's endpoint with lesser x will be potential connection point
2683 if (hy <= p.y && hy >= p.next.y) {
2684 var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
2685 if (x <= hx && x > qx) {
2688 if (hy === p.y) return p;
2689 if (hy === p.next.y) return p.next;
2691 m = p.x < p.next.x ? p : p.next;
2695 } while (p !== outerNode);
2697 if (!m) return null;
2699 if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint
2701 // look for points inside the triangle of hole point, segment intersection and endpoint;
2702 // if there are no points found, we have a valid connection;
2703 // otherwise choose the point of the minimum angle with the ray as connection point
2713 while (p !== stop) {
2714 if (hx >= p.x && p.x >= mx &&
2715 pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
2717 tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
2719 if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
2731 // interlink polygon nodes in z-order
2732 function indexCurve(start, minX, minY, size) {
2735 if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, size);
2739 } while (p !== start);
2741 p.prevZ.nextZ = null;
2747 // Simon Tatham's linked list merge sort algorithm
2748 // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
2749 function sortLinked(list) {
2750 var i, p, q, e, tail, numMerges, pSize, qSize,
2763 for (i = 0; i < inSize; i++) {
2771 while (pSize > 0 || (qSize > 0 && q)) {
2777 } else if (qSize === 0 || !q) {
2781 } else if (p.z <= q.z) {
2791 if (tail) tail.nextZ = e;
2804 } while (numMerges > 1);
2809 // z-order of a point given coords and size of the data bounding box
2810 function zOrder(x, y, minX, minY, size) {
2811 // coords are transformed into non-negative 15-bit integer range
2812 x = 32767 * (x - minX) / size;
2813 y = 32767 * (y - minY) / size;
2815 x = (x | (x << 8)) & 0x00FF00FF;
2816 x = (x | (x << 4)) & 0x0F0F0F0F;
2817 x = (x | (x << 2)) & 0x33333333;
2818 x = (x | (x << 1)) & 0x55555555;
2820 y = (y | (y << 8)) & 0x00FF00FF;
2821 y = (y | (y << 4)) & 0x0F0F0F0F;
2822 y = (y | (y << 2)) & 0x33333333;
2823 y = (y | (y << 1)) & 0x55555555;
2825 return x | (y << 1);
2828 // find the leftmost node of a polygon ring
2829 function getLeftmost(start) {
2833 if (p.x < leftmost.x) leftmost = p;
2835 } while (p !== start);
2840 // check if a point lies within a convex triangle
2841 function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
2842 return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
2843 (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
2844 (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
2847 // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
2848 function isValidDiagonal(a, b) {
2849 return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) &&
2850 locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
2853 // signed area of a triangle
2854 function area(p, q, r) {
2855 return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
2858 // check if two points are equal
2859 function equals(p1, p2) {
2860 return p1.x === p2.x && p1.y === p2.y;
2863 // check if two segments intersect
2864 function intersects(p1, q1, p2, q2) {
2865 if ((equals(p1, q1) && equals(p2, q2)) ||
2866 (equals(p1, q2) && equals(p2, q1))) return true;
2867 return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
2868 area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
2871 // check if a polygon diagonal intersects any polygon segments
2872 function intersectsPolygon(a, b) {
2875 if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
2876 intersects(p, p.next, a, b)) return true;
2883 // check if a polygon diagonal is locally inside the polygon
2884 function locallyInside(a, b) {
2885 return area(a.prev, a, a.next) < 0 ?
2886 area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
2887 area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
2890 // check if the middle point of a polygon diagonal is inside the polygon
2891 function middleInside(a, b) {
2894 px = (a.x + b.x) / 2,
2895 py = (a.y + b.y) / 2;
2897 if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
2905 // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
2906 // if one belongs to the outer ring and another to a hole, it merges it into a single ring
2907 function splitPolygon(a, b) {
2908 var a2 = new Node(a.i, a.x, a.y),
2909 b2 = new Node(b.i, b.x, b.y),
2928 // create a node and optionally link it with previous one (in a circular doubly linked list)
2929 function insertNode(i, x, y, last) {
2930 var p = new Node(i, x, y);
2945 function removeNode(p) {
2946 p.next.prev = p.prev;
2947 p.prev.next = p.next;
2949 if (p.prevZ) p.prevZ.nextZ = p.nextZ;
2950 if (p.nextZ) p.nextZ.prevZ = p.prevZ;
2953 function Node(i, x, y) {
2954 // vertice index in coordinates array
2957 // vertex coordinates
2961 // previous and next vertice nodes in a polygon ring
2965 // z-order curve value
2968 // previous and next nodes in z-order
2972 // indicates whether this is a steiner point
2973 this.steiner = false;
2976 // return a percentage difference between the polygon area and its triangulation area;
2977 // used to verify correctness of triangulation
2978 earcut.deviation = function (data, holeIndices, dim, triangles) {
2979 var hasHoles = holeIndices && holeIndices.length;
2980 var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
2982 var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
2984 for (var i = 0, len = holeIndices.length; i < len; i++) {
2985 var start = holeIndices[i] * dim;
2986 var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
2987 polygonArea -= Math.abs(signedArea(data, start, end, dim));
2991 var trianglesArea = 0;
2992 for (i = 0; i < triangles.length; i += 3) {
2993 var a = triangles[i] * dim;
2994 var b = triangles[i + 1] * dim;
2995 var c = triangles[i + 2] * dim;
2996 trianglesArea += Math.abs(
2997 (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
2998 (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
3001 return polygonArea === 0 && trianglesArea === 0 ? 0 :
3002 Math.abs((trianglesArea - polygonArea) / polygonArea);
3005 function signedArea(data, start, end, dim) {
3007 for (var i = start, j = end - dim; i < end; i += dim) {
3008 sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
3014 // turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
3015 earcut.flatten = function (data) {
3016 var dim = data[0][0].length,
3017 result = {vertices: [], holes: [], dimensions: dim},
3020 for (var i = 0; i < data.length; i++) {
3021 for (var j = 0; j < data[i].length; j++) {
3022 for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]);
3025 holeIndex += data[i - 1].length;
3026 result.holes.push(holeIndex);
3032 },{}],9:[function(require,module,exports){
3035 var OneVersionConstraint = require('individual/one-version');
3037 var MY_VERSION = '7';
3038 OneVersionConstraint('ev-store', MY_VERSION);
3040 var hashKey = '__EV_STORE_KEY@' + MY_VERSION;
3042 module.exports = EvStore;
3044 function EvStore(elem) {
3045 var hash = elem[hashKey];
3048 hash = elem[hashKey] = {};
3054 },{"individual/one-version":19}],10:[function(require,module,exports){
3056 var request = require('./request');
3057 var buildQueryObject = require('./buildQueryObject');
3058 var isArray = Array.isArray;
3060 function simpleExtend(obj, obj2) {
3062 for (prop in obj2) {
3063 obj[prop] = obj2[prop];
3068 function XMLHttpSource(jsongUrl, config) {
3069 this._jsongUrl = jsongUrl;
3070 if (typeof config === 'number') {
3076 this._config = simpleExtend({
3082 XMLHttpSource.prototype = {
3083 // because javascript
3084 constructor: XMLHttpSource,
3086 * buildQueryObject helper
3088 buildQueryObject: buildQueryObject,
3091 * @inheritDoc DataSource#get
3093 get: function httpSourceGet(pathSet) {
3095 var queryObject = this.buildQueryObject(this._jsongUrl, method, {
3099 var config = simpleExtend(queryObject, this._config);
3100 // pass context for onBeforeRequest callback
3102 return request(method, config, context);
3106 * @inheritDoc DataSource#set
3108 set: function httpSourceSet(jsongEnv) {
3109 var method = 'POST';
3110 var queryObject = this.buildQueryObject(this._jsongUrl, method, {
3111 jsonGraph: jsongEnv,
3114 var config = simpleExtend(queryObject, this._config);
3115 config.headers["Content-Type"] = "application/x-www-form-urlencoded";
3117 // pass context for onBeforeRequest callback
3119 return request(method, config, context);
3124 * @inheritDoc DataSource#call
3126 call: function httpSourceCall(callPath, args, pathSuffix, paths) {
3127 // arguments defaults
3129 pathSuffix = pathSuffix || [];
3130 paths = paths || [];
3132 var method = 'POST';
3134 queryData.push('method=call');
3135 queryData.push('callPath=' + encodeURIComponent(JSON.stringify(callPath)));
3136 queryData.push('arguments=' + encodeURIComponent(JSON.stringify(args)));
3137 queryData.push('pathSuffixes=' + encodeURIComponent(JSON.stringify(pathSuffix)));
3138 queryData.push('paths=' + encodeURIComponent(JSON.stringify(paths)));
3140 var queryObject = this.buildQueryObject(this._jsongUrl, method, queryData.join('&'));
3141 var config = simpleExtend(queryObject, this._config);
3142 config.headers["Content-Type"] = "application/x-www-form-urlencoded";
3144 // pass context for onBeforeRequest callback
3146 return request(method, config, context);
3150 XMLHttpSource.XMLHttpSource = XMLHttpSource;
3151 XMLHttpSource['default'] = XMLHttpSource;
3153 module.exports = XMLHttpSource;
3155 },{"./buildQueryObject":11,"./request":14}],11:[function(require,module,exports){
3157 module.exports = function buildQueryObject(url, method, queryData) {
3160 var data = {url: url};
3161 var isQueryParamUrl = url.indexOf('?') !== -1;
3162 var startUrl = (isQueryParamUrl) ? '&' : '?';
3164 if (typeof queryData === 'string') {
3165 qData.push(queryData);
3168 keys = Object.keys(queryData);
3169 keys.forEach(function (k) {
3170 var value = (typeof queryData[k] === 'object') ? JSON.stringify(queryData[k]) : queryData[k];
3171 qData.push(k + '=' + encodeURIComponent(value));
3175 if (method === 'GET') {
3176 data.url += startUrl + qData.join('&');
3178 data.data = qData.join('&');
3184 },{}],12:[function(require,module,exports){
3187 // Get CORS support even for older IE
3188 module.exports = function getCORSRequest() {
3189 var xhr = new global.XMLHttpRequest();
3190 if ('withCredentials' in xhr) {
3192 } else if (!!global.XDomainRequest) {
3193 return new XDomainRequest();
3195 throw new Error('CORS is not supported by your browser');
3199 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3201 },{}],13:[function(require,module,exports){
3204 module.exports = function getXMLHttpRequest() {
3208 if (global.XMLHttpRequest) {
3209 return new global.XMLHttpRequest();
3212 progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'];
3213 for (i = 0; i < 3; i++) {
3215 progId = progIds[i];
3216 if (new global.ActiveXObject(progId)) {
3221 return new global.ActiveXObject(progId);
3223 throw new Error('XMLHttpRequest is not supported by your browser');
3228 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3230 },{}],14:[function(require,module,exports){
3232 var getXMLHttpRequest = require('./getXMLHttpRequest');
3233 var getCORSRequest = require('./getCORSRequest');
3234 var hasOwnProp = Object.prototype.hasOwnProperty;
3236 var noop = function() {};
3238 function Observable() {}
3240 Observable.create = function(subscribe) {
3241 var o = new Observable();
3243 o.subscribe = function(onNext, onError, onCompleted) {
3248 if (typeof onNext === 'function') {
3251 onError: (onError || noop),
3252 onCompleted: (onCompleted || noop)
3258 disposable = subscribe(observer);
3260 if (typeof disposable === 'function') {
3272 function request(method, options, context) {
3273 return Observable.create(function requestObserver(observer) {
3276 method: method || 'GET',
3280 responseType: 'json'
3289 for (prop in options) {
3290 if (hasOwnProp.call(options, prop)) {
3291 config[prop] = options[prop];
3295 // Add request with Headers
3296 if (!config.crossDomain && !config.headers['X-Requested-With']) {
3297 config.headers['X-Requested-With'] = 'XMLHttpRequest';
3300 // allow the user to mutate the config open
3301 if (context.onBeforeRequest != null) {
3302 context.onBeforeRequest(config);
3307 xhr = config.crossDomain ? getCORSRequest() : getXMLHttpRequest();
3309 observer.onError(err);
3312 // Takes the url and opens the connection
3314 xhr.open(config.method, config.url, config.async, config.user, config.password);
3316 xhr.open(config.method, config.url, config.async);
3319 // Sets timeout information
3320 xhr.timeout = config.timeout;
3322 // Anything but explicit false results in true.
3323 xhr.withCredentials = config.withCredentials !== false;
3325 // Fills the request headers
3326 headers = config.headers;
3327 for (header in headers) {
3328 if (hasOwnProp.call(headers, header)) {
3329 xhr.setRequestHeader(header, headers[header]);
3333 if (config.responseType) {
3335 xhr.responseType = config.responseType;
3337 // WebKit added support for the json responseType value on 09/03/2013
3338 // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
3339 // known to throw when setting the value "json" as the response type. Other older
3340 // browsers implementing the responseType
3342 // The json response type can be ignored if not supported, because JSON payloads are
3343 // parsed on the client-side regardless.
3344 if (config.responseType !== 'json') {
3350 xhr.onreadystatechange = function onreadystatechange(e) {
3352 if (xhr.readyState === 4) {
3355 onXhrLoad(observer, xhr, e);
3361 xhr.ontimeout = function ontimeout(e) {
3364 onXhrError(observer, xhr, 'timeout error', e);
3369 xhr.send(config.data);
3372 observer.onError(e);
3375 return function dispose() {
3376 // Doesn't work in IE9
3377 if (!isDone && xhr.readyState !== 4) {
3386 * General handling of ultimate failure (after appropriate retries)
3388 function _handleXhrError(observer, textStatus, errorThrown) {
3389 // IE9: cross-domain request may be considered errors
3391 errorThrown = new Error(textStatus);
3394 observer.onError(errorThrown);
3397 function onXhrLoad(observer, xhr, e) {
3402 // If there's no observer, the request has been (or is being) cancelled.
3403 if (xhr && observer) {
3404 responseType = xhr.responseType;
3405 // responseText is the old-school way of retrieving response (supported by IE8 & 9)
3406 // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
3407 responseData = ('response' in xhr) ? xhr.response : xhr.responseText;
3409 // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
3410 var status = (xhr.status === 1223) ? 204 : xhr.status;
3412 if (status >= 200 && status <= 399) {
3414 if (responseType !== 'json') {
3415 responseData = JSON.parse(responseData || '');
3417 if (typeof responseData === 'string') {
3418 responseData = JSON.parse(responseData || '');
3421 _handleXhrError(observer, 'invalid json', e);
3423 observer.onNext(responseData);
3424 observer.onCompleted();
3427 } else if (status === 401 || status === 403 || status === 407) {
3429 return _handleXhrError(observer, responseData);
3431 } else if (status === 410) {
3433 return _handleXhrError(observer, responseData);
3435 } else if (status === 408 || status === 504) {
3437 return _handleXhrError(observer, responseData);
3441 return _handleXhrError(observer, responseData || ('Response code ' + status));
3447 function onXhrError(observer, xhr, status, e) {
3448 _handleXhrError(observer, status || xhr.statusText || 'request error', e);
3451 module.exports = request;
3453 },{"./getCORSRequest":12,"./getXMLHttpRequest":13}],15:[function(require,module,exports){
3455 !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(){
3456 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);
3457 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(){
3458 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(){
3459 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)});
3460 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3462 },{}],16:[function(require,module,exports){
3464 var topLevel = typeof global !== 'undefined' ? global :
3465 typeof window !== 'undefined' ? window : {}
3466 var minDoc = require('min-document');
3470 if (typeof document !== 'undefined') {
3473 doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'];
3476 doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc;
3480 module.exports = doccy;
3482 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3484 },{"min-document":4}],17:[function(require,module,exports){
3485 exports.read = function (buffer, offset, isLE, mLen, nBytes) {
3487 var eLen = nBytes * 8 - mLen - 1
3488 var eMax = (1 << eLen) - 1
3489 var eBias = eMax >> 1
3491 var i = isLE ? (nBytes - 1) : 0
3492 var d = isLE ? -1 : 1
3493 var s = buffer[offset + i]
3497 e = s & ((1 << (-nBits)) - 1)
3500 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
3502 m = e & ((1 << (-nBits)) - 1)
3505 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
3509 } else if (e === eMax) {
3510 return m ? NaN : ((s ? -1 : 1) * Infinity)
3512 m = m + Math.pow(2, mLen)
3515 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
3518 exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
3520 var eLen = nBytes * 8 - mLen - 1
3521 var eMax = (1 << eLen) - 1
3522 var eBias = eMax >> 1
3523 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
3524 var i = isLE ? 0 : (nBytes - 1)
3525 var d = isLE ? 1 : -1
3526 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
3528 value = Math.abs(value)
3530 if (isNaN(value) || value === Infinity) {
3531 m = isNaN(value) ? 1 : 0
3534 e = Math.floor(Math.log(value) / Math.LN2)
3535 if (value * (c = Math.pow(2, -e)) < 1) {
3539 if (e + eBias >= 1) {
3542 value += rt * Math.pow(2, 1 - eBias)
3544 if (value * c >= 2) {
3549 if (e + eBias >= eMax) {
3552 } else if (e + eBias >= 1) {
3553 m = (value * c - 1) * Math.pow(2, mLen)
3556 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
3561 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
3565 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
3567 buffer[offset + i - d] |= s * 128
3570 },{}],18:[function(require,module,exports){
3574 /*global window, global*/
3576 var root = typeof window !== 'undefined' ?
3577 window : typeof global !== 'undefined' ?
3580 module.exports = Individual;
3582 function Individual(key, value) {
3592 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3594 },{}],19:[function(require,module,exports){
3597 var Individual = require('./index.js');
3599 module.exports = OneVersion;
3601 function OneVersion(moduleName, version, defaultValue) {
3602 var key = '__INDIVIDUAL_ONE_VERSION_' + moduleName;
3603 var enforceKey = key + '_ENFORCE_SINGLETON';
3605 var versionValue = Individual(enforceKey, version);
3607 if (versionValue !== version) {
3608 throw new Error('Can only have one copy of ' +
3609 moduleName + '.\n' +
3610 'You already have version ' + versionValue +
3612 'This means you cannot install version ' + version);
3615 return Individual(key, defaultValue);
3618 },{"./index.js":18}],20:[function(require,module,exports){
3621 module.exports = function isObject(x) {
3622 return typeof x === "object" && x !== null;
3625 },{}],21:[function(require,module,exports){
3626 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
3627 /* Geohash encoding/decoding and associated functions (c) Chris Veness 2014-2016 / MIT Licence */
3628 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
3634 * Geohash encode, decode, bounds, neighbours.
3640 /* (Geohash-specific) Base32 map */
3641 Geohash.base32 = '0123456789bcdefghjkmnpqrstuvwxyz';
3644 * Encodes latitude/longitude to geohash, either to specified precision or to automatically
3645 * evaluated precision.
3647 * @param {number} lat - Latitude in degrees.
3648 * @param {number} lon - Longitude in degrees.
3649 * @param {number} [precision] - Number of characters in resulting geohash.
3650 * @returns {string} Geohash of supplied latitude/longitude.
3651 * @throws Invalid geohash.
3654 * var geohash = Geohash.encode(52.205, 0.119, 7); // geohash: 'u120fxw'
3656 Geohash.encode = function(lat, lon, precision) {
3658 if (typeof precision == 'undefined') {
3659 // refine geohash until it matches precision of supplied lat/lon
3660 for (var p=1; p<=12; p++) {
3661 var hash = Geohash.encode(lat, lon, p);
3662 var posn = Geohash.decode(hash);
3663 if (posn.lat==lat && posn.lon==lon) return hash;
3665 precision = 12; // set to maximum
3670 precision = Number(precision);
3672 if (isNaN(lat) || isNaN(lon) || isNaN(precision)) throw new Error('Invalid geohash');
3674 var idx = 0; // index into base32 map
3675 var bit = 0; // each char holds 5 bits
3679 var latMin = -90, latMax = 90;
3680 var lonMin = -180, lonMax = 180;
3682 while (geohash.length < precision) {
3684 // bisect E-W longitude
3685 var lonMid = (lonMin + lonMax) / 2;
3686 if (lon >= lonMid) {
3694 // bisect N-S latitude
3695 var latMid = (latMin + latMax) / 2;
3696 if (lat >= latMid) {
3707 // 5 bits gives us a character: append it and start over
3708 geohash += Geohash.base32.charAt(idx);
3719 * Decode geohash to latitude/longitude (location is approximate centre of geohash cell,
3720 * to reasonable precision).
3722 * @param {string} geohash - Geohash string to be converted to latitude/longitude.
3723 * @returns {{lat:number, lon:number}} (Center of) geohashed location.
3724 * @throws Invalid geohash.
3727 * var latlon = Geohash.decode('u120fxw'); // latlon: { lat: 52.205, lon: 0.1188 }
3729 Geohash.decode = function(geohash) {
3731 var bounds = Geohash.bounds(geohash); // <-- the hard work
3732 // now just determine the centre of the cell...
3734 var latMin = bounds.sw.lat, lonMin = bounds.sw.lon;
3735 var latMax = bounds.ne.lat, lonMax = bounds.ne.lon;
3738 var lat = (latMin + latMax)/2;
3739 var lon = (lonMin + lonMax)/2;
3741 // round to close to centre without excessive precision: ⌊2-log10(Δ°)⌋ decimal places
3742 lat = lat.toFixed(Math.floor(2-Math.log(latMax-latMin)/Math.LN10));
3743 lon = lon.toFixed(Math.floor(2-Math.log(lonMax-lonMin)/Math.LN10));
3745 return { lat: Number(lat), lon: Number(lon) };
3750 * Returns SW/NE latitude/longitude bounds of specified geohash.
3752 * @param {string} geohash - Cell that bounds are required of.
3753 * @returns {{sw: {lat: number, lon: number}, ne: {lat: number, lon: number}}}
3754 * @throws Invalid geohash.
3756 Geohash.bounds = function(geohash) {
3757 if (geohash.length === 0) throw new Error('Invalid geohash');
3759 geohash = geohash.toLowerCase();
3762 var latMin = -90, latMax = 90;
3763 var lonMin = -180, lonMax = 180;
3765 for (var i=0; i<geohash.length; i++) {
3766 var chr = geohash.charAt(i);
3767 var idx = Geohash.base32.indexOf(chr);
3768 if (idx == -1) throw new Error('Invalid geohash');
3770 for (var n=4; n>=0; n--) {
3771 var bitN = idx >> n & 1;
3774 var lonMid = (lonMin+lonMax) / 2;
3782 var latMid = (latMin+latMax) / 2;
3794 sw: { lat: latMin, lon: lonMin },
3795 ne: { lat: latMax, lon: lonMax },
3803 * Determines adjacent cell in given direction.
3805 * @param geohash - Cell to which adjacent cell is required.
3806 * @param direction - Direction from geohash (N/S/E/W).
3807 * @returns {string} Geocode of adjacent cell.
3808 * @throws Invalid geohash.
3810 Geohash.adjacent = function(geohash, direction) {
3811 // based on github.com/davetroy/geohash-js
3813 geohash = geohash.toLowerCase();
3814 direction = direction.toLowerCase();
3816 if (geohash.length === 0) throw new Error('Invalid geohash');
3817 if ('nsew'.indexOf(direction) == -1) throw new Error('Invalid direction');
3820 n: [ 'p0r21436x8zb9dcf5h7kjnmqesgutwvy', 'bc01fg45238967deuvhjyznpkmstqrwx' ],
3821 s: [ '14365h7k9dcfesgujnmqp0r2twvyx8zb', '238967debc01fg45kmstqrwxuvhjyznp' ],
3822 e: [ 'bc01fg45238967deuvhjyznpkmstqrwx', 'p0r21436x8zb9dcf5h7kjnmqesgutwvy' ],
3823 w: [ '238967debc01fg45kmstqrwxuvhjyznp', '14365h7k9dcfesgujnmqp0r2twvyx8zb' ],
3826 n: [ 'prxz', 'bcfguvyz' ],
3827 s: [ '028b', '0145hjnp' ],
3828 e: [ 'bcfguvyz', 'prxz' ],
3829 w: [ '0145hjnp', '028b' ],
3832 var lastCh = geohash.slice(-1); // last character of hash
3833 var parent = geohash.slice(0, -1); // hash without last character
3835 var type = geohash.length % 2;
3837 // check for edge-cases which don't share common prefix
3838 if (border[direction][type].indexOf(lastCh) != -1 && parent !== '') {
3839 parent = Geohash.adjacent(parent, direction);
3842 // append letter for direction to parent
3843 return parent + Geohash.base32.charAt(neighbour[direction][type].indexOf(lastCh));
3848 * Returns all 8 adjacent cells to specified geohash.
3850 * @param {string} geohash - Geohash neighbours are required of.
3851 * @returns {{n,ne,e,se,s,sw,w,nw: string}}
3852 * @throws Invalid geohash.
3854 Geohash.neighbours = function(geohash) {
3856 'n': Geohash.adjacent(geohash, 'n'),
3857 'ne': Geohash.adjacent(Geohash.adjacent(geohash, 'n'), 'e'),
3858 'e': Geohash.adjacent(geohash, 'e'),
3859 'se': Geohash.adjacent(Geohash.adjacent(geohash, 's'), 'e'),
3860 's': Geohash.adjacent(geohash, 's'),
3861 'sw': Geohash.adjacent(Geohash.adjacent(geohash, 's'), 'w'),
3862 'w': Geohash.adjacent(geohash, 'w'),
3863 'nw': Geohash.adjacent(Geohash.adjacent(geohash, 'n'), 'w'),
3868 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
3869 if (typeof module != 'undefined' && module.exports) module.exports = Geohash; // CommonJS, node.js
3871 },{}],22:[function(require,module,exports){
3872 (function (process){
3873 // Copyright Joyent, Inc. and other Node contributors.
3875 // Permission is hereby granted, free of charge, to any person obtaining a
3876 // copy of this software and associated documentation files (the
3877 // "Software"), to deal in the Software without restriction, including
3878 // without limitation the rights to use, copy, modify, merge, publish,
3879 // distribute, sublicense, and/or sell copies of the Software, and to permit
3880 // persons to whom the Software is furnished to do so, subject to the
3881 // following conditions:
3883 // The above copyright notice and this permission notice shall be included
3884 // in all copies or substantial portions of the Software.
3886 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3887 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3888 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3889 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3890 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3891 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3892 // USE OR OTHER DEALINGS IN THE SOFTWARE.
3894 // resolves . and .. elements in a path array with directory names there
3895 // must be no slashes, empty elements, or device names (c:\) in the array
3896 // (so also no leading and trailing slashes - it does not distinguish
3897 // relative and absolute paths)
3898 function normalizeArray(parts, allowAboveRoot) {
3899 // if the path tries to go above the root, `up` ends up > 0
3901 for (var i = parts.length - 1; i >= 0; i--) {
3902 var last = parts[i];
3905 } else if (last === '..') {
3914 // if the path is allowed to go above the root, restore leading ..s
3915 if (allowAboveRoot) {
3917 parts.unshift('..');
3924 // Split a filename into [root, dir, basename, ext], unix version
3925 // 'root' is just a slash, or nothing.
3927 /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
3928 var splitPath = function(filename) {
3929 return splitPathRe.exec(filename).slice(1);
3932 // path.resolve([from ...], to)
3934 exports.resolve = function() {
3935 var resolvedPath = '',
3936 resolvedAbsolute = false;
3938 for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
3939 var path = (i >= 0) ? arguments[i] : process.cwd();
3941 // Skip empty and invalid entries
3942 if (typeof path !== 'string') {
3943 throw new TypeError('Arguments to path.resolve must be strings');
3948 resolvedPath = path + '/' + resolvedPath;
3949 resolvedAbsolute = path.charAt(0) === '/';
3952 // At this point the path should be resolved to a full absolute path, but
3953 // handle relative paths to be safe (might happen when process.cwd() fails)
3955 // Normalize the path
3956 resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
3958 }), !resolvedAbsolute).join('/');
3960 return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
3963 // path.normalize(path)
3965 exports.normalize = function(path) {
3966 var isAbsolute = exports.isAbsolute(path),
3967 trailingSlash = substr(path, -1) === '/';
3969 // Normalize the path
3970 path = normalizeArray(filter(path.split('/'), function(p) {
3972 }), !isAbsolute).join('/');
3974 if (!path && !isAbsolute) {
3977 if (path && trailingSlash) {
3981 return (isAbsolute ? '/' : '') + path;
3985 exports.isAbsolute = function(path) {
3986 return path.charAt(0) === '/';
3990 exports.join = function() {
3991 var paths = Array.prototype.slice.call(arguments, 0);
3992 return exports.normalize(filter(paths, function(p, index) {
3993 if (typeof p !== 'string') {
3994 throw new TypeError('Arguments to path.join must be strings');
4001 // path.relative(from, to)
4003 exports.relative = function(from, to) {
4004 from = exports.resolve(from).substr(1);
4005 to = exports.resolve(to).substr(1);
4007 function trim(arr) {
4009 for (; start < arr.length; start++) {
4010 if (arr[start] !== '') break;
4013 var end = arr.length - 1;
4014 for (; end >= 0; end--) {
4015 if (arr[end] !== '') break;
4018 if (start > end) return [];
4019 return arr.slice(start, end - start + 1);
4022 var fromParts = trim(from.split('/'));
4023 var toParts = trim(to.split('/'));
4025 var length = Math.min(fromParts.length, toParts.length);
4026 var samePartsLength = length;
4027 for (var i = 0; i < length; i++) {
4028 if (fromParts[i] !== toParts[i]) {
4029 samePartsLength = i;
4034 var outputParts = [];
4035 for (var i = samePartsLength; i < fromParts.length; i++) {
4036 outputParts.push('..');
4039 outputParts = outputParts.concat(toParts.slice(samePartsLength));
4041 return outputParts.join('/');
4045 exports.delimiter = ':';
4047 exports.dirname = function(path) {
4048 var result = splitPath(path),
4052 if (!root && !dir) {
4053 // No dirname whatsoever
4058 // It has a dirname, strip trailing slash
4059 dir = dir.substr(0, dir.length - 1);
4066 exports.basename = function(path, ext) {
4067 var f = splitPath(path)[2];
4068 // TODO: make this comparison case-insensitive on windows?
4069 if (ext && f.substr(-1 * ext.length) === ext) {
4070 f = f.substr(0, f.length - ext.length);
4076 exports.extname = function(path) {
4077 return splitPath(path)[3];
4080 function filter (xs, f) {
4081 if (xs.filter) return xs.filter(f);
4083 for (var i = 0; i < xs.length; i++) {
4084 if (f(xs[i], i, xs)) res.push(xs[i]);
4089 // String.prototype.substr - negative index don't work in IE8
4090 var substr = 'ab'.substr(-1) === 'b'
4091 ? function (str, start, len) { return str.substr(start, len) }
4092 : function (str, start, len) {
4093 if (start < 0) start = str.length + start;
4094 return str.substr(start, len);
4098 }).call(this,require('_process'))
4100 },{"_process":6}],23:[function(require,module,exports){
4103 module.exports = Pbf;
4105 var ieee754 = require('ieee754');
4108 this.buf = ArrayBuffer.isView && ArrayBuffer.isView(buf) ? buf : new Uint8Array(buf || 0);
4111 this.length = this.buf.length;
4114 Pbf.Varint = 0; // varint: int32, int64, uint32, uint64, sint32, sint64, bool, enum
4115 Pbf.Fixed64 = 1; // 64-bit: double, fixed64, sfixed64
4116 Pbf.Bytes = 2; // length-delimited: string, bytes, embedded messages, packed repeated fields
4117 Pbf.Fixed32 = 5; // 32-bit: float, fixed32, sfixed32
4119 var SHIFT_LEFT_32 = (1 << 16) * (1 << 16),
4120 SHIFT_RIGHT_32 = 1 / SHIFT_LEFT_32;
4124 destroy: function() {
4128 // === READING =================================================================
4130 readFields: function(readField, result, end) {
4131 end = end || this.length;
4133 while (this.pos < end) {
4134 var val = this.readVarint(),
4136 startPos = this.pos;
4138 this.type = val & 0x7;
4139 readField(tag, result, this);
4141 if (this.pos === startPos) this.skip(val);
4146 readMessage: function(readField, result) {
4147 return this.readFields(readField, result, this.readVarint() + this.pos);
4150 readFixed32: function() {
4151 var val = readUInt32(this.buf, this.pos);
4156 readSFixed32: function() {
4157 var val = readInt32(this.buf, this.pos);
4162 // 64-bit int handling is based on github.com/dpw/node-buffer-more-ints (MIT-licensed)
4164 readFixed64: function() {
4165 var val = readUInt32(this.buf, this.pos) + readUInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32;
4170 readSFixed64: function() {
4171 var val = readUInt32(this.buf, this.pos) + readInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32;
4176 readFloat: function() {
4177 var val = ieee754.read(this.buf, this.pos, true, 23, 4);
4182 readDouble: function() {
4183 var val = ieee754.read(this.buf, this.pos, true, 52, 8);
4188 readVarint: function(isSigned) {
4192 b = buf[this.pos++]; val = b & 0x7f; if (b < 0x80) return val;
4193 b = buf[this.pos++]; val |= (b & 0x7f) << 7; if (b < 0x80) return val;
4194 b = buf[this.pos++]; val |= (b & 0x7f) << 14; if (b < 0x80) return val;
4195 b = buf[this.pos++]; val |= (b & 0x7f) << 21; if (b < 0x80) return val;
4196 b = buf[this.pos]; val |= (b & 0x0f) << 28;
4198 return readVarintRemainder(val, isSigned, this);
4201 readVarint64: function() { // for compatibility with v2.0.1
4202 return this.readVarint(true);
4205 readSVarint: function() {
4206 var num = this.readVarint();
4207 return num % 2 === 1 ? (num + 1) / -2 : num / 2; // zigzag encoding
4210 readBoolean: function() {
4211 return Boolean(this.readVarint());
4214 readString: function() {
4215 var end = this.readVarint() + this.pos,
4216 str = readUtf8(this.buf, this.pos, end);
4221 readBytes: function() {
4222 var end = this.readVarint() + this.pos,
4223 buffer = this.buf.subarray(this.pos, end);
4228 // verbose for performance reasons; doesn't affect gzipped size
4230 readPackedVarint: function(arr, isSigned) {
4231 var end = readPackedEnd(this);
4233 while (this.pos < end) arr.push(this.readVarint(isSigned));
4236 readPackedSVarint: function(arr) {
4237 var end = readPackedEnd(this);
4239 while (this.pos < end) arr.push(this.readSVarint());
4242 readPackedBoolean: function(arr) {
4243 var end = readPackedEnd(this);
4245 while (this.pos < end) arr.push(this.readBoolean());
4248 readPackedFloat: function(arr) {
4249 var end = readPackedEnd(this);
4251 while (this.pos < end) arr.push(this.readFloat());
4254 readPackedDouble: function(arr) {
4255 var end = readPackedEnd(this);
4257 while (this.pos < end) arr.push(this.readDouble());
4260 readPackedFixed32: function(arr) {
4261 var end = readPackedEnd(this);
4263 while (this.pos < end) arr.push(this.readFixed32());
4266 readPackedSFixed32: function(arr) {
4267 var end = readPackedEnd(this);
4269 while (this.pos < end) arr.push(this.readSFixed32());
4272 readPackedFixed64: function(arr) {
4273 var end = readPackedEnd(this);
4275 while (this.pos < end) arr.push(this.readFixed64());
4278 readPackedSFixed64: function(arr) {
4279 var end = readPackedEnd(this);
4281 while (this.pos < end) arr.push(this.readSFixed64());
4285 skip: function(val) {
4286 var type = val & 0x7;
4287 if (type === Pbf.Varint) while (this.buf[this.pos++] > 0x7f) {}
4288 else if (type === Pbf.Bytes) this.pos = this.readVarint() + this.pos;
4289 else if (type === Pbf.Fixed32) this.pos += 4;
4290 else if (type === Pbf.Fixed64) this.pos += 8;
4291 else throw new Error('Unimplemented type: ' + type);
4294 // === WRITING =================================================================
4296 writeTag: function(tag, type) {
4297 this.writeVarint((tag << 3) | type);
4300 realloc: function(min) {
4301 var length = this.length || 16;
4303 while (length < this.pos + min) length *= 2;
4305 if (length !== this.length) {
4306 var buf = new Uint8Array(length);
4309 this.length = length;
4313 finish: function() {
4314 this.length = this.pos;
4316 return this.buf.subarray(0, this.length);
4319 writeFixed32: function(val) {
4321 writeInt32(this.buf, val, this.pos);
4325 writeSFixed32: function(val) {
4327 writeInt32(this.buf, val, this.pos);
4331 writeFixed64: function(val) {
4333 writeInt32(this.buf, val & -1, this.pos);
4334 writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4);
4338 writeSFixed64: function(val) {
4340 writeInt32(this.buf, val & -1, this.pos);
4341 writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4);
4345 writeVarint: function(val) {
4348 if (val > 0xfffffff || val < 0) {
4349 writeBigVarint(val, this);
4355 this.buf[this.pos++] = val & 0x7f | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
4356 this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
4357 this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
4358 this.buf[this.pos++] = (val >>> 7) & 0x7f;
4361 writeSVarint: function(val) {
4362 this.writeVarint(val < 0 ? -val * 2 - 1 : val * 2);
4365 writeBoolean: function(val) {
4366 this.writeVarint(Boolean(val));
4369 writeString: function(str) {
4371 this.realloc(str.length * 4);
4373 this.pos++; // reserve 1 byte for short string length
4375 var startPos = this.pos;
4376 // write the string directly to the buffer and see how much was written
4377 this.pos = writeUtf8(this.buf, str, this.pos);
4378 var len = this.pos - startPos;
4380 if (len >= 0x80) makeRoomForExtraLength(startPos, len, this);
4382 // finally, write the message length in the reserved place and restore the position
4383 this.pos = startPos - 1;
4384 this.writeVarint(len);
4388 writeFloat: function(val) {
4390 ieee754.write(this.buf, val, this.pos, true, 23, 4);
4394 writeDouble: function(val) {
4396 ieee754.write(this.buf, val, this.pos, true, 52, 8);
4400 writeBytes: function(buffer) {
4401 var len = buffer.length;
4402 this.writeVarint(len);
4404 for (var i = 0; i < len; i++) this.buf[this.pos++] = buffer[i];
4407 writeRawMessage: function(fn, obj) {
4408 this.pos++; // reserve 1 byte for short message length
4410 // write the message directly to the buffer and see how much was written
4411 var startPos = this.pos;
4413 var len = this.pos - startPos;
4415 if (len >= 0x80) makeRoomForExtraLength(startPos, len, this);
4417 // finally, write the message length in the reserved place and restore the position
4418 this.pos = startPos - 1;
4419 this.writeVarint(len);
4423 writeMessage: function(tag, fn, obj) {
4424 this.writeTag(tag, Pbf.Bytes);
4425 this.writeRawMessage(fn, obj);
4428 writePackedVarint: function(tag, arr) { this.writeMessage(tag, writePackedVarint, arr); },
4429 writePackedSVarint: function(tag, arr) { this.writeMessage(tag, writePackedSVarint, arr); },
4430 writePackedBoolean: function(tag, arr) { this.writeMessage(tag, writePackedBoolean, arr); },
4431 writePackedFloat: function(tag, arr) { this.writeMessage(tag, writePackedFloat, arr); },
4432 writePackedDouble: function(tag, arr) { this.writeMessage(tag, writePackedDouble, arr); },
4433 writePackedFixed32: function(tag, arr) { this.writeMessage(tag, writePackedFixed32, arr); },
4434 writePackedSFixed32: function(tag, arr) { this.writeMessage(tag, writePackedSFixed32, arr); },
4435 writePackedFixed64: function(tag, arr) { this.writeMessage(tag, writePackedFixed64, arr); },
4436 writePackedSFixed64: function(tag, arr) { this.writeMessage(tag, writePackedSFixed64, arr); },
4438 writeBytesField: function(tag, buffer) {
4439 this.writeTag(tag, Pbf.Bytes);
4440 this.writeBytes(buffer);
4442 writeFixed32Field: function(tag, val) {
4443 this.writeTag(tag, Pbf.Fixed32);
4444 this.writeFixed32(val);
4446 writeSFixed32Field: function(tag, val) {
4447 this.writeTag(tag, Pbf.Fixed32);
4448 this.writeSFixed32(val);
4450 writeFixed64Field: function(tag, val) {
4451 this.writeTag(tag, Pbf.Fixed64);
4452 this.writeFixed64(val);
4454 writeSFixed64Field: function(tag, val) {
4455 this.writeTag(tag, Pbf.Fixed64);
4456 this.writeSFixed64(val);
4458 writeVarintField: function(tag, val) {
4459 this.writeTag(tag, Pbf.Varint);
4460 this.writeVarint(val);
4462 writeSVarintField: function(tag, val) {
4463 this.writeTag(tag, Pbf.Varint);
4464 this.writeSVarint(val);
4466 writeStringField: function(tag, str) {
4467 this.writeTag(tag, Pbf.Bytes);
4468 this.writeString(str);
4470 writeFloatField: function(tag, val) {
4471 this.writeTag(tag, Pbf.Fixed32);
4472 this.writeFloat(val);
4474 writeDoubleField: function(tag, val) {
4475 this.writeTag(tag, Pbf.Fixed64);
4476 this.writeDouble(val);
4478 writeBooleanField: function(tag, val) {
4479 this.writeVarintField(tag, Boolean(val));
4483 function readVarintRemainder(l, s, p) {
4487 b = buf[p.pos++]; h = (b & 0x70) >> 4; if (b < 0x80) return toNum(l, h, s);
4488 b = buf[p.pos++]; h |= (b & 0x7f) << 3; if (b < 0x80) return toNum(l, h, s);
4489 b = buf[p.pos++]; h |= (b & 0x7f) << 10; if (b < 0x80) return toNum(l, h, s);
4490 b = buf[p.pos++]; h |= (b & 0x7f) << 17; if (b < 0x80) return toNum(l, h, s);
4491 b = buf[p.pos++]; h |= (b & 0x7f) << 24; if (b < 0x80) return toNum(l, h, s);
4492 b = buf[p.pos++]; h |= (b & 0x01) << 31; if (b < 0x80) return toNum(l, h, s);
4494 throw new Error('Expected varint not more than 10 bytes');
4497 function readPackedEnd(pbf) {
4498 return pbf.type === Pbf.Bytes ?
4499 pbf.readVarint() + pbf.pos : pbf.pos + 1;
4502 function toNum(low, high, isSigned) {
4504 return high * 0x100000000 + (low >>> 0);
4507 return ((high >>> 0) * 0x100000000) + (low >>> 0);
4510 function writeBigVarint(val, pbf) {
4514 low = (val % 0x100000000) | 0;
4515 high = (val / 0x100000000) | 0;
4517 low = ~(-val % 0x100000000);
4518 high = ~(-val / 0x100000000);
4520 if (low ^ 0xffffffff) {
4521 low = (low + 1) | 0;
4524 high = (high + 1) | 0;
4528 if (val >= 0x10000000000000000 || val < -0x10000000000000000) {
4529 throw new Error('Given varint doesn\'t fit into 10 bytes');
4534 writeBigVarintLow(low, high, pbf);
4535 writeBigVarintHigh(high, pbf);
4538 function writeBigVarintLow(low, high, pbf) {
4539 pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
4540 pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
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;
4546 function writeBigVarintHigh(high, pbf) {
4547 var lsb = (high & 0x07) << 4;
4549 pbf.buf[pbf.pos++] |= lsb | ((high >>>= 3) ? 0x80 : 0); if (!high) return;
4550 pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
4551 pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 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;
4557 function makeRoomForExtraLength(startPos, len, pbf) {
4560 len <= 0x1fffff ? 2 :
4561 len <= 0xfffffff ? 3 : Math.ceil(Math.log(len) / (Math.LN2 * 7));
4563 // if 1 byte isn't enough for encoding message length, shift the data to the right
4564 pbf.realloc(extraLen);
4565 for (var i = pbf.pos - 1; i >= startPos; i--) pbf.buf[i + extraLen] = pbf.buf[i];
4568 function writePackedVarint(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeVarint(arr[i]); }
4569 function writePackedSVarint(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSVarint(arr[i]); }
4570 function writePackedFloat(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFloat(arr[i]); }
4571 function writePackedDouble(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeDouble(arr[i]); }
4572 function writePackedBoolean(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeBoolean(arr[i]); }
4573 function writePackedFixed32(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFixed32(arr[i]); }
4574 function writePackedSFixed32(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed32(arr[i]); }
4575 function writePackedFixed64(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFixed64(arr[i]); }
4576 function writePackedSFixed64(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed64(arr[i]); }
4578 // Buffer code below from https://github.com/feross/buffer, MIT-licensed
4580 function readUInt32(buf, pos) {
4581 return ((buf[pos]) |
4582 (buf[pos + 1] << 8) |
4583 (buf[pos + 2] << 16)) +
4584 (buf[pos + 3] * 0x1000000);
4587 function writeInt32(buf, val, pos) {
4589 buf[pos + 1] = (val >>> 8);
4590 buf[pos + 2] = (val >>> 16);
4591 buf[pos + 3] = (val >>> 24);
4594 function readInt32(buf, pos) {
4595 return ((buf[pos]) |
4596 (buf[pos + 1] << 8) |
4597 (buf[pos + 2] << 16)) +
4598 (buf[pos + 3] << 24);
4601 function readUtf8(buf, pos, end) {
4607 var c = null; // codepoint
4608 var bytesPerSequence =
4613 if (i + bytesPerSequence > end) break;
4617 if (bytesPerSequence === 1) {
4621 } else if (bytesPerSequence === 2) {
4623 if ((b1 & 0xC0) === 0x80) {
4624 c = (b0 & 0x1F) << 0x6 | (b1 & 0x3F);
4629 } else if (bytesPerSequence === 3) {
4632 if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80) {
4633 c = (b0 & 0xF) << 0xC | (b1 & 0x3F) << 0x6 | (b2 & 0x3F);
4634 if (c <= 0x7FF || (c >= 0xD800 && c <= 0xDFFF)) {
4638 } else if (bytesPerSequence === 4) {
4642 if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80) {
4643 c = (b0 & 0xF) << 0x12 | (b1 & 0x3F) << 0xC | (b2 & 0x3F) << 0x6 | (b3 & 0x3F);
4644 if (c <= 0xFFFF || c >= 0x110000) {
4652 bytesPerSequence = 1;
4654 } else if (c > 0xFFFF) {
4656 str += String.fromCharCode(c >>> 10 & 0x3FF | 0xD800);
4657 c = 0xDC00 | c & 0x3FF;
4660 str += String.fromCharCode(c);
4661 i += bytesPerSequence;
4667 function writeUtf8(buf, str, pos) {
4668 for (var i = 0, c, lead; i < str.length; i++) {
4669 c = str.charCodeAt(i); // code point
4671 if (c > 0xD7FF && c < 0xE000) {
4680 c = lead - 0xD800 << 10 | c - 0xDC00 | 0x10000;
4684 if (c > 0xDBFF || (i + 1 === str.length)) {
4704 buf[pos++] = c >> 0x6 | 0xC0;
4707 buf[pos++] = c >> 0xC | 0xE0;
4709 buf[pos++] = c >> 0x12 | 0xF0;
4710 buf[pos++] = c >> 0xC & 0x3F | 0x80;
4712 buf[pos++] = c >> 0x6 & 0x3F | 0x80;
4714 buf[pos++] = c & 0x3F | 0x80;
4720 },{"ieee754":17}],24:[function(require,module,exports){
4723 module.exports = partialSort;
4725 // Floyd-Rivest selection algorithm:
4726 // Rearrange items so that all items in the [left, k] range are smaller than all items in (k, right];
4727 // The k-th element will have the (k - left + 1)th smallest value in [left, right]
4729 function partialSort(arr, k, left, right, compare) {
4731 right = right || (arr.length - 1);
4732 compare = compare || defaultCompare;
4734 while (right > left) {
4735 if (right - left > 600) {
4736 var n = right - left + 1;
4737 var m = k - left + 1;
4738 var z = Math.log(n);
4739 var s = 0.5 * Math.exp(2 * z / 3);
4740 var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
4741 var newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
4742 var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
4743 partialSort(arr, k, newLeft, newRight, compare);
4751 if (compare(arr[right], t) > 0) swap(arr, left, right);
4757 while (compare(arr[i], t) < 0) i++;
4758 while (compare(arr[j], t) > 0) j--;
4761 if (compare(arr[left], t) === 0) swap(arr, left, j);
4764 swap(arr, j, right);
4767 if (j <= k) left = j + 1;
4768 if (k <= j) right = j - 1;
4772 function swap(arr, i, j) {
4778 function defaultCompare(a, b) {
4779 return a < b ? -1 : a > b ? 1 : 0;
4782 },{}],25:[function(require,module,exports){
4785 module.exports = rbush;
4787 var quickselect = require('quickselect');
4789 function rbush(maxEntries, format) {
4790 if (!(this instanceof rbush)) return new rbush(maxEntries, format);
4792 // max entries in a node is 9 by default; min node fill is 40% for best performance
4793 this._maxEntries = Math.max(4, maxEntries || 9);
4794 this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4));
4797 this._initFormat(format);
4806 return this._all(this.data, []);
4809 search: function (bbox) {
4811 var node = this.data,
4813 toBBox = this.toBBox;
4815 if (!intersects(bbox, node)) return result;
4817 var nodesToSearch = [],
4818 i, len, child, childBBox;
4821 for (i = 0, len = node.children.length; i < len; i++) {
4823 child = node.children[i];
4824 childBBox = node.leaf ? toBBox(child) : child;
4826 if (intersects(bbox, childBBox)) {
4827 if (node.leaf) result.push(child);
4828 else if (contains(bbox, childBBox)) this._all(child, result);
4829 else nodesToSearch.push(child);
4832 node = nodesToSearch.pop();
4838 collides: function (bbox) {
4840 var node = this.data,
4841 toBBox = this.toBBox;
4843 if (!intersects(bbox, node)) return false;
4845 var nodesToSearch = [],
4846 i, len, child, childBBox;
4849 for (i = 0, len = node.children.length; i < len; i++) {
4851 child = node.children[i];
4852 childBBox = node.leaf ? toBBox(child) : child;
4854 if (intersects(bbox, childBBox)) {
4855 if (node.leaf || contains(bbox, childBBox)) return true;
4856 nodesToSearch.push(child);
4859 node = nodesToSearch.pop();
4865 load: function (data) {
4866 if (!(data && data.length)) return this;
4868 if (data.length < this._minEntries) {
4869 for (var i = 0, len = data.length; i < len; i++) {
4870 this.insert(data[i]);
4875 // recursively build the tree with the given data from stratch using OMT algorithm
4876 var node = this._build(data.slice(), 0, data.length - 1, 0);
4878 if (!this.data.children.length) {
4879 // save as is if tree is empty
4882 } else if (this.data.height === node.height) {
4883 // split root if trees have the same height
4884 this._splitRoot(this.data, node);
4887 if (this.data.height < node.height) {
4888 // swap trees if inserted one is bigger
4889 var tmpNode = this.data;
4894 // insert the small tree into the large tree at appropriate level
4895 this._insert(node, this.data.height - node.height - 1, true);
4901 insert: function (item) {
4902 if (item) this._insert(item, this.data.height - 1);
4906 clear: function () {
4907 this.data = createNode([]);
4911 remove: function (item, equalsFn) {
4912 if (!item) return this;
4914 var node = this.data,
4915 bbox = this.toBBox(item),
4918 i, parent, index, goingUp;
4920 // depth-first iterative tree traversal
4921 while (node || path.length) {
4923 if (!node) { // go up
4925 parent = path[path.length - 1];
4930 if (node.leaf) { // check current node
4931 index = findItem(item, node.children, equalsFn);
4934 // item found, remove the item and condense tree upwards
4935 node.children.splice(index, 1);
4937 this._condense(path);
4942 if (!goingUp && !node.leaf && contains(node, bbox)) { // go down
4947 node = node.children[0];
4949 } else if (parent) { // go right
4951 node = parent.children[i];
4954 } else node = null; // nothing found
4960 toBBox: function (item) { return item; },
4962 compareMinX: compareNodeMinX,
4963 compareMinY: compareNodeMinY,
4965 toJSON: function () { return this.data; },
4967 fromJSON: function (data) {
4972 _all: function (node, result) {
4973 var nodesToSearch = [];
4975 if (node.leaf) result.push.apply(result, node.children);
4976 else nodesToSearch.push.apply(nodesToSearch, node.children);
4978 node = nodesToSearch.pop();
4983 _build: function (items, left, right, height) {
4985 var N = right - left + 1,
4986 M = this._maxEntries,
4990 // reached leaf level; return leaf
4991 node = createNode(items.slice(left, right + 1));
4992 calcBBox(node, this.toBBox);
4997 // target height of the bulk-loaded tree
4998 height = Math.ceil(Math.log(N) / Math.log(M));
5000 // target number of root entries to maximize storage utilization
5001 M = Math.ceil(N / Math.pow(M, height - 1));
5004 node = createNode([]);
5006 node.height = height;
5008 // split the items into M mostly square tiles
5010 var N2 = Math.ceil(N / M),
5011 N1 = N2 * Math.ceil(Math.sqrt(M)),
5012 i, j, right2, right3;
5014 multiSelect(items, left, right, N1, this.compareMinX);
5016 for (i = left; i <= right; i += N1) {
5018 right2 = Math.min(i + N1 - 1, right);
5020 multiSelect(items, i, right2, N2, this.compareMinY);
5022 for (j = i; j <= right2; j += N2) {
5024 right3 = Math.min(j + N2 - 1, right2);
5026 // pack each entry recursively
5027 node.children.push(this._build(items, j, right3, height - 1));
5031 calcBBox(node, this.toBBox);
5036 _chooseSubtree: function (bbox, node, level, path) {
5038 var i, len, child, targetNode, area, enlargement, minArea, minEnlargement;
5043 if (node.leaf || path.length - 1 === level) break;
5045 minArea = minEnlargement = Infinity;
5047 for (i = 0, len = node.children.length; i < len; i++) {
5048 child = node.children[i];
5049 area = bboxArea(child);
5050 enlargement = enlargedArea(bbox, child) - area;
5052 // choose entry with the least area enlargement
5053 if (enlargement < minEnlargement) {
5054 minEnlargement = enlargement;
5055 minArea = area < minArea ? area : minArea;
5058 } else if (enlargement === minEnlargement) {
5059 // otherwise choose one with the smallest area
5060 if (area < minArea) {
5067 node = targetNode || node.children[0];
5073 _insert: function (item, level, isNode) {
5075 var toBBox = this.toBBox,
5076 bbox = isNode ? item : toBBox(item),
5079 // find the best node for accommodating the item, saving all nodes along the path too
5080 var node = this._chooseSubtree(bbox, this.data, level, insertPath);
5082 // put the item into the node
5083 node.children.push(item);
5086 // split on node overflow; propagate upwards if necessary
5087 while (level >= 0) {
5088 if (insertPath[level].children.length > this._maxEntries) {
5089 this._split(insertPath, level);
5094 // adjust bboxes along the insertion path
5095 this._adjustParentBBoxes(bbox, insertPath, level);
5098 // split overflowed node into two
5099 _split: function (insertPath, level) {
5101 var node = insertPath[level],
5102 M = node.children.length,
5103 m = this._minEntries;
5105 this._chooseSplitAxis(node, m, M);
5107 var splitIndex = this._chooseSplitIndex(node, m, M);
5109 var newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex));
5110 newNode.height = node.height;
5111 newNode.leaf = node.leaf;
5113 calcBBox(node, this.toBBox);
5114 calcBBox(newNode, this.toBBox);
5116 if (level) insertPath[level - 1].children.push(newNode);
5117 else this._splitRoot(node, newNode);
5120 _splitRoot: function (node, newNode) {
5122 this.data = createNode([node, newNode]);
5123 this.data.height = node.height + 1;
5124 this.data.leaf = false;
5125 calcBBox(this.data, this.toBBox);
5128 _chooseSplitIndex: function (node, m, M) {
5130 var i, bbox1, bbox2, overlap, area, minOverlap, minArea, index;
5132 minOverlap = minArea = Infinity;
5134 for (i = m; i <= M - m; i++) {
5135 bbox1 = distBBox(node, 0, i, this.toBBox);
5136 bbox2 = distBBox(node, i, M, this.toBBox);
5138 overlap = intersectionArea(bbox1, bbox2);
5139 area = bboxArea(bbox1) + bboxArea(bbox2);
5141 // choose distribution with minimum overlap
5142 if (overlap < minOverlap) {
5143 minOverlap = overlap;
5146 minArea = area < minArea ? area : minArea;
5148 } else if (overlap === minOverlap) {
5149 // otherwise choose distribution with minimum area
5150 if (area < minArea) {
5160 // sorts node children by the best axis for split
5161 _chooseSplitAxis: function (node, m, M) {
5163 var compareMinX = node.leaf ? this.compareMinX : compareNodeMinX,
5164 compareMinY = node.leaf ? this.compareMinY : compareNodeMinY,
5165 xMargin = this._allDistMargin(node, m, M, compareMinX),
5166 yMargin = this._allDistMargin(node, m, M, compareMinY);
5168 // if total distributions margin value is minimal for x, sort by minX,
5169 // otherwise it's already sorted by minY
5170 if (xMargin < yMargin) node.children.sort(compareMinX);
5173 // total margin of all possible split distributions where each node is at least m full
5174 _allDistMargin: function (node, m, M, compare) {
5176 node.children.sort(compare);
5178 var toBBox = this.toBBox,
5179 leftBBox = distBBox(node, 0, m, toBBox),
5180 rightBBox = distBBox(node, M - m, M, toBBox),
5181 margin = bboxMargin(leftBBox) + bboxMargin(rightBBox),
5184 for (i = m; i < M - m; i++) {
5185 child = node.children[i];
5186 extend(leftBBox, node.leaf ? toBBox(child) : child);
5187 margin += bboxMargin(leftBBox);
5190 for (i = M - m - 1; i >= m; i--) {
5191 child = node.children[i];
5192 extend(rightBBox, node.leaf ? toBBox(child) : child);
5193 margin += bboxMargin(rightBBox);
5199 _adjustParentBBoxes: function (bbox, path, level) {
5200 // adjust bboxes along the given tree path
5201 for (var i = level; i >= 0; i--) {
5202 extend(path[i], bbox);
5206 _condense: function (path) {
5207 // go through the path, removing empty nodes and updating bboxes
5208 for (var i = path.length - 1, siblings; i >= 0; i--) {
5209 if (path[i].children.length === 0) {
5211 siblings = path[i - 1].children;
5212 siblings.splice(siblings.indexOf(path[i]), 1);
5214 } else this.clear();
5216 } else calcBBox(path[i], this.toBBox);
5220 _initFormat: function (format) {
5221 // data format (minX, minY, maxX, maxY accessors)
5223 // uses eval-type function compilation instead of just accepting a toBBox function
5224 // because the algorithms are very sensitive to sorting functions performance,
5225 // so they should be dead simple and without inner calls
5227 var compareArr = ['return a', ' - b', ';'];
5229 this.compareMinX = new Function('a', 'b', compareArr.join(format[0]));
5230 this.compareMinY = new Function('a', 'b', compareArr.join(format[1]));
5232 this.toBBox = new Function('a',
5233 'return {minX: a' + format[0] +
5234 ', minY: a' + format[1] +
5235 ', maxX: a' + format[2] +
5236 ', maxY: a' + format[3] + '};');
5240 function findItem(item, items, equalsFn) {
5241 if (!equalsFn) return items.indexOf(item);
5243 for (var i = 0; i < items.length; i++) {
5244 if (equalsFn(item, items[i])) return i;
5249 // calculate node's bbox from bboxes of its children
5250 function calcBBox(node, toBBox) {
5251 distBBox(node, 0, node.children.length, toBBox, node);
5254 // min bounding rectangle of node children from k to p-1
5255 function distBBox(node, k, p, toBBox, destNode) {
5256 if (!destNode) destNode = createNode(null);
5257 destNode.minX = Infinity;
5258 destNode.minY = Infinity;
5259 destNode.maxX = -Infinity;
5260 destNode.maxY = -Infinity;
5262 for (var i = k, child; i < p; i++) {
5263 child = node.children[i];
5264 extend(destNode, node.leaf ? toBBox(child) : child);
5270 function extend(a, b) {
5271 a.minX = Math.min(a.minX, b.minX);
5272 a.minY = Math.min(a.minY, b.minY);
5273 a.maxX = Math.max(a.maxX, b.maxX);
5274 a.maxY = Math.max(a.maxY, b.maxY);
5278 function compareNodeMinX(a, b) { return a.minX - b.minX; }
5279 function compareNodeMinY(a, b) { return a.minY - b.minY; }
5281 function bboxArea(a) { return (a.maxX - a.minX) * (a.maxY - a.minY); }
5282 function bboxMargin(a) { return (a.maxX - a.minX) + (a.maxY - a.minY); }
5284 function enlargedArea(a, b) {
5285 return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) *
5286 (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY));
5289 function intersectionArea(a, b) {
5290 var minX = Math.max(a.minX, b.minX),
5291 minY = Math.max(a.minY, b.minY),
5292 maxX = Math.min(a.maxX, b.maxX),
5293 maxY = Math.min(a.maxY, b.maxY);
5295 return Math.max(0, maxX - minX) *
5296 Math.max(0, maxY - minY);
5299 function contains(a, b) {
5300 return a.minX <= b.minX &&
5306 function intersects(a, b) {
5307 return b.minX <= a.maxX &&
5313 function createNode(children) {
5325 // sort an array so that items come in groups of n unsorted items, with groups sorted between each other;
5326 // combines selection algorithm with binary divide & conquer approach
5328 function multiSelect(arr, left, right, n, compare) {
5329 var stack = [left, right],
5332 while (stack.length) {
5333 right = stack.pop();
5336 if (right - left <= n) continue;
5338 mid = left + Math.ceil((right - left) / n / 2) * n;
5339 quickselect(arr, mid, left, right, compare);
5341 stack.push(left, mid, mid, right);
5345 },{"quickselect":24}],26:[function(require,module,exports){
5347 var __extends = (this && this.__extends) || function (d, b) {
5348 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5349 function __() { this.constructor = d; }
5350 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5352 var Subject_1 = require('./Subject');
5353 var ObjectUnsubscribedError_1 = require('./util/ObjectUnsubscribedError');
5355 * @class BehaviorSubject<T>
5357 var BehaviorSubject = (function (_super) {
5358 __extends(BehaviorSubject, _super);
5359 function BehaviorSubject(_value) {
5361 this._value = _value;
5363 Object.defineProperty(BehaviorSubject.prototype, "value", {
5365 return this.getValue();
5370 BehaviorSubject.prototype._subscribe = function (subscriber) {
5371 var subscription = _super.prototype._subscribe.call(this, subscriber);
5372 if (subscription && !subscription.closed) {
5373 subscriber.next(this._value);
5375 return subscription;
5377 BehaviorSubject.prototype.getValue = function () {
5378 if (this.hasError) {
5379 throw this.thrownError;
5381 else if (this.closed) {
5382 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5388 BehaviorSubject.prototype.next = function (value) {
5389 _super.prototype.next.call(this, this._value = value);
5391 return BehaviorSubject;
5392 }(Subject_1.Subject));
5393 exports.BehaviorSubject = BehaviorSubject;
5395 },{"./Subject":34,"./util/ObjectUnsubscribedError":160}],27:[function(require,module,exports){
5397 var __extends = (this && this.__extends) || function (d, b) {
5398 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5399 function __() { this.constructor = d; }
5400 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5402 var Subscriber_1 = require('./Subscriber');
5404 * We need this JSDoc comment for affecting ESDoc.
5406 * @extends {Ignored}
5408 var InnerSubscriber = (function (_super) {
5409 __extends(InnerSubscriber, _super);
5410 function InnerSubscriber(parent, outerValue, outerIndex) {
5412 this.parent = parent;
5413 this.outerValue = outerValue;
5414 this.outerIndex = outerIndex;
5417 InnerSubscriber.prototype._next = function (value) {
5418 this.parent.notifyNext(this.outerValue, value, this.outerIndex, this.index++, this);
5420 InnerSubscriber.prototype._error = function (error) {
5421 this.parent.notifyError(error, this);
5424 InnerSubscriber.prototype._complete = function () {
5425 this.parent.notifyComplete(this);
5428 return InnerSubscriber;
5429 }(Subscriber_1.Subscriber));
5430 exports.InnerSubscriber = InnerSubscriber;
5432 },{"./Subscriber":36}],28:[function(require,module,exports){
5434 var Observable_1 = require('./Observable');
5436 * Represents a push-based event or value that an {@link Observable} can emit.
5437 * This class is particularly useful for operators that manage notifications,
5438 * like {@link materialize}, {@link dematerialize}, {@link observeOn}, and
5439 * others. Besides wrapping the actual delivered value, it also annotates it
5440 * with metadata of, for instance, what type of push message it is (`next`,
5441 * `error`, or `complete`).
5443 * @see {@link materialize}
5444 * @see {@link dematerialize}
5445 * @see {@link observeOn}
5447 * @class Notification<T>
5449 var Notification = (function () {
5450 function Notification(kind, value, error) {
5454 this.hasValue = kind === 'N';
5457 * Delivers to the given `observer` the value wrapped by this Notification.
5458 * @param {Observer} observer
5461 Notification.prototype.observe = function (observer) {
5462 switch (this.kind) {
5464 return observer.next && observer.next(this.value);
5466 return observer.error && observer.error(this.error);
5468 return observer.complete && observer.complete();
5472 * Given some {@link Observer} callbacks, deliver the value represented by the
5473 * current Notification to the correctly corresponding callback.
5474 * @param {function(value: T): void} next An Observer `next` callback.
5475 * @param {function(err: any): void} [error] An Observer `error` callback.
5476 * @param {function(): void} [complete] An Observer `complete` callback.
5479 Notification.prototype.do = function (next, error, complete) {
5480 var kind = this.kind;
5483 return next && next(this.value);
5485 return error && error(this.error);
5487 return complete && complete();
5491 * Takes an Observer or its individual callback functions, and calls `observe`
5492 * or `do` methods accordingly.
5493 * @param {Observer|function(value: T): void} nextOrObserver An Observer or
5494 * the `next` callback.
5495 * @param {function(err: any): void} [error] An Observer `error` callback.
5496 * @param {function(): void} [complete] An Observer `complete` callback.
5499 Notification.prototype.accept = function (nextOrObserver, error, complete) {
5500 if (nextOrObserver && typeof nextOrObserver.next === 'function') {
5501 return this.observe(nextOrObserver);
5504 return this.do(nextOrObserver, error, complete);
5508 * Returns a simple Observable that just delivers the notification represented
5509 * by this Notification instance.
5512 Notification.prototype.toObservable = function () {
5513 var kind = this.kind;
5516 return Observable_1.Observable.of(this.value);
5518 return Observable_1.Observable.throw(this.error);
5520 return Observable_1.Observable.empty();
5522 throw new Error('unexpected notification kind value');
5525 * A shortcut to create a Notification instance of the type `next` from a
5527 * @param {T} value The `next` value.
5528 * @return {Notification<T>} The "next" Notification representing the
5531 Notification.createNext = function (value) {
5532 if (typeof value !== 'undefined') {
5533 return new Notification('N', value);
5535 return Notification.undefinedValueNotification;
5538 * A shortcut to create a Notification instance of the type `error` from a
5540 * @param {any} [err] The `error` error.
5541 * @return {Notification<T>} The "error" Notification representing the
5544 Notification.createError = function (err) {
5545 return new Notification('E', undefined, err);
5548 * A shortcut to create a Notification instance of the type `complete`.
5549 * @return {Notification<any>} The valueless "complete" Notification.
5551 Notification.createComplete = function () {
5552 return Notification.completeNotification;
5554 Notification.completeNotification = new Notification('C');
5555 Notification.undefinedValueNotification = new Notification('N', undefined);
5556 return Notification;
5558 exports.Notification = Notification;
5560 },{"./Observable":29}],29:[function(require,module,exports){
5562 var root_1 = require('./util/root');
5563 var toSubscriber_1 = require('./util/toSubscriber');
5564 var observable_1 = require('./symbol/observable');
5566 * A representation of any set of values over any amount of time. This the most basic building block
5569 * @class Observable<T>
5571 var Observable = (function () {
5574 * @param {Function} subscribe the function that is called when the Observable is
5575 * initially subscribed to. This function is given a Subscriber, to which new values
5576 * can be `next`ed, or an `error` method can be called to raise an error, or
5577 * `complete` can be called to notify of a successful completion.
5579 function Observable(subscribe) {
5580 this._isScalar = false;
5582 this._subscribe = subscribe;
5586 * Creates a new Observable, with this Observable as the source, and the passed
5587 * operator defined as the new observable's operator.
5589 * @param {Operator} operator the operator defining the operation to take on the observable
5590 * @return {Observable} a new observable with the Operator applied
5592 Observable.prototype.lift = function (operator) {
5593 var observable = new Observable();
5594 observable.source = this;
5595 observable.operator = operator;
5599 * Invokes an execution of an Observable and registers Observer handlers for notifications it will emit.
5601 * <span class="informal">Use it when you have all these Observables, but still nothing is happening.</span>
5603 * `subscribe` is not a regular operator, but a method that calls Observables internal `subscribe` function. It
5604 * might be for example a function that you passed to a {@link create} static factory, but most of the time it is
5605 * a library implementation, which defines what and when will be emitted by an Observable. This means that calling
5606 * `subscribe` is actually the moment when Observable starts its work, not when it is created, as it is often
5609 * Apart from starting the execution of an Observable, this method allows you to listen for values
5610 * that an Observable emits, as well as for when it completes or errors. You can achieve this in two
5613 * The first way is creating an object that implements {@link Observer} interface. It should have methods
5614 * defined by that interface, but note that it should be just a regular JavaScript object, which you can create
5615 * yourself in any way you want (ES6 class, classic function constructor, object literal etc.). In particular do
5616 * not attempt to use any RxJS implementation details to create Observers - you don't need them. Remember also
5617 * that your object does not have to implement all methods. If you find yourself creating a method that doesn't
5618 * do anything, you can simply omit it. Note however, that if `error` method is not provided, all errors will
5621 * The second way is to give up on Observer object altogether and simply provide callback functions in place of its methods.
5622 * This means you can provide three functions as arguments to `subscribe`, where first function is equivalent
5623 * of a `next` method, second of an `error` method and third of a `complete` method. Just as in case of Observer,
5624 * if you do not need to listen for something, you can omit a function, preferably by passing `undefined` or `null`,
5625 * since `subscribe` recognizes these functions by where they were placed in function call. When it comes
5626 * to `error` function, just as before, if not provided, errors emitted by an Observable will be thrown.
5628 * Whatever style of calling `subscribe` you use, in both cases it returns a Subscription object.
5629 * This object allows you to call `unsubscribe` on it, which in turn will stop work that an Observable does and will clean
5630 * up all resources that an Observable used. Note that cancelling a subscription will not call `complete` callback
5631 * provided to `subscribe` function, which is reserved for a regular completion signal that comes from an Observable.
5633 * Remember that callbacks provided to `subscribe` are not guaranteed to be called asynchronously.
5634 * It is an Observable itself that decides when these functions will be called. For example {@link of}
5635 * by default emits all its values synchronously. Always check documentation for how given Observable
5636 * will behave when subscribed and if its default behavior can be modified with a {@link Scheduler}.
5638 * @example <caption>Subscribe with an Observer</caption>
5639 * const sumObserver = {
5642 * console.log('Adding: ' + value);
5643 * this.sum = this.sum + value;
5645 * error() { // We actually could just remote this method,
5646 * }, // since we do not really care about errors right now.
5648 * console.log('Sum equals: ' + this.sum);
5652 * Rx.Observable.of(1, 2, 3) // Synchronously emits 1, 2, 3 and then completes.
5653 * .subscribe(sumObserver);
5659 * // "Sum equals: 6"
5662 * @example <caption>Subscribe with functions</caption>
5665 * Rx.Observable.of(1, 2, 3)
5668 * console.log('Adding: ' + value);
5669 * sum = sum + value;
5673 * console.log('Sum equals: ' + sum);
5681 * // "Sum equals: 6"
5684 * @example <caption>Cancel a subscription</caption>
5685 * const subscription = Rx.Observable.interval(1000).subscribe(
5686 * num => console.log(num),
5688 * () => console.log('completed!') // Will not be called, even
5689 * ); // when cancelling subscription
5692 * setTimeout(() => {
5693 * subscription.unsubscribe();
5694 * console.log('unsubscribed!');
5700 * // "unsubscribed!" after 2,5s
5703 * @param {Observer|Function} observerOrNext (optional) Either an observer with methods to be called,
5704 * or the first of three possible handlers, which is the handler for each value emitted from the subscribed
5706 * @param {Function} error (optional) A handler for a terminal event resulting from an error. If no error handler is provided,
5707 * the error will be thrown as unhandled.
5708 * @param {Function} complete (optional) A handler for a terminal event resulting from successful completion.
5709 * @return {ISubscription} a subscription reference to the registered handlers
5712 Observable.prototype.subscribe = function (observerOrNext, error, complete) {
5713 var operator = this.operator;
5714 var sink = toSubscriber_1.toSubscriber(observerOrNext, error, complete);
5716 operator.call(sink, this.source);
5719 sink.add(this.source ? this._subscribe(sink) : this._trySubscribe(sink));
5721 if (sink.syncErrorThrowable) {
5722 sink.syncErrorThrowable = false;
5723 if (sink.syncErrorThrown) {
5724 throw sink.syncErrorValue;
5729 Observable.prototype._trySubscribe = function (sink) {
5731 return this._subscribe(sink);
5734 sink.syncErrorThrown = true;
5735 sink.syncErrorValue = err;
5741 * @param {Function} next a handler for each value emitted by the observable
5742 * @param {PromiseConstructor} [PromiseCtor] a constructor function used to instantiate the Promise
5743 * @return {Promise} a promise that either resolves on observable completion or
5744 * rejects with the handled error
5746 Observable.prototype.forEach = function (next, PromiseCtor) {
5749 if (root_1.root.Rx && root_1.root.Rx.config && root_1.root.Rx.config.Promise) {
5750 PromiseCtor = root_1.root.Rx.config.Promise;
5752 else if (root_1.root.Promise) {
5753 PromiseCtor = root_1.root.Promise;
5757 throw new Error('no Promise impl found');
5759 return new PromiseCtor(function (resolve, reject) {
5760 // Must be declared in a separate statement to avoid a RefernceError when
5761 // accessing subscription below in the closure due to Temporal Dead Zone.
5763 subscription = _this.subscribe(function (value) {
5765 // if there is a subscription, then we can surmise
5766 // the next handling is asynchronous. Any errors thrown
5767 // need to be rejected explicitly and unsubscribe must be
5774 subscription.unsubscribe();
5778 // if there is NO subscription, then we're getting a nexted
5779 // value synchronously during subscription. We can just call it.
5780 // If it errors, Observable's `subscribe` will ensure the
5781 // unsubscription logic is called, then synchronously rethrow the error.
5782 // After that, Promise will trap the error and send it
5783 // down the rejection path.
5786 }, reject, resolve);
5789 Observable.prototype._subscribe = function (subscriber) {
5790 return this.source.subscribe(subscriber);
5793 * An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable
5794 * @method Symbol.observable
5795 * @return {Observable} this instance of the observable
5797 Observable.prototype[observable_1.observable] = function () {
5800 // HACK: Since TypeScript inherits static properties too, we have to
5801 // fight against TypeScript here so Subject can have a different static create signature
5803 * Creates a new cold Observable by calling the Observable constructor
5807 * @param {Function} subscribe? the subscriber function to be passed to the Observable constructor
5808 * @return {Observable} a new cold observable
5810 Observable.create = function (subscribe) {
5811 return new Observable(subscribe);
5815 exports.Observable = Observable;
5817 },{"./symbol/observable":155,"./util/root":172,"./util/toSubscriber":174}],30:[function(require,module,exports){
5821 next: function (value) { },
5822 error: function (err) { throw err; },
5823 complete: function () { }
5826 },{}],31:[function(require,module,exports){
5828 var __extends = (this && this.__extends) || function (d, b) {
5829 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5830 function __() { this.constructor = d; }
5831 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5833 var Subscriber_1 = require('./Subscriber');
5835 * We need this JSDoc comment for affecting ESDoc.
5837 * @extends {Ignored}
5839 var OuterSubscriber = (function (_super) {
5840 __extends(OuterSubscriber, _super);
5841 function OuterSubscriber() {
5842 _super.apply(this, arguments);
5844 OuterSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
5845 this.destination.next(innerValue);
5847 OuterSubscriber.prototype.notifyError = function (error, innerSub) {
5848 this.destination.error(error);
5850 OuterSubscriber.prototype.notifyComplete = function (innerSub) {
5851 this.destination.complete();
5853 return OuterSubscriber;
5854 }(Subscriber_1.Subscriber));
5855 exports.OuterSubscriber = OuterSubscriber;
5857 },{"./Subscriber":36}],32:[function(require,module,exports){
5859 var __extends = (this && this.__extends) || function (d, b) {
5860 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5861 function __() { this.constructor = d; }
5862 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5864 var Subject_1 = require('./Subject');
5865 var queue_1 = require('./scheduler/queue');
5866 var Subscription_1 = require('./Subscription');
5867 var observeOn_1 = require('./operator/observeOn');
5868 var ObjectUnsubscribedError_1 = require('./util/ObjectUnsubscribedError');
5869 var SubjectSubscription_1 = require('./SubjectSubscription');
5871 * @class ReplaySubject<T>
5873 var ReplaySubject = (function (_super) {
5874 __extends(ReplaySubject, _super);
5875 function ReplaySubject(bufferSize, windowTime, scheduler) {
5876 if (bufferSize === void 0) { bufferSize = Number.POSITIVE_INFINITY; }
5877 if (windowTime === void 0) { windowTime = Number.POSITIVE_INFINITY; }
5879 this.scheduler = scheduler;
5881 this._bufferSize = bufferSize < 1 ? 1 : bufferSize;
5882 this._windowTime = windowTime < 1 ? 1 : windowTime;
5884 ReplaySubject.prototype.next = function (value) {
5885 var now = this._getNow();
5886 this._events.push(new ReplayEvent(now, value));
5887 this._trimBufferThenGetEvents();
5888 _super.prototype.next.call(this, value);
5890 ReplaySubject.prototype._subscribe = function (subscriber) {
5891 var _events = this._trimBufferThenGetEvents();
5892 var scheduler = this.scheduler;
5895 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5897 else if (this.hasError) {
5898 subscription = Subscription_1.Subscription.EMPTY;
5900 else if (this.isStopped) {
5901 subscription = Subscription_1.Subscription.EMPTY;
5904 this.observers.push(subscriber);
5905 subscription = new SubjectSubscription_1.SubjectSubscription(this, subscriber);
5908 subscriber.add(subscriber = new observeOn_1.ObserveOnSubscriber(subscriber, scheduler));
5910 var len = _events.length;
5911 for (var i = 0; i < len && !subscriber.closed; i++) {
5912 subscriber.next(_events[i].value);
5914 if (this.hasError) {
5915 subscriber.error(this.thrownError);
5917 else if (this.isStopped) {
5918 subscriber.complete();
5920 return subscription;
5922 ReplaySubject.prototype._getNow = function () {
5923 return (this.scheduler || queue_1.queue).now();
5925 ReplaySubject.prototype._trimBufferThenGetEvents = function () {
5926 var now = this._getNow();
5927 var _bufferSize = this._bufferSize;
5928 var _windowTime = this._windowTime;
5929 var _events = this._events;
5930 var eventsCount = _events.length;
5931 var spliceCount = 0;
5932 // Trim events that fall out of the time window.
5933 // Start at the front of the list. Break early once
5934 // we encounter an event that falls within the window.
5935 while (spliceCount < eventsCount) {
5936 if ((now - _events[spliceCount].time) < _windowTime) {
5941 if (eventsCount > _bufferSize) {
5942 spliceCount = Math.max(spliceCount, eventsCount - _bufferSize);
5944 if (spliceCount > 0) {
5945 _events.splice(0, spliceCount);
5949 return ReplaySubject;
5950 }(Subject_1.Subject));
5951 exports.ReplaySubject = ReplaySubject;
5952 var ReplayEvent = (function () {
5953 function ReplayEvent(time, value) {
5960 },{"./Subject":34,"./SubjectSubscription":35,"./Subscription":37,"./operator/observeOn":129,"./scheduler/queue":153,"./util/ObjectUnsubscribedError":160}],33:[function(require,module,exports){
5963 * An execution context and a data structure to order tasks and schedule their
5964 * execution. Provides a notion of (potentially virtual) time, through the
5965 * `now()` getter method.
5967 * Each unit of work in a Scheduler is called an {@link Action}.
5972 * schedule(work, delay?, state?): Subscription;
5978 var Scheduler = (function () {
5979 function Scheduler(SchedulerAction, now) {
5980 if (now === void 0) { now = Scheduler.now; }
5981 this.SchedulerAction = SchedulerAction;
5985 * Schedules a function, `work`, for execution. May happen at some point in
5986 * the future, according to the `delay` parameter, if specified. May be passed
5987 * some context object, `state`, which will be passed to the `work` function.
5989 * The given arguments will be processed an stored as an Action object in a
5992 * @param {function(state: ?T): ?Subscription} work A function representing a
5993 * task, or some unit of work to be executed by the Scheduler.
5994 * @param {number} [delay] Time to wait before executing the work, where the
5995 * time unit is implicit and defined by the Scheduler itself.
5996 * @param {T} [state] Some contextual data that the `work` function uses when
5997 * called by the Scheduler.
5998 * @return {Subscription} A subscription in order to be able to unsubscribe
5999 * the scheduled work.
6001 Scheduler.prototype.schedule = function (work, delay, state) {
6002 if (delay === void 0) { delay = 0; }
6003 return new this.SchedulerAction(this, work).schedule(state, delay);
6005 Scheduler.now = Date.now ? Date.now : function () { return +new Date(); };
6008 exports.Scheduler = Scheduler;
6010 },{}],34:[function(require,module,exports){
6012 var __extends = (this && this.__extends) || function (d, b) {
6013 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6014 function __() { this.constructor = d; }
6015 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6017 var Observable_1 = require('./Observable');
6018 var Subscriber_1 = require('./Subscriber');
6019 var Subscription_1 = require('./Subscription');
6020 var ObjectUnsubscribedError_1 = require('./util/ObjectUnsubscribedError');
6021 var SubjectSubscription_1 = require('./SubjectSubscription');
6022 var rxSubscriber_1 = require('./symbol/rxSubscriber');
6024 * @class SubjectSubscriber<T>
6026 var SubjectSubscriber = (function (_super) {
6027 __extends(SubjectSubscriber, _super);
6028 function SubjectSubscriber(destination) {
6029 _super.call(this, destination);
6030 this.destination = destination;
6032 return SubjectSubscriber;
6033 }(Subscriber_1.Subscriber));
6034 exports.SubjectSubscriber = SubjectSubscriber;
6038 var Subject = (function (_super) {
6039 __extends(Subject, _super);
6040 function Subject() {
6042 this.observers = [];
6043 this.closed = false;
6044 this.isStopped = false;
6045 this.hasError = false;
6046 this.thrownError = null;
6048 Subject.prototype[rxSubscriber_1.rxSubscriber] = function () {
6049 return new SubjectSubscriber(this);
6051 Subject.prototype.lift = function (operator) {
6052 var subject = new AnonymousSubject(this, this);
6053 subject.operator = operator;
6056 Subject.prototype.next = function (value) {
6058 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6060 if (!this.isStopped) {
6061 var observers = this.observers;
6062 var len = observers.length;
6063 var copy = observers.slice();
6064 for (var i = 0; i < len; i++) {
6065 copy[i].next(value);
6069 Subject.prototype.error = function (err) {
6071 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6073 this.hasError = true;
6074 this.thrownError = err;
6075 this.isStopped = true;
6076 var observers = this.observers;
6077 var len = observers.length;
6078 var copy = observers.slice();
6079 for (var i = 0; i < len; i++) {
6082 this.observers.length = 0;
6084 Subject.prototype.complete = function () {
6086 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6088 this.isStopped = true;
6089 var observers = this.observers;
6090 var len = observers.length;
6091 var copy = observers.slice();
6092 for (var i = 0; i < len; i++) {
6095 this.observers.length = 0;
6097 Subject.prototype.unsubscribe = function () {
6098 this.isStopped = true;
6100 this.observers = null;
6102 Subject.prototype._trySubscribe = function (subscriber) {
6104 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6107 return _super.prototype._trySubscribe.call(this, subscriber);
6110 Subject.prototype._subscribe = function (subscriber) {
6112 throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6114 else if (this.hasError) {
6115 subscriber.error(this.thrownError);
6116 return Subscription_1.Subscription.EMPTY;
6118 else if (this.isStopped) {
6119 subscriber.complete();
6120 return Subscription_1.Subscription.EMPTY;
6123 this.observers.push(subscriber);
6124 return new SubjectSubscription_1.SubjectSubscription(this, subscriber);
6127 Subject.prototype.asObservable = function () {
6128 var observable = new Observable_1.Observable();
6129 observable.source = this;
6132 Subject.create = function (destination, source) {
6133 return new AnonymousSubject(destination, source);
6136 }(Observable_1.Observable));
6137 exports.Subject = Subject;
6139 * @class AnonymousSubject<T>
6141 var AnonymousSubject = (function (_super) {
6142 __extends(AnonymousSubject, _super);
6143 function AnonymousSubject(destination, source) {
6145 this.destination = destination;
6146 this.source = source;
6148 AnonymousSubject.prototype.next = function (value) {
6149 var destination = this.destination;
6150 if (destination && destination.next) {
6151 destination.next(value);
6154 AnonymousSubject.prototype.error = function (err) {
6155 var destination = this.destination;
6156 if (destination && destination.error) {
6157 this.destination.error(err);
6160 AnonymousSubject.prototype.complete = function () {
6161 var destination = this.destination;
6162 if (destination && destination.complete) {
6163 this.destination.complete();
6166 AnonymousSubject.prototype._subscribe = function (subscriber) {
6167 var source = this.source;
6169 return this.source.subscribe(subscriber);
6172 return Subscription_1.Subscription.EMPTY;
6175 return AnonymousSubject;
6177 exports.AnonymousSubject = AnonymousSubject;
6179 },{"./Observable":29,"./SubjectSubscription":35,"./Subscriber":36,"./Subscription":37,"./symbol/rxSubscriber":156,"./util/ObjectUnsubscribedError":160}],35:[function(require,module,exports){
6181 var __extends = (this && this.__extends) || function (d, b) {
6182 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6183 function __() { this.constructor = d; }
6184 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6186 var Subscription_1 = require('./Subscription');
6188 * We need this JSDoc comment for affecting ESDoc.
6190 * @extends {Ignored}
6192 var SubjectSubscription = (function (_super) {
6193 __extends(SubjectSubscription, _super);
6194 function SubjectSubscription(subject, subscriber) {
6196 this.subject = subject;
6197 this.subscriber = subscriber;
6198 this.closed = false;
6200 SubjectSubscription.prototype.unsubscribe = function () {
6205 var subject = this.subject;
6206 var observers = subject.observers;
6207 this.subject = null;
6208 if (!observers || observers.length === 0 || subject.isStopped || subject.closed) {
6211 var subscriberIndex = observers.indexOf(this.subscriber);
6212 if (subscriberIndex !== -1) {
6213 observers.splice(subscriberIndex, 1);
6216 return SubjectSubscription;
6217 }(Subscription_1.Subscription));
6218 exports.SubjectSubscription = SubjectSubscription;
6220 },{"./Subscription":37}],36:[function(require,module,exports){
6222 var __extends = (this && this.__extends) || function (d, b) {
6223 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6224 function __() { this.constructor = d; }
6225 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6227 var isFunction_1 = require('./util/isFunction');
6228 var Subscription_1 = require('./Subscription');
6229 var Observer_1 = require('./Observer');
6230 var rxSubscriber_1 = require('./symbol/rxSubscriber');
6232 * Implements the {@link Observer} interface and extends the
6233 * {@link Subscription} class. While the {@link Observer} is the public API for
6234 * consuming the values of an {@link Observable}, all Observers get converted to
6235 * a Subscriber, in order to provide Subscription-like capabilities such as
6236 * `unsubscribe`. Subscriber is a common type in RxJS, and crucial for
6237 * implementing operators, but it is rarely used as a public API.
6239 * @class Subscriber<T>
6241 var Subscriber = (function (_super) {
6242 __extends(Subscriber, _super);
6244 * @param {Observer|function(value: T): void} [destinationOrNext] A partially
6245 * defined Observer or a `next` callback function.
6246 * @param {function(e: ?any): void} [error] The `error` callback of an
6248 * @param {function(): void} [complete] The `complete` callback of an
6251 function Subscriber(destinationOrNext, error, complete) {
6253 this.syncErrorValue = null;
6254 this.syncErrorThrown = false;
6255 this.syncErrorThrowable = false;
6256 this.isStopped = false;
6257 switch (arguments.length) {
6259 this.destination = Observer_1.empty;
6262 if (!destinationOrNext) {
6263 this.destination = Observer_1.empty;
6266 if (typeof destinationOrNext === 'object') {
6267 if (destinationOrNext instanceof Subscriber) {
6268 this.destination = destinationOrNext;
6269 this.destination.add(this);
6272 this.syncErrorThrowable = true;
6273 this.destination = new SafeSubscriber(this, destinationOrNext);
6278 this.syncErrorThrowable = true;
6279 this.destination = new SafeSubscriber(this, destinationOrNext, error, complete);
6283 Subscriber.prototype[rxSubscriber_1.rxSubscriber] = function () { return this; };
6285 * A static factory for a Subscriber, given a (potentially partial) definition
6287 * @param {function(x: ?T): void} [next] The `next` callback of an Observer.
6288 * @param {function(e: ?any): void} [error] The `error` callback of an
6290 * @param {function(): void} [complete] The `complete` callback of an
6292 * @return {Subscriber<T>} A Subscriber wrapping the (partially defined)
6293 * Observer represented by the given arguments.
6295 Subscriber.create = function (next, error, complete) {
6296 var subscriber = new Subscriber(next, error, complete);
6297 subscriber.syncErrorThrowable = false;
6301 * The {@link Observer} callback to receive notifications of type `next` from
6302 * the Observable, with a value. The Observable may call this method 0 or more
6304 * @param {T} [value] The `next` value.
6307 Subscriber.prototype.next = function (value) {
6308 if (!this.isStopped) {
6313 * The {@link Observer} callback to receive notifications of type `error` from
6314 * the Observable, with an attached {@link Error}. Notifies the Observer that
6315 * the Observable has experienced an error condition.
6316 * @param {any} [err] The `error` exception.
6319 Subscriber.prototype.error = function (err) {
6320 if (!this.isStopped) {
6321 this.isStopped = true;
6326 * The {@link Observer} callback to receive a valueless notification of type
6327 * `complete` from the Observable. Notifies the Observer that the Observable
6328 * has finished sending push-based notifications.
6331 Subscriber.prototype.complete = function () {
6332 if (!this.isStopped) {
6333 this.isStopped = true;
6337 Subscriber.prototype.unsubscribe = function () {
6341 this.isStopped = true;
6342 _super.prototype.unsubscribe.call(this);
6344 Subscriber.prototype._next = function (value) {
6345 this.destination.next(value);
6347 Subscriber.prototype._error = function (err) {
6348 this.destination.error(err);
6351 Subscriber.prototype._complete = function () {
6352 this.destination.complete();
6355 Subscriber.prototype._unsubscribeAndRecycle = function () {
6356 var _a = this, _parent = _a._parent, _parents = _a._parents;
6357 this._parent = null;
6358 this._parents = null;
6360 this.closed = false;
6361 this.isStopped = false;
6362 this._parent = _parent;
6363 this._parents = _parents;
6367 }(Subscription_1.Subscription));
6368 exports.Subscriber = Subscriber;
6370 * We need this JSDoc comment for affecting ESDoc.
6372 * @extends {Ignored}
6374 var SafeSubscriber = (function (_super) {
6375 __extends(SafeSubscriber, _super);
6376 function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) {
6378 this._parentSubscriber = _parentSubscriber;
6381 if (isFunction_1.isFunction(observerOrNext)) {
6382 next = observerOrNext;
6384 else if (observerOrNext) {
6385 next = observerOrNext.next;
6386 error = observerOrNext.error;
6387 complete = observerOrNext.complete;
6388 if (observerOrNext !== Observer_1.empty) {
6389 context = Object.create(observerOrNext);
6390 if (isFunction_1.isFunction(context.unsubscribe)) {
6391 this.add(context.unsubscribe.bind(context));
6393 context.unsubscribe = this.unsubscribe.bind(this);
6396 this._context = context;
6398 this._error = error;
6399 this._complete = complete;
6401 SafeSubscriber.prototype.next = function (value) {
6402 if (!this.isStopped && this._next) {
6403 var _parentSubscriber = this._parentSubscriber;
6404 if (!_parentSubscriber.syncErrorThrowable) {
6405 this.__tryOrUnsub(this._next, value);
6407 else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {
6412 SafeSubscriber.prototype.error = function (err) {
6413 if (!this.isStopped) {
6414 var _parentSubscriber = this._parentSubscriber;
6416 if (!_parentSubscriber.syncErrorThrowable) {
6417 this.__tryOrUnsub(this._error, err);
6421 this.__tryOrSetError(_parentSubscriber, this._error, err);
6425 else if (!_parentSubscriber.syncErrorThrowable) {
6430 _parentSubscriber.syncErrorValue = err;
6431 _parentSubscriber.syncErrorThrown = true;
6436 SafeSubscriber.prototype.complete = function () {
6438 if (!this.isStopped) {
6439 var _parentSubscriber = this._parentSubscriber;
6440 if (this._complete) {
6441 var wrappedComplete = function () { return _this._complete.call(_this._context); };
6442 if (!_parentSubscriber.syncErrorThrowable) {
6443 this.__tryOrUnsub(wrappedComplete);
6447 this.__tryOrSetError(_parentSubscriber, wrappedComplete);
6456 SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) {
6458 fn.call(this._context, value);
6465 SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) {
6467 fn.call(this._context, value);
6470 parent.syncErrorValue = err;
6471 parent.syncErrorThrown = true;
6476 SafeSubscriber.prototype._unsubscribe = function () {
6477 var _parentSubscriber = this._parentSubscriber;
6478 this._context = null;
6479 this._parentSubscriber = null;
6480 _parentSubscriber.unsubscribe();
6482 return SafeSubscriber;
6485 },{"./Observer":30,"./Subscription":37,"./symbol/rxSubscriber":156,"./util/isFunction":167}],37:[function(require,module,exports){
6487 var isArray_1 = require('./util/isArray');
6488 var isObject_1 = require('./util/isObject');
6489 var isFunction_1 = require('./util/isFunction');
6490 var tryCatch_1 = require('./util/tryCatch');
6491 var errorObject_1 = require('./util/errorObject');
6492 var UnsubscriptionError_1 = require('./util/UnsubscriptionError');
6494 * Represents a disposable resource, such as the execution of an Observable. A
6495 * Subscription has one important method, `unsubscribe`, that takes no argument
6496 * and just disposes the resource held by the subscription.
6498 * Additionally, subscriptions may be grouped together through the `add()`
6499 * method, which will attach a child Subscription to the current Subscription.
6500 * When a Subscription is unsubscribed, all its children (and its grandchildren)
6501 * will be unsubscribed as well.
6503 * @class Subscription
6505 var Subscription = (function () {
6507 * @param {function(): void} [unsubscribe] A function describing how to
6508 * perform the disposal of resources when the `unsubscribe` method is called.
6510 function Subscription(unsubscribe) {
6512 * A flag to indicate whether this Subscription has already been unsubscribed.
6515 this.closed = false;
6516 this._parent = null;
6517 this._parents = null;
6518 this._subscriptions = null;
6520 this._unsubscribe = unsubscribe;
6524 * Disposes the resources held by the subscription. May, for instance, cancel
6525 * an ongoing Observable execution or cancel any other type of work that
6526 * started when the Subscription was created.
6529 Subscription.prototype.unsubscribe = function () {
6530 var hasErrors = false;
6535 var _a = this, _parent = _a._parent, _parents = _a._parents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions;
6537 this._parent = null;
6538 this._parents = null;
6539 // null out _subscriptions first so any child subscriptions that attempt
6540 // to remove themselves from this subscription will noop
6541 this._subscriptions = null;
6543 var len = _parents ? _parents.length : 0;
6544 // if this._parent is null, then so is this._parents, and we
6545 // don't have to remove ourselves from any parent subscriptions.
6547 _parent.remove(this);
6548 // if this._parents is null or index >= len,
6549 // then _parent is set to null, and the loop exits
6550 _parent = ++index < len && _parents[index] || null;
6552 if (isFunction_1.isFunction(_unsubscribe)) {
6553 var trial = tryCatch_1.tryCatch(_unsubscribe).call(this);
6554 if (trial === errorObject_1.errorObject) {
6556 errors = errors || (errorObject_1.errorObject.e instanceof UnsubscriptionError_1.UnsubscriptionError ?
6557 flattenUnsubscriptionErrors(errorObject_1.errorObject.e.errors) : [errorObject_1.errorObject.e]);
6560 if (isArray_1.isArray(_subscriptions)) {
6562 len = _subscriptions.length;
6563 while (++index < len) {
6564 var sub = _subscriptions[index];
6565 if (isObject_1.isObject(sub)) {
6566 var trial = tryCatch_1.tryCatch(sub.unsubscribe).call(sub);
6567 if (trial === errorObject_1.errorObject) {
6569 errors = errors || [];
6570 var err = errorObject_1.errorObject.e;
6571 if (err instanceof UnsubscriptionError_1.UnsubscriptionError) {
6572 errors = errors.concat(flattenUnsubscriptionErrors(err.errors));
6582 throw new UnsubscriptionError_1.UnsubscriptionError(errors);
6586 * Adds a tear down to be called during the unsubscribe() of this
6589 * If the tear down being added is a subscription that is already
6590 * unsubscribed, is the same reference `add` is being called on, or is
6591 * `Subscription.EMPTY`, it will not be added.
6593 * If this subscription is already in an `closed` state, the passed
6594 * tear down logic will be executed immediately.
6596 * @param {TeardownLogic} teardown The additional logic to execute on
6598 * @return {Subscription} Returns the Subscription used or created to be
6599 * added to the inner subscriptions list. This Subscription can be used with
6600 * `remove()` to remove the passed teardown logic from the inner subscriptions
6603 Subscription.prototype.add = function (teardown) {
6604 if (!teardown || (teardown === Subscription.EMPTY)) {
6605 return Subscription.EMPTY;
6607 if (teardown === this) {
6610 var subscription = teardown;
6611 switch (typeof teardown) {
6613 subscription = new Subscription(teardown);
6615 if (subscription.closed || typeof subscription.unsubscribe !== 'function') {
6616 return subscription;
6618 else if (this.closed) {
6619 subscription.unsubscribe();
6620 return subscription;
6622 else if (typeof subscription._addParent !== 'function' /* quack quack */) {
6623 var tmp = subscription;
6624 subscription = new Subscription();
6625 subscription._subscriptions = [tmp];
6629 throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');
6631 var subscriptions = this._subscriptions || (this._subscriptions = []);
6632 subscriptions.push(subscription);
6633 subscription._addParent(this);
6634 return subscription;
6637 * Removes a Subscription from the internal list of subscriptions that will
6638 * unsubscribe during the unsubscribe process of this Subscription.
6639 * @param {Subscription} subscription The subscription to remove.
6642 Subscription.prototype.remove = function (subscription) {
6643 var subscriptions = this._subscriptions;
6644 if (subscriptions) {
6645 var subscriptionIndex = subscriptions.indexOf(subscription);
6646 if (subscriptionIndex !== -1) {
6647 subscriptions.splice(subscriptionIndex, 1);
6651 Subscription.prototype._addParent = function (parent) {
6652 var _a = this, _parent = _a._parent, _parents = _a._parents;
6653 if (!_parent || _parent === parent) {
6654 // If we don't have a parent, or the new parent is the same as the
6655 // current parent, then set this._parent to the new parent.
6656 this._parent = parent;
6658 else if (!_parents) {
6659 // If there's already one parent, but not multiple, allocate an Array to
6660 // store the rest of the parent Subscriptions.
6661 this._parents = [parent];
6663 else if (_parents.indexOf(parent) === -1) {
6664 // Only add the new parent to the _parents list if it's not already there.
6665 _parents.push(parent);
6668 Subscription.EMPTY = (function (empty) {
6669 empty.closed = true;
6671 }(new Subscription()));
6672 return Subscription;
6674 exports.Subscription = Subscription;
6675 function flattenUnsubscriptionErrors(errors) {
6676 return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError_1.UnsubscriptionError) ? err.errors : err); }, []);
6679 },{"./util/UnsubscriptionError":162,"./util/errorObject":163,"./util/isArray":164,"./util/isFunction":167,"./util/isObject":169,"./util/tryCatch":175}],38:[function(require,module,exports){
6681 var Observable_1 = require('../../Observable');
6682 var combineLatest_1 = require('../../observable/combineLatest');
6683 Observable_1.Observable.combineLatest = combineLatest_1.combineLatest;
6685 },{"../../Observable":29,"../../observable/combineLatest":97}],39:[function(require,module,exports){
6687 var Observable_1 = require('../../Observable');
6688 var defer_1 = require('../../observable/defer');
6689 Observable_1.Observable.defer = defer_1.defer;
6691 },{"../../Observable":29,"../../observable/defer":98}],40:[function(require,module,exports){
6693 var Observable_1 = require('../../Observable');
6694 var empty_1 = require('../../observable/empty');
6695 Observable_1.Observable.empty = empty_1.empty;
6697 },{"../../Observable":29,"../../observable/empty":99}],41:[function(require,module,exports){
6699 var Observable_1 = require('../../Observable');
6700 var from_1 = require('../../observable/from');
6701 Observable_1.Observable.from = from_1.from;
6703 },{"../../Observable":29,"../../observable/from":100}],42:[function(require,module,exports){
6705 var Observable_1 = require('../../Observable');
6706 var fromEvent_1 = require('../../observable/fromEvent');
6707 Observable_1.Observable.fromEvent = fromEvent_1.fromEvent;
6709 },{"../../Observable":29,"../../observable/fromEvent":101}],43:[function(require,module,exports){
6711 var Observable_1 = require('../../Observable');
6712 var fromPromise_1 = require('../../observable/fromPromise');
6713 Observable_1.Observable.fromPromise = fromPromise_1.fromPromise;
6715 },{"../../Observable":29,"../../observable/fromPromise":102}],44:[function(require,module,exports){
6717 var Observable_1 = require('../../Observable');
6718 var merge_1 = require('../../observable/merge');
6719 Observable_1.Observable.merge = merge_1.merge;
6721 },{"../../Observable":29,"../../observable/merge":103}],45:[function(require,module,exports){
6723 var Observable_1 = require('../../Observable');
6724 var of_1 = require('../../observable/of');
6725 Observable_1.Observable.of = of_1.of;
6727 },{"../../Observable":29,"../../observable/of":104}],46:[function(require,module,exports){
6729 var Observable_1 = require('../../Observable');
6730 var throw_1 = require('../../observable/throw');
6731 Observable_1.Observable.throw = throw_1._throw;
6733 },{"../../Observable":29,"../../observable/throw":105}],47:[function(require,module,exports){
6735 var Observable_1 = require('../../Observable');
6736 var timer_1 = require('../../observable/timer');
6737 Observable_1.Observable.timer = timer_1.timer;
6739 },{"../../Observable":29,"../../observable/timer":106}],48:[function(require,module,exports){
6741 var Observable_1 = require('../../Observable');
6742 var zip_1 = require('../../observable/zip');
6743 Observable_1.Observable.zip = zip_1.zip;
6745 },{"../../Observable":29,"../../observable/zip":107}],49:[function(require,module,exports){
6747 var Observable_1 = require('../../Observable');
6748 var buffer_1 = require('../../operator/buffer');
6749 Observable_1.Observable.prototype.buffer = buffer_1.buffer;
6751 },{"../../Observable":29,"../../operator/buffer":108}],50:[function(require,module,exports){
6753 var Observable_1 = require('../../Observable');
6754 var bufferCount_1 = require('../../operator/bufferCount');
6755 Observable_1.Observable.prototype.bufferCount = bufferCount_1.bufferCount;
6757 },{"../../Observable":29,"../../operator/bufferCount":109}],51:[function(require,module,exports){
6759 var Observable_1 = require('../../Observable');
6760 var bufferWhen_1 = require('../../operator/bufferWhen');
6761 Observable_1.Observable.prototype.bufferWhen = bufferWhen_1.bufferWhen;
6763 },{"../../Observable":29,"../../operator/bufferWhen":110}],52:[function(require,module,exports){
6765 var Observable_1 = require('../../Observable');
6766 var catch_1 = require('../../operator/catch');
6767 Observable_1.Observable.prototype.catch = catch_1._catch;
6768 Observable_1.Observable.prototype._catch = catch_1._catch;
6770 },{"../../Observable":29,"../../operator/catch":111}],53:[function(require,module,exports){
6772 var Observable_1 = require('../../Observable');
6773 var combineLatest_1 = require('../../operator/combineLatest');
6774 Observable_1.Observable.prototype.combineLatest = combineLatest_1.combineLatest;
6776 },{"../../Observable":29,"../../operator/combineLatest":112}],54:[function(require,module,exports){
6778 var Observable_1 = require('../../Observable');
6779 var concat_1 = require('../../operator/concat');
6780 Observable_1.Observable.prototype.concat = concat_1.concat;
6782 },{"../../Observable":29,"../../operator/concat":113}],55:[function(require,module,exports){
6784 var Observable_1 = require('../../Observable');
6785 var debounceTime_1 = require('../../operator/debounceTime');
6786 Observable_1.Observable.prototype.debounceTime = debounceTime_1.debounceTime;
6788 },{"../../Observable":29,"../../operator/debounceTime":114}],56:[function(require,module,exports){
6790 var Observable_1 = require('../../Observable');
6791 var delay_1 = require('../../operator/delay');
6792 Observable_1.Observable.prototype.delay = delay_1.delay;
6794 },{"../../Observable":29,"../../operator/delay":115}],57:[function(require,module,exports){
6796 var Observable_1 = require('../../Observable');
6797 var distinct_1 = require('../../operator/distinct');
6798 Observable_1.Observable.prototype.distinct = distinct_1.distinct;
6800 },{"../../Observable":29,"../../operator/distinct":116}],58:[function(require,module,exports){
6802 var Observable_1 = require('../../Observable');
6803 var distinctUntilChanged_1 = require('../../operator/distinctUntilChanged');
6804 Observable_1.Observable.prototype.distinctUntilChanged = distinctUntilChanged_1.distinctUntilChanged;
6806 },{"../../Observable":29,"../../operator/distinctUntilChanged":117}],59:[function(require,module,exports){
6808 var Observable_1 = require('../../Observable');
6809 var do_1 = require('../../operator/do');
6810 Observable_1.Observable.prototype.do = do_1._do;
6811 Observable_1.Observable.prototype._do = do_1._do;
6813 },{"../../Observable":29,"../../operator/do":118}],60:[function(require,module,exports){
6815 var Observable_1 = require('../../Observable');
6816 var expand_1 = require('../../operator/expand');
6817 Observable_1.Observable.prototype.expand = expand_1.expand;
6819 },{"../../Observable":29,"../../operator/expand":119}],61:[function(require,module,exports){
6821 var Observable_1 = require('../../Observable');
6822 var filter_1 = require('../../operator/filter');
6823 Observable_1.Observable.prototype.filter = filter_1.filter;
6825 },{"../../Observable":29,"../../operator/filter":120}],62:[function(require,module,exports){
6827 var Observable_1 = require('../../Observable');
6828 var finally_1 = require('../../operator/finally');
6829 Observable_1.Observable.prototype.finally = finally_1._finally;
6830 Observable_1.Observable.prototype._finally = finally_1._finally;
6832 },{"../../Observable":29,"../../operator/finally":121}],63:[function(require,module,exports){
6834 var Observable_1 = require('../../Observable');
6835 var first_1 = require('../../operator/first');
6836 Observable_1.Observable.prototype.first = first_1.first;
6838 },{"../../Observable":29,"../../operator/first":122}],64:[function(require,module,exports){
6840 var Observable_1 = require('../../Observable');
6841 var last_1 = require('../../operator/last');
6842 Observable_1.Observable.prototype.last = last_1.last;
6844 },{"../../Observable":29,"../../operator/last":123}],65:[function(require,module,exports){
6846 var Observable_1 = require('../../Observable');
6847 var map_1 = require('../../operator/map');
6848 Observable_1.Observable.prototype.map = map_1.map;
6850 },{"../../Observable":29,"../../operator/map":124}],66:[function(require,module,exports){
6852 var Observable_1 = require('../../Observable');
6853 var merge_1 = require('../../operator/merge');
6854 Observable_1.Observable.prototype.merge = merge_1.merge;
6856 },{"../../Observable":29,"../../operator/merge":125}],67:[function(require,module,exports){
6858 var Observable_1 = require('../../Observable');
6859 var mergeAll_1 = require('../../operator/mergeAll');
6860 Observable_1.Observable.prototype.mergeAll = mergeAll_1.mergeAll;
6862 },{"../../Observable":29,"../../operator/mergeAll":126}],68:[function(require,module,exports){
6864 var Observable_1 = require('../../Observable');
6865 var mergeMap_1 = require('../../operator/mergeMap');
6866 Observable_1.Observable.prototype.mergeMap = mergeMap_1.mergeMap;
6867 Observable_1.Observable.prototype.flatMap = mergeMap_1.mergeMap;
6869 },{"../../Observable":29,"../../operator/mergeMap":127}],69:[function(require,module,exports){
6871 var Observable_1 = require('../../Observable');
6872 var pairwise_1 = require('../../operator/pairwise');
6873 Observable_1.Observable.prototype.pairwise = pairwise_1.pairwise;
6875 },{"../../Observable":29,"../../operator/pairwise":130}],70:[function(require,module,exports){
6877 var Observable_1 = require('../../Observable');
6878 var pluck_1 = require('../../operator/pluck');
6879 Observable_1.Observable.prototype.pluck = pluck_1.pluck;
6881 },{"../../Observable":29,"../../operator/pluck":131}],71:[function(require,module,exports){
6883 var Observable_1 = require('../../Observable');
6884 var publish_1 = require('../../operator/publish');
6885 Observable_1.Observable.prototype.publish = publish_1.publish;
6887 },{"../../Observable":29,"../../operator/publish":132}],72:[function(require,module,exports){
6889 var Observable_1 = require('../../Observable');
6890 var publishReplay_1 = require('../../operator/publishReplay');
6891 Observable_1.Observable.prototype.publishReplay = publishReplay_1.publishReplay;
6893 },{"../../Observable":29,"../../operator/publishReplay":133}],73:[function(require,module,exports){
6895 var Observable_1 = require('../../Observable');
6896 var scan_1 = require('../../operator/scan');
6897 Observable_1.Observable.prototype.scan = scan_1.scan;
6899 },{"../../Observable":29,"../../operator/scan":134}],74:[function(require,module,exports){
6901 var Observable_1 = require('../../Observable');
6902 var share_1 = require('../../operator/share');
6903 Observable_1.Observable.prototype.share = share_1.share;
6905 },{"../../Observable":29,"../../operator/share":135}],75:[function(require,module,exports){
6907 var Observable_1 = require('../../Observable');
6908 var skip_1 = require('../../operator/skip');
6909 Observable_1.Observable.prototype.skip = skip_1.skip;
6911 },{"../../Observable":29,"../../operator/skip":136}],76:[function(require,module,exports){
6913 var Observable_1 = require('../../Observable');
6914 var skipUntil_1 = require('../../operator/skipUntil');
6915 Observable_1.Observable.prototype.skipUntil = skipUntil_1.skipUntil;
6917 },{"../../Observable":29,"../../operator/skipUntil":137}],77:[function(require,module,exports){
6919 var Observable_1 = require('../../Observable');
6920 var skipWhile_1 = require('../../operator/skipWhile');
6921 Observable_1.Observable.prototype.skipWhile = skipWhile_1.skipWhile;
6923 },{"../../Observable":29,"../../operator/skipWhile":138}],78:[function(require,module,exports){
6925 var Observable_1 = require('../../Observable');
6926 var startWith_1 = require('../../operator/startWith');
6927 Observable_1.Observable.prototype.startWith = startWith_1.startWith;
6929 },{"../../Observable":29,"../../operator/startWith":139}],79:[function(require,module,exports){
6931 var Observable_1 = require('../../Observable');
6932 var switchMap_1 = require('../../operator/switchMap');
6933 Observable_1.Observable.prototype.switchMap = switchMap_1.switchMap;
6935 },{"../../Observable":29,"../../operator/switchMap":140}],80:[function(require,module,exports){
6937 var Observable_1 = require('../../Observable');
6938 var take_1 = require('../../operator/take');
6939 Observable_1.Observable.prototype.take = take_1.take;
6941 },{"../../Observable":29,"../../operator/take":141}],81:[function(require,module,exports){
6943 var Observable_1 = require('../../Observable');
6944 var takeUntil_1 = require('../../operator/takeUntil');
6945 Observable_1.Observable.prototype.takeUntil = takeUntil_1.takeUntil;
6947 },{"../../Observable":29,"../../operator/takeUntil":142}],82:[function(require,module,exports){
6949 var Observable_1 = require('../../Observable');
6950 var throttleTime_1 = require('../../operator/throttleTime');
6951 Observable_1.Observable.prototype.throttleTime = throttleTime_1.throttleTime;
6953 },{"../../Observable":29,"../../operator/throttleTime":144}],83:[function(require,module,exports){
6955 var Observable_1 = require('../../Observable');
6956 var withLatestFrom_1 = require('../../operator/withLatestFrom');
6957 Observable_1.Observable.prototype.withLatestFrom = withLatestFrom_1.withLatestFrom;
6959 },{"../../Observable":29,"../../operator/withLatestFrom":145}],84:[function(require,module,exports){
6961 var Observable_1 = require('../../Observable');
6962 var zip_1 = require('../../operator/zip');
6963 Observable_1.Observable.prototype.zip = zip_1.zipProto;
6965 },{"../../Observable":29,"../../operator/zip":146}],85:[function(require,module,exports){
6967 var __extends = (this && this.__extends) || function (d, b) {
6968 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6969 function __() { this.constructor = d; }
6970 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6972 var Observable_1 = require('../Observable');
6973 var ScalarObservable_1 = require('./ScalarObservable');
6974 var EmptyObservable_1 = require('./EmptyObservable');
6976 * We need this JSDoc comment for affecting ESDoc.
6977 * @extends {Ignored}
6980 var ArrayLikeObservable = (function (_super) {
6981 __extends(ArrayLikeObservable, _super);
6982 function ArrayLikeObservable(arrayLike, scheduler) {
6984 this.arrayLike = arrayLike;
6985 this.scheduler = scheduler;
6986 if (!scheduler && arrayLike.length === 1) {
6987 this._isScalar = true;
6988 this.value = arrayLike[0];
6991 ArrayLikeObservable.create = function (arrayLike, scheduler) {
6992 var length = arrayLike.length;
6994 return new EmptyObservable_1.EmptyObservable();
6996 else if (length === 1) {
6997 return new ScalarObservable_1.ScalarObservable(arrayLike[0], scheduler);
7000 return new ArrayLikeObservable(arrayLike, scheduler);
7003 ArrayLikeObservable.dispatch = function (state) {
7004 var arrayLike = state.arrayLike, index = state.index, length = state.length, subscriber = state.subscriber;
7005 if (subscriber.closed) {
7008 if (index >= length) {
7009 subscriber.complete();
7012 subscriber.next(arrayLike[index]);
7013 state.index = index + 1;
7014 this.schedule(state);
7016 ArrayLikeObservable.prototype._subscribe = function (subscriber) {
7018 var _a = this, arrayLike = _a.arrayLike, scheduler = _a.scheduler;
7019 var length = arrayLike.length;
7021 return scheduler.schedule(ArrayLikeObservable.dispatch, 0, {
7022 arrayLike: arrayLike, index: index, length: length, subscriber: subscriber
7026 for (var i = 0; i < length && !subscriber.closed; i++) {
7027 subscriber.next(arrayLike[i]);
7029 subscriber.complete();
7032 return ArrayLikeObservable;
7033 }(Observable_1.Observable));
7034 exports.ArrayLikeObservable = ArrayLikeObservable;
7036 },{"../Observable":29,"./EmptyObservable":89,"./ScalarObservable":95}],86:[function(require,module,exports){
7038 var __extends = (this && this.__extends) || function (d, b) {
7039 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7040 function __() { this.constructor = d; }
7041 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7043 var Observable_1 = require('../Observable');
7044 var ScalarObservable_1 = require('./ScalarObservable');
7045 var EmptyObservable_1 = require('./EmptyObservable');
7046 var isScheduler_1 = require('../util/isScheduler');
7048 * We need this JSDoc comment for affecting ESDoc.
7049 * @extends {Ignored}
7052 var ArrayObservable = (function (_super) {
7053 __extends(ArrayObservable, _super);
7054 function ArrayObservable(array, scheduler) {
7057 this.scheduler = scheduler;
7058 if (!scheduler && array.length === 1) {
7059 this._isScalar = true;
7060 this.value = array[0];
7063 ArrayObservable.create = function (array, scheduler) {
7064 return new ArrayObservable(array, scheduler);
7067 * Creates an Observable that emits some values you specify as arguments,
7068 * immediately one after the other, and then emits a complete notification.
7070 * <span class="informal">Emits the arguments you provide, then completes.
7073 * <img src="./img/of.png" width="100%">
7075 * This static operator is useful for creating a simple Observable that only
7076 * emits the arguments given, and the complete notification thereafter. It can
7077 * be used for composing with other Observables, such as with {@link concat}.
7078 * By default, it uses a `null` IScheduler, which means the `next`
7079 * notifications are sent synchronously, although with a different IScheduler
7080 * it is possible to determine when those notifications will be delivered.
7082 * @example <caption>Emit 10, 20, 30, then 'a', 'b', 'c', then start ticking every second.</caption>
7083 * var numbers = Rx.Observable.of(10, 20, 30);
7084 * var letters = Rx.Observable.of('a', 'b', 'c');
7085 * var interval = Rx.Observable.interval(1000);
7086 * var result = numbers.concat(letters).concat(interval);
7087 * result.subscribe(x => console.log(x));
7089 * @see {@link create}
7090 * @see {@link empty}
7091 * @see {@link never}
7092 * @see {@link throw}
7094 * @param {...T} values Arguments that represent `next` values to be emitted.
7095 * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
7096 * the emissions of the `next` notifications.
7097 * @return {Observable<T>} An Observable that emits each given input value.
7102 ArrayObservable.of = function () {
7104 for (var _i = 0; _i < arguments.length; _i++) {
7105 array[_i - 0] = arguments[_i];
7107 var scheduler = array[array.length - 1];
7108 if (isScheduler_1.isScheduler(scheduler)) {
7114 var len = array.length;
7116 return new ArrayObservable(array, scheduler);
7118 else if (len === 1) {
7119 return new ScalarObservable_1.ScalarObservable(array[0], scheduler);
7122 return new EmptyObservable_1.EmptyObservable(scheduler);
7125 ArrayObservable.dispatch = function (state) {
7126 var array = state.array, index = state.index, count = state.count, subscriber = state.subscriber;
7127 if (index >= count) {
7128 subscriber.complete();
7131 subscriber.next(array[index]);
7132 if (subscriber.closed) {
7135 state.index = index + 1;
7136 this.schedule(state);
7138 ArrayObservable.prototype._subscribe = function (subscriber) {
7140 var array = this.array;
7141 var count = array.length;
7142 var scheduler = this.scheduler;
7144 return scheduler.schedule(ArrayObservable.dispatch, 0, {
7145 array: array, index: index, count: count, subscriber: subscriber
7149 for (var i = 0; i < count && !subscriber.closed; i++) {
7150 subscriber.next(array[i]);
7152 subscriber.complete();
7155 return ArrayObservable;
7156 }(Observable_1.Observable));
7157 exports.ArrayObservable = ArrayObservable;
7159 },{"../Observable":29,"../util/isScheduler":171,"./EmptyObservable":89,"./ScalarObservable":95}],87:[function(require,module,exports){
7161 var __extends = (this && this.__extends) || function (d, b) {
7162 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7163 function __() { this.constructor = d; }
7164 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7166 var Subject_1 = require('../Subject');
7167 var Observable_1 = require('../Observable');
7168 var Subscriber_1 = require('../Subscriber');
7169 var Subscription_1 = require('../Subscription');
7171 * @class ConnectableObservable<T>
7173 var ConnectableObservable = (function (_super) {
7174 __extends(ConnectableObservable, _super);
7175 function ConnectableObservable(source, subjectFactory) {
7177 this.source = source;
7178 this.subjectFactory = subjectFactory;
7180 this._isComplete = false;
7182 ConnectableObservable.prototype._subscribe = function (subscriber) {
7183 return this.getSubject().subscribe(subscriber);
7185 ConnectableObservable.prototype.getSubject = function () {
7186 var subject = this._subject;
7187 if (!subject || subject.isStopped) {
7188 this._subject = this.subjectFactory();
7190 return this._subject;
7192 ConnectableObservable.prototype.connect = function () {
7193 var connection = this._connection;
7195 this._isComplete = false;
7196 connection = this._connection = new Subscription_1.Subscription();
7197 connection.add(this.source
7198 .subscribe(new ConnectableSubscriber(this.getSubject(), this)));
7199 if (connection.closed) {
7200 this._connection = null;
7201 connection = Subscription_1.Subscription.EMPTY;
7204 this._connection = connection;
7209 ConnectableObservable.prototype.refCount = function () {
7210 return this.lift(new RefCountOperator(this));
7212 return ConnectableObservable;
7213 }(Observable_1.Observable));
7214 exports.ConnectableObservable = ConnectableObservable;
7215 var connectableProto = ConnectableObservable.prototype;
7216 exports.connectableObservableDescriptor = {
7217 operator: { value: null },
7218 _refCount: { value: 0, writable: true },
7219 _subject: { value: null, writable: true },
7220 _connection: { value: null, writable: true },
7221 _subscribe: { value: connectableProto._subscribe },
7222 _isComplete: { value: connectableProto._isComplete, writable: true },
7223 getSubject: { value: connectableProto.getSubject },
7224 connect: { value: connectableProto.connect },
7225 refCount: { value: connectableProto.refCount }
7227 var ConnectableSubscriber = (function (_super) {
7228 __extends(ConnectableSubscriber, _super);
7229 function ConnectableSubscriber(destination, connectable) {
7230 _super.call(this, destination);
7231 this.connectable = connectable;
7233 ConnectableSubscriber.prototype._error = function (err) {
7234 this._unsubscribe();
7235 _super.prototype._error.call(this, err);
7237 ConnectableSubscriber.prototype._complete = function () {
7238 this.connectable._isComplete = true;
7239 this._unsubscribe();
7240 _super.prototype._complete.call(this);
7242 ConnectableSubscriber.prototype._unsubscribe = function () {
7243 var connectable = this.connectable;
7245 this.connectable = null;
7246 var connection = connectable._connection;
7247 connectable._refCount = 0;
7248 connectable._subject = null;
7249 connectable._connection = null;
7251 connection.unsubscribe();
7255 return ConnectableSubscriber;
7256 }(Subject_1.SubjectSubscriber));
7257 var RefCountOperator = (function () {
7258 function RefCountOperator(connectable) {
7259 this.connectable = connectable;
7261 RefCountOperator.prototype.call = function (subscriber, source) {
7262 var connectable = this.connectable;
7263 connectable._refCount++;
7264 var refCounter = new RefCountSubscriber(subscriber, connectable);
7265 var subscription = source.subscribe(refCounter);
7266 if (!refCounter.closed) {
7267 refCounter.connection = connectable.connect();
7269 return subscription;
7271 return RefCountOperator;
7273 var RefCountSubscriber = (function (_super) {
7274 __extends(RefCountSubscriber, _super);
7275 function RefCountSubscriber(destination, connectable) {
7276 _super.call(this, destination);
7277 this.connectable = connectable;
7279 RefCountSubscriber.prototype._unsubscribe = function () {
7280 var connectable = this.connectable;
7282 this.connection = null;
7285 this.connectable = null;
7286 var refCount = connectable._refCount;
7287 if (refCount <= 0) {
7288 this.connection = null;
7291 connectable._refCount = refCount - 1;
7293 this.connection = null;
7297 // Compare the local RefCountSubscriber's connection Subscription to the
7298 // connection Subscription on the shared ConnectableObservable. In cases
7299 // where the ConnectableObservable source synchronously emits values, and
7300 // the RefCountSubscriber's downstream Observers synchronously unsubscribe,
7301 // execution continues to here before the RefCountOperator has a chance to
7302 // supply the RefCountSubscriber with the shared connection Subscription.
7305 // Observable.range(0, 10)
7311 // In order to account for this case, RefCountSubscriber should only dispose
7312 // the ConnectableObservable's shared connection Subscription if the
7313 // connection Subscription exists, *and* either:
7314 // a. RefCountSubscriber doesn't have a reference to the shared connection
7315 // Subscription yet, or,
7316 // b. RefCountSubscriber's connection Subscription reference is identical
7317 // to the shared connection Subscription
7319 var connection = this.connection;
7320 var sharedConnection = connectable._connection;
7321 this.connection = null;
7322 if (sharedConnection && (!connection || sharedConnection === connection)) {
7323 sharedConnection.unsubscribe();
7326 return RefCountSubscriber;
7327 }(Subscriber_1.Subscriber));
7329 },{"../Observable":29,"../Subject":34,"../Subscriber":36,"../Subscription":37}],88:[function(require,module,exports){
7331 var __extends = (this && this.__extends) || function (d, b) {
7332 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7333 function __() { this.constructor = d; }
7334 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7336 var Observable_1 = require('../Observable');
7337 var subscribeToResult_1 = require('../util/subscribeToResult');
7338 var OuterSubscriber_1 = require('../OuterSubscriber');
7340 * We need this JSDoc comment for affecting ESDoc.
7341 * @extends {Ignored}
7344 var DeferObservable = (function (_super) {
7345 __extends(DeferObservable, _super);
7346 function DeferObservable(observableFactory) {
7348 this.observableFactory = observableFactory;
7351 * Creates an Observable that, on subscribe, calls an Observable factory to
7352 * make an Observable for each new Observer.
7354 * <span class="informal">Creates the Observable lazily, that is, only when it
7358 * <img src="./img/defer.png" width="100%">
7360 * `defer` allows you to create the Observable only when the Observer
7361 * subscribes, and create a fresh Observable for each Observer. It waits until
7362 * an Observer subscribes to it, and then it generates an Observable,
7363 * typically with an Observable factory function. It does this afresh for each
7364 * subscriber, so although each subscriber may think it is subscribing to the
7365 * same Observable, in fact each subscriber gets its own individual
7368 * @example <caption>Subscribe to either an Observable of clicks or an Observable of interval, at random</caption>
7369 * var clicksOrInterval = Rx.Observable.defer(function () {
7370 * if (Math.random() > 0.5) {
7371 * return Rx.Observable.fromEvent(document, 'click');
7373 * return Rx.Observable.interval(1000);
7376 * clicksOrInterval.subscribe(x => console.log(x));
7378 * // Results in the following behavior:
7379 * // If the result of Math.random() is greater than 0.5 it will listen
7380 * // for clicks anywhere on the "document"; when document is clicked it
7381 * // will log a MouseEvent object to the console. If the result is less
7382 * // than 0.5 it will emit ascending numbers, one every second(1000ms).
7384 * @see {@link create}
7386 * @param {function(): SubscribableOrPromise} observableFactory The Observable
7387 * factory function to invoke for each Observer that subscribes to the output
7388 * Observable. May also return a Promise, which will be converted on the fly
7390 * @return {Observable} An Observable whose Observers' subscriptions trigger
7391 * an invocation of the given Observable factory function.
7396 DeferObservable.create = function (observableFactory) {
7397 return new DeferObservable(observableFactory);
7399 DeferObservable.prototype._subscribe = function (subscriber) {
7400 return new DeferSubscriber(subscriber, this.observableFactory);
7402 return DeferObservable;
7403 }(Observable_1.Observable));
7404 exports.DeferObservable = DeferObservable;
7405 var DeferSubscriber = (function (_super) {
7406 __extends(DeferSubscriber, _super);
7407 function DeferSubscriber(destination, factory) {
7408 _super.call(this, destination);
7409 this.factory = factory;
7412 DeferSubscriber.prototype.tryDefer = function () {
7414 this._callFactory();
7420 DeferSubscriber.prototype._callFactory = function () {
7421 var result = this.factory();
7423 this.add(subscribeToResult_1.subscribeToResult(this, result));
7426 return DeferSubscriber;
7427 }(OuterSubscriber_1.OuterSubscriber));
7429 },{"../Observable":29,"../OuterSubscriber":31,"../util/subscribeToResult":173}],89:[function(require,module,exports){
7431 var __extends = (this && this.__extends) || function (d, b) {
7432 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7433 function __() { this.constructor = d; }
7434 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7436 var Observable_1 = require('../Observable');
7438 * We need this JSDoc comment for affecting ESDoc.
7439 * @extends {Ignored}
7442 var EmptyObservable = (function (_super) {
7443 __extends(EmptyObservable, _super);
7444 function EmptyObservable(scheduler) {
7446 this.scheduler = scheduler;
7449 * Creates an Observable that emits no items to the Observer and immediately
7450 * emits a complete notification.
7452 * <span class="informal">Just emits 'complete', and nothing else.
7455 * <img src="./img/empty.png" width="100%">
7457 * This static operator is useful for creating a simple Observable that only
7458 * emits the complete notification. It can be used for composing with other
7459 * Observables, such as in a {@link mergeMap}.
7461 * @example <caption>Emit the number 7, then complete.</caption>
7462 * var result = Rx.Observable.empty().startWith(7);
7463 * result.subscribe(x => console.log(x));
7465 * @example <caption>Map and flatten only odd numbers to the sequence 'a', 'b', 'c'</caption>
7466 * var interval = Rx.Observable.interval(1000);
7467 * var result = interval.mergeMap(x =>
7468 * x % 2 === 1 ? Rx.Observable.of('a', 'b', 'c') : Rx.Observable.empty()
7470 * result.subscribe(x => console.log(x));
7472 * // Results in the following to the console:
7473 * // x is equal to the count on the interval eg(0,1,2,3,...)
7474 * // x will occur every 1000ms
7475 * // if x % 2 is equal to 1 print abc
7476 * // if x % 2 is not equal to 1 nothing will be output
7478 * @see {@link create}
7479 * @see {@link never}
7481 * @see {@link throw}
7483 * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
7484 * the emission of the complete notification.
7485 * @return {Observable} An "empty" Observable: emits only the complete
7491 EmptyObservable.create = function (scheduler) {
7492 return new EmptyObservable(scheduler);
7494 EmptyObservable.dispatch = function (arg) {
7495 var subscriber = arg.subscriber;
7496 subscriber.complete();
7498 EmptyObservable.prototype._subscribe = function (subscriber) {
7499 var scheduler = this.scheduler;
7501 return scheduler.schedule(EmptyObservable.dispatch, 0, { subscriber: subscriber });
7504 subscriber.complete();
7507 return EmptyObservable;
7508 }(Observable_1.Observable));
7509 exports.EmptyObservable = EmptyObservable;
7511 },{"../Observable":29}],90:[function(require,module,exports){
7513 var __extends = (this && this.__extends) || function (d, b) {
7514 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7515 function __() { this.constructor = d; }
7516 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7518 var Observable_1 = require('../Observable');
7520 * We need this JSDoc comment for affecting ESDoc.
7521 * @extends {Ignored}
7524 var ErrorObservable = (function (_super) {
7525 __extends(ErrorObservable, _super);
7526 function ErrorObservable(error, scheduler) {
7529 this.scheduler = scheduler;
7532 * Creates an Observable that emits no items to the Observer and immediately
7533 * emits an error notification.
7535 * <span class="informal">Just emits 'error', and nothing else.
7538 * <img src="./img/throw.png" width="100%">
7540 * This static operator is useful for creating a simple Observable that only
7541 * emits the error notification. It can be used for composing with other
7542 * Observables, such as in a {@link mergeMap}.
7544 * @example <caption>Emit the number 7, then emit an error.</caption>
7545 * var result = Rx.Observable.throw(new Error('oops!')).startWith(7);
7546 * result.subscribe(x => console.log(x), e => console.error(e));
7548 * @example <caption>Map and flatten numbers to the sequence 'a', 'b', 'c', but throw an error for 13</caption>
7549 * var interval = Rx.Observable.interval(1000);
7550 * var result = interval.mergeMap(x =>
7552 * Rx.Observable.throw('Thirteens are bad') :
7553 * Rx.Observable.of('a', 'b', 'c')
7555 * result.subscribe(x => console.log(x), e => console.error(e));
7557 * @see {@link create}
7558 * @see {@link empty}
7559 * @see {@link never}
7562 * @param {any} error The particular Error to pass to the error notification.
7563 * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
7564 * the emission of the error notification.
7565 * @return {Observable} An error Observable: emits only the error notification
7566 * using the given error argument.
7571 ErrorObservable.create = function (error, scheduler) {
7572 return new ErrorObservable(error, scheduler);
7574 ErrorObservable.dispatch = function (arg) {
7575 var error = arg.error, subscriber = arg.subscriber;
7576 subscriber.error(error);
7578 ErrorObservable.prototype._subscribe = function (subscriber) {
7579 var error = this.error;
7580 var scheduler = this.scheduler;
7581 subscriber.syncErrorThrowable = true;
7583 return scheduler.schedule(ErrorObservable.dispatch, 0, {
7584 error: error, subscriber: subscriber
7588 subscriber.error(error);
7591 return ErrorObservable;
7592 }(Observable_1.Observable));
7593 exports.ErrorObservable = ErrorObservable;
7595 },{"../Observable":29}],91:[function(require,module,exports){
7597 var __extends = (this && this.__extends) || function (d, b) {
7598 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7599 function __() { this.constructor = d; }
7600 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7602 var Observable_1 = require('../Observable');
7603 var tryCatch_1 = require('../util/tryCatch');
7604 var isFunction_1 = require('../util/isFunction');
7605 var errorObject_1 = require('../util/errorObject');
7606 var Subscription_1 = require('../Subscription');
7607 var toString = Object.prototype.toString;
7608 function isNodeStyleEventEmitter(sourceObj) {
7609 return !!sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function';
7611 function isJQueryStyleEventEmitter(sourceObj) {
7612 return !!sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function';
7614 function isNodeList(sourceObj) {
7615 return !!sourceObj && toString.call(sourceObj) === '[object NodeList]';
7617 function isHTMLCollection(sourceObj) {
7618 return !!sourceObj && toString.call(sourceObj) === '[object HTMLCollection]';
7620 function isEventTarget(sourceObj) {
7621 return !!sourceObj && typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function';
7624 * We need this JSDoc comment for affecting ESDoc.
7625 * @extends {Ignored}
7628 var FromEventObservable = (function (_super) {
7629 __extends(FromEventObservable, _super);
7630 function FromEventObservable(sourceObj, eventName, selector, options) {
7632 this.sourceObj = sourceObj;
7633 this.eventName = eventName;
7634 this.selector = selector;
7635 this.options = options;
7637 /* tslint:enable:max-line-length */
7639 * Creates an Observable that emits events of a specific type coming from the
7640 * given event target.
7642 * <span class="informal">Creates an Observable from DOM events, or Node
7643 * EventEmitter events or others.</span>
7645 * <img src="./img/fromEvent.png" width="100%">
7647 * Creates an Observable by attaching an event listener to an "event target",
7648 * which may be an object with `addEventListener` and `removeEventListener`,
7649 * a Node.js EventEmitter, a jQuery style EventEmitter, a NodeList from the
7650 * DOM, or an HTMLCollection from the DOM. The event handler is attached when
7651 * the output Observable is subscribed, and removed when the Subscription is
7654 * @example <caption>Emits clicks happening on the DOM document</caption>
7655 * var clicks = Rx.Observable.fromEvent(document, 'click');
7656 * clicks.subscribe(x => console.log(x));
7659 * // MouseEvent object logged to console everytime a click
7660 * // occurs on the document.
7663 * @see {@link fromEventPattern}
7665 * @param {EventTargetLike} target The DOMElement, event target, Node.js
7666 * EventEmitter, NodeList or HTMLCollection to attach the event handler to.
7667 * @param {string} eventName The event name of interest, being emitted by the
7669 * @param {EventListenerOptions} [options] Options to pass through to addEventListener
7670 * @param {SelectorMethodSignature<T>} [selector] An optional function to
7671 * post-process results. It takes the arguments from the event handler and
7672 * should return a single value.
7673 * @return {Observable<T>}
7678 FromEventObservable.create = function (target, eventName, options, selector) {
7679 if (isFunction_1.isFunction(options)) {
7681 options = undefined;
7683 return new FromEventObservable(target, eventName, selector, options);
7685 FromEventObservable.setupSubscription = function (sourceObj, eventName, handler, subscriber, options) {
7687 if (isNodeList(sourceObj) || isHTMLCollection(sourceObj)) {
7688 for (var i = 0, len = sourceObj.length; i < len; i++) {
7689 FromEventObservable.setupSubscription(sourceObj[i], eventName, handler, subscriber, options);
7692 else if (isEventTarget(sourceObj)) {
7693 var source_1 = sourceObj;
7694 sourceObj.addEventListener(eventName, handler, options);
7695 unsubscribe = function () { return source_1.removeEventListener(eventName, handler); };
7697 else if (isJQueryStyleEventEmitter(sourceObj)) {
7698 var source_2 = sourceObj;
7699 sourceObj.on(eventName, handler);
7700 unsubscribe = function () { return source_2.off(eventName, handler); };
7702 else if (isNodeStyleEventEmitter(sourceObj)) {
7703 var source_3 = sourceObj;
7704 sourceObj.addListener(eventName, handler);
7705 unsubscribe = function () { return source_3.removeListener(eventName, handler); };
7708 throw new TypeError('Invalid event target');
7710 subscriber.add(new Subscription_1.Subscription(unsubscribe));
7712 FromEventObservable.prototype._subscribe = function (subscriber) {
7713 var sourceObj = this.sourceObj;
7714 var eventName = this.eventName;
7715 var options = this.options;
7716 var selector = this.selector;
7717 var handler = selector ? function () {
7719 for (var _i = 0; _i < arguments.length; _i++) {
7720 args[_i - 0] = arguments[_i];
7722 var result = tryCatch_1.tryCatch(selector).apply(void 0, args);
7723 if (result === errorObject_1.errorObject) {
7724 subscriber.error(errorObject_1.errorObject.e);
7727 subscriber.next(result);
7729 } : function (e) { return subscriber.next(e); };
7730 FromEventObservable.setupSubscription(sourceObj, eventName, handler, subscriber, options);
7732 return FromEventObservable;
7733 }(Observable_1.Observable));
7734 exports.FromEventObservable = FromEventObservable;
7736 },{"../Observable":29,"../Subscription":37,"../util/errorObject":163,"../util/isFunction":167,"../util/tryCatch":175}],92:[function(require,module,exports){
7738 var __extends = (this && this.__extends) || function (d, b) {
7739 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7740 function __() { this.constructor = d; }
7741 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7743 var isArray_1 = require('../util/isArray');
7744 var isArrayLike_1 = require('../util/isArrayLike');
7745 var isPromise_1 = require('../util/isPromise');
7746 var PromiseObservable_1 = require('./PromiseObservable');
7747 var IteratorObservable_1 = require('./IteratorObservable');
7748 var ArrayObservable_1 = require('./ArrayObservable');
7749 var ArrayLikeObservable_1 = require('./ArrayLikeObservable');
7750 var iterator_1 = require('../symbol/iterator');
7751 var Observable_1 = require('../Observable');
7752 var observeOn_1 = require('../operator/observeOn');
7753 var observable_1 = require('../symbol/observable');
7755 * We need this JSDoc comment for affecting ESDoc.
7756 * @extends {Ignored}
7759 var FromObservable = (function (_super) {
7760 __extends(FromObservable, _super);
7761 function FromObservable(ish, scheduler) {
7762 _super.call(this, null);
7764 this.scheduler = scheduler;
7767 * Creates an Observable from an Array, an array-like object, a Promise, an
7768 * iterable object, or an Observable-like object.
7770 * <span class="informal">Converts almost anything to an Observable.</span>
7772 * <img src="./img/from.png" width="100%">
7774 * Convert various other objects and data types into Observables. `from`
7775 * converts a Promise or an array-like or an
7776 * [iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable)
7777 * object into an Observable that emits the items in that promise or array or
7778 * iterable. A String, in this context, is treated as an array of characters.
7779 * Observable-like objects (contains a function named with the ES2015 Symbol
7780 * for Observable) can also be converted through this operator.
7782 * @example <caption>Converts an array to an Observable</caption>
7783 * var array = [10, 20, 30];
7784 * var result = Rx.Observable.from(array);
7785 * result.subscribe(x => console.log(x));
7787 * // Results in the following:
7790 * @example <caption>Convert an infinite iterable (from a generator) to an Observable</caption>
7791 * function* generateDoubles(seed) {
7795 * i = 2 * i; // double it
7799 * var iterator = generateDoubles(3);
7800 * var result = Rx.Observable.from(iterator).take(10);
7801 * result.subscribe(x => console.log(x));
7803 * // Results in the following:
7804 * // 3 6 12 24 48 96 192 384 768 1536
7806 * @see {@link create}
7807 * @see {@link fromEvent}
7808 * @see {@link fromEventPattern}
7809 * @see {@link fromPromise}
7811 * @param {ObservableInput<T>} ish A subscribable object, a Promise, an
7812 * Observable-like, an Array, an iterable or an array-like object to be
7814 * @param {Scheduler} [scheduler] The scheduler on which to schedule the
7815 * emissions of values.
7816 * @return {Observable<T>} The Observable whose values are originally from the
7817 * input object that was converted.
7822 FromObservable.create = function (ish, scheduler) {
7824 if (typeof ish[observable_1.observable] === 'function') {
7825 if (ish instanceof Observable_1.Observable && !scheduler) {
7828 return new FromObservable(ish, scheduler);
7830 else if (isArray_1.isArray(ish)) {
7831 return new ArrayObservable_1.ArrayObservable(ish, scheduler);
7833 else if (isPromise_1.isPromise(ish)) {
7834 return new PromiseObservable_1.PromiseObservable(ish, scheduler);
7836 else if (typeof ish[iterator_1.iterator] === 'function' || typeof ish === 'string') {
7837 return new IteratorObservable_1.IteratorObservable(ish, scheduler);
7839 else if (isArrayLike_1.isArrayLike(ish)) {
7840 return new ArrayLikeObservable_1.ArrayLikeObservable(ish, scheduler);
7843 throw new TypeError((ish !== null && typeof ish || ish) + ' is not observable');
7845 FromObservable.prototype._subscribe = function (subscriber) {
7847 var scheduler = this.scheduler;
7848 if (scheduler == null) {
7849 return ish[observable_1.observable]().subscribe(subscriber);
7852 return ish[observable_1.observable]().subscribe(new observeOn_1.ObserveOnSubscriber(subscriber, scheduler, 0));
7855 return FromObservable;
7856 }(Observable_1.Observable));
7857 exports.FromObservable = FromObservable;
7859 },{"../Observable":29,"../operator/observeOn":129,"../symbol/iterator":154,"../symbol/observable":155,"../util/isArray":164,"../util/isArrayLike":165,"../util/isPromise":170,"./ArrayLikeObservable":85,"./ArrayObservable":86,"./IteratorObservable":93,"./PromiseObservable":94}],93:[function(require,module,exports){
7861 var __extends = (this && this.__extends) || function (d, b) {
7862 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7863 function __() { this.constructor = d; }
7864 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7866 var root_1 = require('../util/root');
7867 var Observable_1 = require('../Observable');
7868 var iterator_1 = require('../symbol/iterator');
7870 * We need this JSDoc comment for affecting ESDoc.
7871 * @extends {Ignored}
7874 var IteratorObservable = (function (_super) {
7875 __extends(IteratorObservable, _super);
7876 function IteratorObservable(iterator, scheduler) {
7878 this.scheduler = scheduler;
7879 if (iterator == null) {
7880 throw new Error('iterator cannot be null.');
7882 this.iterator = getIterator(iterator);
7884 IteratorObservable.create = function (iterator, scheduler) {
7885 return new IteratorObservable(iterator, scheduler);
7887 IteratorObservable.dispatch = function (state) {
7888 var index = state.index, hasError = state.hasError, iterator = state.iterator, subscriber = state.subscriber;
7890 subscriber.error(state.error);
7893 var result = iterator.next();
7895 subscriber.complete();
7898 subscriber.next(result.value);
7899 state.index = index + 1;
7900 if (subscriber.closed) {
7901 if (typeof iterator.return === 'function') {
7906 this.schedule(state);
7908 IteratorObservable.prototype._subscribe = function (subscriber) {
7910 var _a = this, iterator = _a.iterator, scheduler = _a.scheduler;
7912 return scheduler.schedule(IteratorObservable.dispatch, 0, {
7913 index: index, iterator: iterator, subscriber: subscriber
7918 var result = iterator.next();
7920 subscriber.complete();
7924 subscriber.next(result.value);
7926 if (subscriber.closed) {
7927 if (typeof iterator.return === 'function') {
7935 return IteratorObservable;
7936 }(Observable_1.Observable));
7937 exports.IteratorObservable = IteratorObservable;
7938 var StringIterator = (function () {
7939 function StringIterator(str, idx, len) {
7940 if (idx === void 0) { idx = 0; }
7941 if (len === void 0) { len = str.length; }
7946 StringIterator.prototype[iterator_1.iterator] = function () { return (this); };
7947 StringIterator.prototype.next = function () {
7948 return this.idx < this.len ? {
7950 value: this.str.charAt(this.idx++)
7956 return StringIterator;
7958 var ArrayIterator = (function () {
7959 function ArrayIterator(arr, idx, len) {
7960 if (idx === void 0) { idx = 0; }
7961 if (len === void 0) { len = toLength(arr); }
7966 ArrayIterator.prototype[iterator_1.iterator] = function () { return this; };
7967 ArrayIterator.prototype.next = function () {
7968 return this.idx < this.len ? {
7970 value: this.arr[this.idx++]
7976 return ArrayIterator;
7978 function getIterator(obj) {
7979 var i = obj[iterator_1.iterator];
7980 if (!i && typeof obj === 'string') {
7981 return new StringIterator(obj);
7983 if (!i && obj.length !== undefined) {
7984 return new ArrayIterator(obj);
7987 throw new TypeError('object is not iterable');
7989 return obj[iterator_1.iterator]();
7991 var maxSafeInteger = Math.pow(2, 53) - 1;
7992 function toLength(o) {
7993 var len = +o.length;
7997 if (len === 0 || !numberIsFinite(len)) {
8000 len = sign(len) * Math.floor(Math.abs(len));
8004 if (len > maxSafeInteger) {
8005 return maxSafeInteger;
8009 function numberIsFinite(value) {
8010 return typeof value === 'number' && root_1.root.isFinite(value);
8012 function sign(value) {
8013 var valueAsNumber = +value;
8014 if (valueAsNumber === 0) {
8015 return valueAsNumber;
8017 if (isNaN(valueAsNumber)) {
8018 return valueAsNumber;
8020 return valueAsNumber < 0 ? -1 : 1;
8023 },{"../Observable":29,"../symbol/iterator":154,"../util/root":172}],94:[function(require,module,exports){
8025 var __extends = (this && this.__extends) || function (d, b) {
8026 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8027 function __() { this.constructor = d; }
8028 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8030 var root_1 = require('../util/root');
8031 var Observable_1 = require('../Observable');
8033 * We need this JSDoc comment for affecting ESDoc.
8034 * @extends {Ignored}
8037 var PromiseObservable = (function (_super) {
8038 __extends(PromiseObservable, _super);
8039 function PromiseObservable(promise, scheduler) {
8041 this.promise = promise;
8042 this.scheduler = scheduler;
8045 * Converts a Promise to an Observable.
8047 * <span class="informal">Returns an Observable that just emits the Promise's
8048 * resolved value, then completes.</span>
8050 * Converts an ES2015 Promise or a Promises/A+ spec compliant Promise to an
8051 * Observable. If the Promise resolves with a value, the output Observable
8052 * emits that resolved value as a `next`, and then completes. If the Promise
8053 * is rejected, then the output Observable emits the corresponding Error.
8055 * @example <caption>Convert the Promise returned by Fetch to an Observable</caption>
8056 * var result = Rx.Observable.fromPromise(fetch('http://myserver.com/'));
8057 * result.subscribe(x => console.log(x), e => console.error(e));
8059 * @see {@link bindCallback}
8062 * @param {PromiseLike<T>} promise The promise to be converted.
8063 * @param {Scheduler} [scheduler] An optional IScheduler to use for scheduling
8064 * the delivery of the resolved value (or the rejection).
8065 * @return {Observable<T>} An Observable which wraps the Promise.
8070 PromiseObservable.create = function (promise, scheduler) {
8071 return new PromiseObservable(promise, scheduler);
8073 PromiseObservable.prototype._subscribe = function (subscriber) {
8075 var promise = this.promise;
8076 var scheduler = this.scheduler;
8077 if (scheduler == null) {
8078 if (this._isScalar) {
8079 if (!subscriber.closed) {
8080 subscriber.next(this.value);
8081 subscriber.complete();
8085 promise.then(function (value) {
8086 _this.value = value;
8087 _this._isScalar = true;
8088 if (!subscriber.closed) {
8089 subscriber.next(value);
8090 subscriber.complete();
8093 if (!subscriber.closed) {
8094 subscriber.error(err);
8097 .then(null, function (err) {
8098 // escape the promise trap, throw unhandled errors
8099 root_1.root.setTimeout(function () { throw err; });
8104 if (this._isScalar) {
8105 if (!subscriber.closed) {
8106 return scheduler.schedule(dispatchNext, 0, { value: this.value, subscriber: subscriber });
8110 promise.then(function (value) {
8111 _this.value = value;
8112 _this._isScalar = true;
8113 if (!subscriber.closed) {
8114 subscriber.add(scheduler.schedule(dispatchNext, 0, { value: value, subscriber: subscriber }));
8117 if (!subscriber.closed) {
8118 subscriber.add(scheduler.schedule(dispatchError, 0, { err: err, subscriber: subscriber }));
8121 .then(null, function (err) {
8122 // escape the promise trap, throw unhandled errors
8123 root_1.root.setTimeout(function () { throw err; });
8128 return PromiseObservable;
8129 }(Observable_1.Observable));
8130 exports.PromiseObservable = PromiseObservable;
8131 function dispatchNext(arg) {
8132 var value = arg.value, subscriber = arg.subscriber;
8133 if (!subscriber.closed) {
8134 subscriber.next(value);
8135 subscriber.complete();
8138 function dispatchError(arg) {
8139 var err = arg.err, subscriber = arg.subscriber;
8140 if (!subscriber.closed) {
8141 subscriber.error(err);
8145 },{"../Observable":29,"../util/root":172}],95:[function(require,module,exports){
8147 var __extends = (this && this.__extends) || function (d, b) {
8148 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8149 function __() { this.constructor = d; }
8150 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8152 var Observable_1 = require('../Observable');
8154 * We need this JSDoc comment for affecting ESDoc.
8155 * @extends {Ignored}
8158 var ScalarObservable = (function (_super) {
8159 __extends(ScalarObservable, _super);
8160 function ScalarObservable(value, scheduler) {
8163 this.scheduler = scheduler;
8164 this._isScalar = true;
8166 this._isScalar = false;
8169 ScalarObservable.create = function (value, scheduler) {
8170 return new ScalarObservable(value, scheduler);
8172 ScalarObservable.dispatch = function (state) {
8173 var done = state.done, value = state.value, subscriber = state.subscriber;
8175 subscriber.complete();
8178 subscriber.next(value);
8179 if (subscriber.closed) {
8183 this.schedule(state);
8185 ScalarObservable.prototype._subscribe = function (subscriber) {
8186 var value = this.value;
8187 var scheduler = this.scheduler;
8189 return scheduler.schedule(ScalarObservable.dispatch, 0, {
8190 done: false, value: value, subscriber: subscriber
8194 subscriber.next(value);
8195 if (!subscriber.closed) {
8196 subscriber.complete();
8200 return ScalarObservable;
8201 }(Observable_1.Observable));
8202 exports.ScalarObservable = ScalarObservable;
8204 },{"../Observable":29}],96:[function(require,module,exports){
8206 var __extends = (this && this.__extends) || function (d, b) {
8207 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8208 function __() { this.constructor = d; }
8209 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8211 var isNumeric_1 = require('../util/isNumeric');
8212 var Observable_1 = require('../Observable');
8213 var async_1 = require('../scheduler/async');
8214 var isScheduler_1 = require('../util/isScheduler');
8215 var isDate_1 = require('../util/isDate');
8217 * We need this JSDoc comment for affecting ESDoc.
8218 * @extends {Ignored}
8221 var TimerObservable = (function (_super) {
8222 __extends(TimerObservable, _super);
8223 function TimerObservable(dueTime, period, scheduler) {
8224 if (dueTime === void 0) { dueTime = 0; }
8228 if (isNumeric_1.isNumeric(period)) {
8229 this.period = Number(period) < 1 && 1 || Number(period);
8231 else if (isScheduler_1.isScheduler(period)) {
8234 if (!isScheduler_1.isScheduler(scheduler)) {
8235 scheduler = async_1.async;
8237 this.scheduler = scheduler;
8238 this.dueTime = isDate_1.isDate(dueTime) ?
8239 (+dueTime - this.scheduler.now()) :
8243 * Creates an Observable that starts emitting after an `initialDelay` and
8244 * emits ever increasing numbers after each `period` of time thereafter.
8246 * <span class="informal">Its like {@link interval}, but you can specify when
8247 * should the emissions start.</span>
8249 * <img src="./img/timer.png" width="100%">
8251 * `timer` returns an Observable that emits an infinite sequence of ascending
8252 * integers, with a constant interval of time, `period` of your choosing
8253 * between those emissions. The first emission happens after the specified
8254 * `initialDelay`. The initial delay may be a {@link Date}. By default, this
8255 * operator uses the `async` IScheduler to provide a notion of time, but you
8256 * may pass any IScheduler to it. If `period` is not specified, the output
8257 * Observable emits only one value, `0`. Otherwise, it emits an infinite
8260 * @example <caption>Emits ascending numbers, one every second (1000ms), starting after 3 seconds</caption>
8261 * var numbers = Rx.Observable.timer(3000, 1000);
8262 * numbers.subscribe(x => console.log(x));
8264 * @example <caption>Emits one number after five seconds</caption>
8265 * var numbers = Rx.Observable.timer(5000);
8266 * numbers.subscribe(x => console.log(x));
8268 * @see {@link interval}
8269 * @see {@link delay}
8271 * @param {number|Date} initialDelay The initial delay time to wait before
8272 * emitting the first value of `0`.
8273 * @param {number} [period] The period of time between emissions of the
8274 * subsequent numbers.
8275 * @param {Scheduler} [scheduler=async] The IScheduler to use for scheduling
8276 * the emission of values, and providing a notion of "time".
8277 * @return {Observable} An Observable that emits a `0` after the
8278 * `initialDelay` and ever increasing numbers after each `period` of time
8284 TimerObservable.create = function (initialDelay, period, scheduler) {
8285 if (initialDelay === void 0) { initialDelay = 0; }
8286 return new TimerObservable(initialDelay, period, scheduler);
8288 TimerObservable.dispatch = function (state) {
8289 var index = state.index, period = state.period, subscriber = state.subscriber;
8291 subscriber.next(index);
8292 if (subscriber.closed) {
8295 else if (period === -1) {
8296 return subscriber.complete();
8298 state.index = index + 1;
8299 action.schedule(state, period);
8301 TimerObservable.prototype._subscribe = function (subscriber) {
8303 var _a = this, period = _a.period, dueTime = _a.dueTime, scheduler = _a.scheduler;
8304 return scheduler.schedule(TimerObservable.dispatch, dueTime, {
8305 index: index, period: period, subscriber: subscriber
8308 return TimerObservable;
8309 }(Observable_1.Observable));
8310 exports.TimerObservable = TimerObservable;
8312 },{"../Observable":29,"../scheduler/async":152,"../util/isDate":166,"../util/isNumeric":168,"../util/isScheduler":171}],97:[function(require,module,exports){
8314 var isScheduler_1 = require('../util/isScheduler');
8315 var isArray_1 = require('../util/isArray');
8316 var ArrayObservable_1 = require('./ArrayObservable');
8317 var combineLatest_1 = require('../operator/combineLatest');
8318 /* tslint:enable:max-line-length */
8320 * Combines multiple Observables to create an Observable whose values are
8321 * calculated from the latest values of each of its input Observables.
8323 * <span class="informal">Whenever any input Observable emits a value, it
8324 * computes a formula using the latest values from all the inputs, then emits
8325 * the output of that formula.</span>
8327 * <img src="./img/combineLatest.png" width="100%">
8329 * `combineLatest` combines the values from all the Observables passed as
8330 * arguments. This is done by subscribing to each Observable in order and,
8331 * whenever any Observable emits, collecting an array of the most recent
8332 * values from each Observable. So if you pass `n` Observables to operator,
8333 * returned Observable will always emit an array of `n` values, in order
8334 * corresponding to order of passed Observables (value from the first Observable
8335 * on the first place and so on).
8337 * Static version of `combineLatest` accepts either an array of Observables
8338 * or each Observable can be put directly as an argument. Note that array of
8339 * Observables is good choice, if you don't know beforehand how many Observables
8340 * you will combine. Passing empty array will result in Observable that
8341 * completes immediately.
8343 * To ensure output array has always the same length, `combineLatest` will
8344 * actually wait for all input Observables to emit at least once,
8345 * before it starts emitting results. This means if some Observable emits
8346 * values before other Observables started emitting, all that values but last
8347 * will be lost. On the other hand, is some Observable does not emit value but
8348 * completes, resulting Observable will complete at the same moment without
8349 * emitting anything, since it will be now impossible to include value from
8350 * completed Observable in resulting array. Also, if some input Observable does
8351 * not emit any value and never completes, `combineLatest` will also never emit
8352 * and never complete, since, again, it will wait for all streams to emit some
8355 * If at least one Observable was passed to `combineLatest` and all passed Observables
8356 * emitted something, resulting Observable will complete when all combined
8357 * streams complete. So even if some Observable completes, result of
8358 * `combineLatest` will still emit values when other Observables do. In case
8359 * of completed Observable, its value from now on will always be the last
8360 * emitted value. On the other hand, if any Observable errors, `combineLatest`
8361 * will error immediately as well, and all other Observables will be unsubscribed.
8363 * `combineLatest` accepts as optional parameter `project` function, which takes
8364 * as arguments all values that would normally be emitted by resulting Observable.
8365 * `project` can return any kind of value, which will be then emitted by Observable
8366 * instead of default array. Note that `project` does not take as argument that array
8367 * of values, but values themselves. That means default `project` can be imagined
8368 * as function that takes all its arguments and puts them into an array.
8371 * @example <caption>Combine two timer Observables</caption>
8372 * const firstTimer = Rx.Observable.timer(0, 1000); // emit 0, 1, 2... after every second, starting from now
8373 * const secondTimer = Rx.Observable.timer(500, 1000); // emit 0, 1, 2... after every second, starting 0,5s from now
8374 * const combinedTimers = Rx.Observable.combineLatest(firstTimer, secondTimer);
8375 * combinedTimers.subscribe(value => console.log(value));
8377 * // [0, 0] after 0.5s
8378 * // [1, 0] after 1s
8379 * // [1, 1] after 1.5s
8380 * // [2, 1] after 2s
8383 * @example <caption>Combine an array of Observables</caption>
8384 * const observables = [1, 5, 10].map(
8385 * n => Rx.Observable.of(n).delay(n * 1000).startWith(0) // emit 0 and then emit n after n seconds
8387 * const combined = Rx.Observable.combineLatest(observables);
8388 * combined.subscribe(value => console.log(value));
8390 * // [0, 0, 0] immediately
8391 * // [1, 0, 0] after 1s
8392 * // [1, 5, 0] after 5s
8393 * // [1, 5, 10] after 10s
8396 * @example <caption>Use project function to dynamically calculate the Body-Mass Index</caption>
8397 * var weight = Rx.Observable.of(70, 72, 76, 79, 75);
8398 * var height = Rx.Observable.of(1.76, 1.77, 1.78);
8399 * var bmi = Rx.Observable.combineLatest(weight, height, (w, h) => w / (h * h));
8400 * bmi.subscribe(x => console.log('BMI is ' + x));
8402 * // With output to console:
8403 * // BMI is 24.212293388429753
8404 * // BMI is 23.93948099205209
8405 * // BMI is 23.671253629592222
8408 * @see {@link combineAll}
8409 * @see {@link merge}
8410 * @see {@link withLatestFrom}
8412 * @param {ObservableInput} observable1 An input Observable to combine with other Observables.
8413 * @param {ObservableInput} observable2 An input Observable to combine with other Observables.
8414 * More than one input Observables may be given as arguments
8415 * or an array of Observables may be given as the first argument.
8416 * @param {function} [project] An optional function to project the values from
8417 * the combined latest values into a new value on the output Observable.
8418 * @param {Scheduler} [scheduler=null] The IScheduler to use for subscribing to
8419 * each input Observable.
8420 * @return {Observable} An Observable of projected values from the most recent
8421 * values from each input Observable, or an array of the most recent values from
8422 * each input Observable.
8424 * @name combineLatest
8427 function combineLatest() {
8428 var observables = [];
8429 for (var _i = 0; _i < arguments.length; _i++) {
8430 observables[_i - 0] = arguments[_i];
8433 var scheduler = null;
8434 if (isScheduler_1.isScheduler(observables[observables.length - 1])) {
8435 scheduler = observables.pop();
8437 if (typeof observables[observables.length - 1] === 'function') {
8438 project = observables.pop();
8440 // if the first and only other argument besides the resultSelector is an array
8441 // assume it's been called with `combineLatest([obs1, obs2, obs3], project)`
8442 if (observables.length === 1 && isArray_1.isArray(observables[0])) {
8443 observables = observables[0];
8445 return new ArrayObservable_1.ArrayObservable(observables, scheduler).lift(new combineLatest_1.CombineLatestOperator(project));
8447 exports.combineLatest = combineLatest;
8449 },{"../operator/combineLatest":112,"../util/isArray":164,"../util/isScheduler":171,"./ArrayObservable":86}],98:[function(require,module,exports){
8451 var DeferObservable_1 = require('./DeferObservable');
8452 exports.defer = DeferObservable_1.DeferObservable.create;
8454 },{"./DeferObservable":88}],99:[function(require,module,exports){
8456 var EmptyObservable_1 = require('./EmptyObservable');
8457 exports.empty = EmptyObservable_1.EmptyObservable.create;
8459 },{"./EmptyObservable":89}],100:[function(require,module,exports){
8461 var FromObservable_1 = require('./FromObservable');
8462 exports.from = FromObservable_1.FromObservable.create;
8464 },{"./FromObservable":92}],101:[function(require,module,exports){
8466 var FromEventObservable_1 = require('./FromEventObservable');
8467 exports.fromEvent = FromEventObservable_1.FromEventObservable.create;
8469 },{"./FromEventObservable":91}],102:[function(require,module,exports){
8471 var PromiseObservable_1 = require('./PromiseObservable');
8472 exports.fromPromise = PromiseObservable_1.PromiseObservable.create;
8474 },{"./PromiseObservable":94}],103:[function(require,module,exports){
8476 var merge_1 = require('../operator/merge');
8477 exports.merge = merge_1.mergeStatic;
8479 },{"../operator/merge":125}],104:[function(require,module,exports){
8481 var ArrayObservable_1 = require('./ArrayObservable');
8482 exports.of = ArrayObservable_1.ArrayObservable.of;
8484 },{"./ArrayObservable":86}],105:[function(require,module,exports){
8486 var ErrorObservable_1 = require('./ErrorObservable');
8487 exports._throw = ErrorObservable_1.ErrorObservable.create;
8489 },{"./ErrorObservable":90}],106:[function(require,module,exports){
8491 var TimerObservable_1 = require('./TimerObservable');
8492 exports.timer = TimerObservable_1.TimerObservable.create;
8494 },{"./TimerObservable":96}],107:[function(require,module,exports){
8496 var zip_1 = require('../operator/zip');
8497 exports.zip = zip_1.zipStatic;
8499 },{"../operator/zip":146}],108:[function(require,module,exports){
8501 var __extends = (this && this.__extends) || function (d, b) {
8502 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8503 function __() { this.constructor = d; }
8504 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8506 var OuterSubscriber_1 = require('../OuterSubscriber');
8507 var subscribeToResult_1 = require('../util/subscribeToResult');
8509 * Buffers the source Observable values until `closingNotifier` emits.
8511 * <span class="informal">Collects values from the past as an array, and emits
8512 * that array only when another Observable emits.</span>
8514 * <img src="./img/buffer.png" width="100%">
8516 * Buffers the incoming Observable values until the given `closingNotifier`
8517 * Observable emits a value, at which point it emits the buffer on the output
8518 * Observable and starts a new buffer internally, awaiting the next time
8519 * `closingNotifier` emits.
8521 * @example <caption>On every click, emit array of most recent interval events</caption>
8522 * var clicks = Rx.Observable.fromEvent(document, 'click');
8523 * var interval = Rx.Observable.interval(1000);
8524 * var buffered = interval.buffer(clicks);
8525 * buffered.subscribe(x => console.log(x));
8527 * @see {@link bufferCount}
8528 * @see {@link bufferTime}
8529 * @see {@link bufferToggle}
8530 * @see {@link bufferWhen}
8531 * @see {@link window}
8533 * @param {Observable<any>} closingNotifier An Observable that signals the
8534 * buffer to be emitted on the output Observable.
8535 * @return {Observable<T[]>} An Observable of buffers, which are arrays of
8540 function buffer(closingNotifier) {
8541 return this.lift(new BufferOperator(closingNotifier));
8543 exports.buffer = buffer;
8544 var BufferOperator = (function () {
8545 function BufferOperator(closingNotifier) {
8546 this.closingNotifier = closingNotifier;
8548 BufferOperator.prototype.call = function (subscriber, source) {
8549 return source.subscribe(new BufferSubscriber(subscriber, this.closingNotifier));
8551 return BufferOperator;
8554 * We need this JSDoc comment for affecting ESDoc.
8556 * @extends {Ignored}
8558 var BufferSubscriber = (function (_super) {
8559 __extends(BufferSubscriber, _super);
8560 function BufferSubscriber(destination, closingNotifier) {
8561 _super.call(this, destination);
8563 this.add(subscribeToResult_1.subscribeToResult(this, closingNotifier));
8565 BufferSubscriber.prototype._next = function (value) {
8566 this.buffer.push(value);
8568 BufferSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
8569 var buffer = this.buffer;
8571 this.destination.next(buffer);
8573 return BufferSubscriber;
8574 }(OuterSubscriber_1.OuterSubscriber));
8576 },{"../OuterSubscriber":31,"../util/subscribeToResult":173}],109:[function(require,module,exports){
8578 var __extends = (this && this.__extends) || function (d, b) {
8579 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8580 function __() { this.constructor = d; }
8581 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8583 var Subscriber_1 = require('../Subscriber');
8585 * Buffers the source Observable values until the size hits the maximum
8586 * `bufferSize` given.
8588 * <span class="informal">Collects values from the past as an array, and emits
8589 * that array only when its size reaches `bufferSize`.</span>
8591 * <img src="./img/bufferCount.png" width="100%">
8593 * Buffers a number of values from the source Observable by `bufferSize` then
8594 * emits the buffer and clears it, and starts a new buffer each
8595 * `startBufferEvery` values. If `startBufferEvery` is not provided or is
8596 * `null`, then new buffers are started immediately at the start of the source
8597 * and when each buffer closes and is emitted.
8599 * @example <caption>Emit the last two click events as an array</caption>
8600 * var clicks = Rx.Observable.fromEvent(document, 'click');
8601 * var buffered = clicks.bufferCount(2);
8602 * buffered.subscribe(x => console.log(x));
8604 * @example <caption>On every click, emit the last two click events as an array</caption>
8605 * var clicks = Rx.Observable.fromEvent(document, 'click');
8606 * var buffered = clicks.bufferCount(2, 1);
8607 * buffered.subscribe(x => console.log(x));
8609 * @see {@link buffer}
8610 * @see {@link bufferTime}
8611 * @see {@link bufferToggle}
8612 * @see {@link bufferWhen}
8613 * @see {@link pairwise}
8614 * @see {@link windowCount}
8616 * @param {number} bufferSize The maximum size of the buffer emitted.
8617 * @param {number} [startBufferEvery] Interval at which to start a new buffer.
8618 * For example if `startBufferEvery` is `2`, then a new buffer will be started
8619 * on every other value from the source. A new buffer is started at the
8620 * beginning of the source by default.
8621 * @return {Observable<T[]>} An Observable of arrays of buffered values.
8622 * @method bufferCount
8625 function bufferCount(bufferSize, startBufferEvery) {
8626 if (startBufferEvery === void 0) { startBufferEvery = null; }
8627 return this.lift(new BufferCountOperator(bufferSize, startBufferEvery));
8629 exports.bufferCount = bufferCount;
8630 var BufferCountOperator = (function () {
8631 function BufferCountOperator(bufferSize, startBufferEvery) {
8632 this.bufferSize = bufferSize;
8633 this.startBufferEvery = startBufferEvery;
8634 if (!startBufferEvery || bufferSize === startBufferEvery) {
8635 this.subscriberClass = BufferCountSubscriber;
8638 this.subscriberClass = BufferSkipCountSubscriber;
8641 BufferCountOperator.prototype.call = function (subscriber, source) {
8642 return source.subscribe(new this.subscriberClass(subscriber, this.bufferSize, this.startBufferEvery));
8644 return BufferCountOperator;
8647 * We need this JSDoc comment for affecting ESDoc.
8649 * @extends {Ignored}
8651 var BufferCountSubscriber = (function (_super) {
8652 __extends(BufferCountSubscriber, _super);
8653 function BufferCountSubscriber(destination, bufferSize) {
8654 _super.call(this, destination);
8655 this.bufferSize = bufferSize;
8658 BufferCountSubscriber.prototype._next = function (value) {
8659 var buffer = this.buffer;
8661 if (buffer.length == this.bufferSize) {
8662 this.destination.next(buffer);
8666 BufferCountSubscriber.prototype._complete = function () {
8667 var buffer = this.buffer;
8668 if (buffer.length > 0) {
8669 this.destination.next(buffer);
8671 _super.prototype._complete.call(this);
8673 return BufferCountSubscriber;
8674 }(Subscriber_1.Subscriber));
8676 * We need this JSDoc comment for affecting ESDoc.
8678 * @extends {Ignored}
8680 var BufferSkipCountSubscriber = (function (_super) {
8681 __extends(BufferSkipCountSubscriber, _super);
8682 function BufferSkipCountSubscriber(destination, bufferSize, startBufferEvery) {
8683 _super.call(this, destination);
8684 this.bufferSize = bufferSize;
8685 this.startBufferEvery = startBufferEvery;
8689 BufferSkipCountSubscriber.prototype._next = function (value) {
8690 var _a = this, bufferSize = _a.bufferSize, startBufferEvery = _a.startBufferEvery, buffers = _a.buffers, count = _a.count;
8692 if (count % startBufferEvery === 0) {
8695 for (var i = buffers.length; i--;) {
8696 var buffer = buffers[i];
8698 if (buffer.length === bufferSize) {
8699 buffers.splice(i, 1);
8700 this.destination.next(buffer);
8704 BufferSkipCountSubscriber.prototype._complete = function () {
8705 var _a = this, buffers = _a.buffers, destination = _a.destination;
8706 while (buffers.length > 0) {
8707 var buffer = buffers.shift();
8708 if (buffer.length > 0) {
8709 destination.next(buffer);
8712 _super.prototype._complete.call(this);
8714 return BufferSkipCountSubscriber;
8715 }(Subscriber_1.Subscriber));
8717 },{"../Subscriber":36}],110:[function(require,module,exports){
8719 var __extends = (this && this.__extends) || function (d, b) {
8720 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8721 function __() { this.constructor = d; }
8722 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8724 var Subscription_1 = require('../Subscription');
8725 var tryCatch_1 = require('../util/tryCatch');
8726 var errorObject_1 = require('../util/errorObject');
8727 var OuterSubscriber_1 = require('../OuterSubscriber');
8728 var subscribeToResult_1 = require('../util/subscribeToResult');
8730 * Buffers the source Observable values, using a factory function of closing
8731 * Observables to determine when to close, emit, and reset the buffer.
8733 * <span class="informal">Collects values from the past as an array. When it
8734 * starts collecting values, it calls a function that returns an Observable that
8735 * tells when to close the buffer and restart collecting.</span>
8737 * <img src="./img/bufferWhen.png" width="100%">
8739 * Opens a buffer immediately, then closes the buffer when the observable
8740 * returned by calling `closingSelector` function emits a value. When it closes
8741 * the buffer, it immediately opens a new buffer and repeats the process.
8743 * @example <caption>Emit an array of the last clicks every [1-5] random seconds</caption>
8744 * var clicks = Rx.Observable.fromEvent(document, 'click');
8745 * var buffered = clicks.bufferWhen(() =>
8746 * Rx.Observable.interval(1000 + Math.random() * 4000)
8748 * buffered.subscribe(x => console.log(x));
8750 * @see {@link buffer}
8751 * @see {@link bufferCount}
8752 * @see {@link bufferTime}
8753 * @see {@link bufferToggle}
8754 * @see {@link windowWhen}
8756 * @param {function(): Observable} closingSelector A function that takes no
8757 * arguments and returns an Observable that signals buffer closure.
8758 * @return {Observable<T[]>} An observable of arrays of buffered values.
8759 * @method bufferWhen
8762 function bufferWhen(closingSelector) {
8763 return this.lift(new BufferWhenOperator(closingSelector));
8765 exports.bufferWhen = bufferWhen;
8766 var BufferWhenOperator = (function () {
8767 function BufferWhenOperator(closingSelector) {
8768 this.closingSelector = closingSelector;
8770 BufferWhenOperator.prototype.call = function (subscriber, source) {
8771 return source.subscribe(new BufferWhenSubscriber(subscriber, this.closingSelector));
8773 return BufferWhenOperator;
8776 * We need this JSDoc comment for affecting ESDoc.
8778 * @extends {Ignored}
8780 var BufferWhenSubscriber = (function (_super) {
8781 __extends(BufferWhenSubscriber, _super);
8782 function BufferWhenSubscriber(destination, closingSelector) {
8783 _super.call(this, destination);
8784 this.closingSelector = closingSelector;
8785 this.subscribing = false;
8788 BufferWhenSubscriber.prototype._next = function (value) {
8789 this.buffer.push(value);
8791 BufferWhenSubscriber.prototype._complete = function () {
8792 var buffer = this.buffer;
8794 this.destination.next(buffer);
8796 _super.prototype._complete.call(this);
8798 BufferWhenSubscriber.prototype._unsubscribe = function () {
8800 this.subscribing = false;
8802 BufferWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
8805 BufferWhenSubscriber.prototype.notifyComplete = function () {
8806 if (this.subscribing) {
8813 BufferWhenSubscriber.prototype.openBuffer = function () {
8814 var closingSubscription = this.closingSubscription;
8815 if (closingSubscription) {
8816 this.remove(closingSubscription);
8817 closingSubscription.unsubscribe();
8819 var buffer = this.buffer;
8821 this.destination.next(buffer);
8824 var closingNotifier = tryCatch_1.tryCatch(this.closingSelector)();
8825 if (closingNotifier === errorObject_1.errorObject) {
8826 this.error(errorObject_1.errorObject.e);
8829 closingSubscription = new Subscription_1.Subscription();
8830 this.closingSubscription = closingSubscription;
8831 this.add(closingSubscription);
8832 this.subscribing = true;
8833 closingSubscription.add(subscribeToResult_1.subscribeToResult(this, closingNotifier));
8834 this.subscribing = false;
8837 return BufferWhenSubscriber;
8838 }(OuterSubscriber_1.OuterSubscriber));
8840 },{"../OuterSubscriber":31,"../Subscription":37,"../util/errorObject":163,"../util/subscribeToResult":173,"../util/tryCatch":175}],111:[function(require,module,exports){
8842 var __extends = (this && this.__extends) || function (d, b) {
8843 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8844 function __() { this.constructor = d; }
8845 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8847 var OuterSubscriber_1 = require('../OuterSubscriber');
8848 var subscribeToResult_1 = require('../util/subscribeToResult');
8850 * Catches errors on the observable to be handled by returning a new observable or throwing an error.
8852 * <img src="./img/catch.png" width="100%">
8854 * @example <caption>Continues with a different Observable when there's an error</caption>
8856 * Observable.of(1, 2, 3, 4, 5)
8863 * .catch(err => Observable.of('I', 'II', 'III', 'IV', 'V'))
8864 * .subscribe(x => console.log(x));
8865 * // 1, 2, 3, I, II, III, IV, V
8867 * @example <caption>Retries the caught source Observable again in case of error, similar to retry() operator</caption>
8869 * Observable.of(1, 2, 3, 4, 5)
8876 * .catch((err, caught) => caught)
8878 * .subscribe(x => console.log(x));
8879 * // 1, 2, 3, 1, 2, 3, ...
8881 * @example <caption>Throws a new error when the source Observable throws an error</caption>
8883 * Observable.of(1, 2, 3, 4, 5)
8891 * throw 'error in source. Details: ' + err;
8894 * x => console.log(x),
8895 * err => console.log(err)
8897 * // 1, 2, 3, error in source. Details: four!
8899 * @param {function} selector a function that takes as arguments `err`, which is the error, and `caught`, which
8900 * is the source observable, in case you'd like to "retry" that observable by returning it again. Whatever observable
8901 * is returned by the `selector` will be used to continue the observable chain.
8902 * @return {Observable} An observable that originates from either the source or the observable returned by the
8903 * catch `selector` function.
8908 function _catch(selector) {
8909 var operator = new CatchOperator(selector);
8910 var caught = this.lift(operator);
8911 return (operator.caught = caught);
8913 exports._catch = _catch;
8914 var CatchOperator = (function () {
8915 function CatchOperator(selector) {
8916 this.selector = selector;
8918 CatchOperator.prototype.call = function (subscriber, source) {
8919 return source.subscribe(new CatchSubscriber(subscriber, this.selector, this.caught));
8921 return CatchOperator;
8924 * We need this JSDoc comment for affecting ESDoc.
8926 * @extends {Ignored}
8928 var CatchSubscriber = (function (_super) {
8929 __extends(CatchSubscriber, _super);
8930 function CatchSubscriber(destination, selector, caught) {
8931 _super.call(this, destination);
8932 this.selector = selector;
8933 this.caught = caught;
8935 // NOTE: overriding `error` instead of `_error` because we don't want
8936 // to have this flag this subscriber as `isStopped`. We can mimic the
8937 // behavior of the RetrySubscriber (from the `retry` operator), where
8938 // we unsubscribe from our source chain, reset our Subscriber flags,
8939 // then subscribe to the selector result.
8940 CatchSubscriber.prototype.error = function (err) {
8941 if (!this.isStopped) {
8942 var result = void 0;
8944 result = this.selector(err, this.caught);
8947 _super.prototype.error.call(this, err2);
8950 this._unsubscribeAndRecycle();
8951 this.add(subscribeToResult_1.subscribeToResult(this, result));
8954 return CatchSubscriber;
8955 }(OuterSubscriber_1.OuterSubscriber));
8957 },{"../OuterSubscriber":31,"../util/subscribeToResult":173}],112:[function(require,module,exports){
8959 var __extends = (this && this.__extends) || function (d, b) {
8960 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8961 function __() { this.constructor = d; }
8962 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8964 var ArrayObservable_1 = require('../observable/ArrayObservable');
8965 var isArray_1 = require('../util/isArray');
8966 var OuterSubscriber_1 = require('../OuterSubscriber');
8967 var subscribeToResult_1 = require('../util/subscribeToResult');
8969 /* tslint:enable:max-line-length */
8971 * Combines multiple Observables to create an Observable whose values are
8972 * calculated from the latest values of each of its input Observables.
8974 * <span class="informal">Whenever any input Observable emits a value, it
8975 * computes a formula using the latest values from all the inputs, then emits
8976 * the output of that formula.</span>
8978 * <img src="./img/combineLatest.png" width="100%">
8980 * `combineLatest` combines the values from this Observable with values from
8981 * Observables passed as arguments. This is done by subscribing to each
8982 * Observable, in order, and collecting an array of each of the most recent
8983 * values any time any of the input Observables emits, then either taking that
8984 * array and passing it as arguments to an optional `project` function and
8985 * emitting the return value of that, or just emitting the array of recent
8986 * values directly if there is no `project` function.
8988 * @example <caption>Dynamically calculate the Body-Mass Index from an Observable of weight and one for height</caption>
8989 * var weight = Rx.Observable.of(70, 72, 76, 79, 75);
8990 * var height = Rx.Observable.of(1.76, 1.77, 1.78);
8991 * var bmi = weight.combineLatest(height, (w, h) => w / (h * h));
8992 * bmi.subscribe(x => console.log('BMI is ' + x));
8994 * // With output to console:
8995 * // BMI is 24.212293388429753
8996 * // BMI is 23.93948099205209
8997 * // BMI is 23.671253629592222
8999 * @see {@link combineAll}
9000 * @see {@link merge}
9001 * @see {@link withLatestFrom}
9003 * @param {ObservableInput} other An input Observable to combine with the source
9004 * Observable. More than one input Observables may be given as argument.
9005 * @param {function} [project] An optional function to project the values from
9006 * the combined latest values into a new value on the output Observable.
9007 * @return {Observable} An Observable of projected values from the most recent
9008 * values from each input Observable, or an array of the most recent values from
9009 * each input Observable.
9010 * @method combineLatest
9013 function combineLatest() {
9014 var observables = [];
9015 for (var _i = 0; _i < arguments.length; _i++) {
9016 observables[_i - 0] = arguments[_i];
9019 if (typeof observables[observables.length - 1] === 'function') {
9020 project = observables.pop();
9022 // if the first and only other argument besides the resultSelector is an array
9023 // assume it's been called with `combineLatest([obs1, obs2, obs3], project)`
9024 if (observables.length === 1 && isArray_1.isArray(observables[0])) {
9025 observables = observables[0].slice();
9027 observables.unshift(this);
9028 return this.lift.call(new ArrayObservable_1.ArrayObservable(observables), new CombineLatestOperator(project));
9030 exports.combineLatest = combineLatest;
9031 var CombineLatestOperator = (function () {
9032 function CombineLatestOperator(project) {
9033 this.project = project;
9035 CombineLatestOperator.prototype.call = function (subscriber, source) {
9036 return source.subscribe(new CombineLatestSubscriber(subscriber, this.project));
9038 return CombineLatestOperator;
9040 exports.CombineLatestOperator = CombineLatestOperator;
9042 * We need this JSDoc comment for affecting ESDoc.
9044 * @extends {Ignored}
9046 var CombineLatestSubscriber = (function (_super) {
9047 __extends(CombineLatestSubscriber, _super);
9048 function CombineLatestSubscriber(destination, project) {
9049 _super.call(this, destination);
9050 this.project = project;
9053 this.observables = [];
9055 CombineLatestSubscriber.prototype._next = function (observable) {
9056 this.values.push(none);
9057 this.observables.push(observable);
9059 CombineLatestSubscriber.prototype._complete = function () {
9060 var observables = this.observables;
9061 var len = observables.length;
9063 this.destination.complete();
9067 this.toRespond = len;
9068 for (var i = 0; i < len; i++) {
9069 var observable = observables[i];
9070 this.add(subscribeToResult_1.subscribeToResult(this, observable, observable, i));
9074 CombineLatestSubscriber.prototype.notifyComplete = function (unused) {
9075 if ((this.active -= 1) === 0) {
9076 this.destination.complete();
9079 CombineLatestSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
9080 var values = this.values;
9081 var oldVal = values[outerIndex];
9082 var toRespond = !this.toRespond
9084 : oldVal === none ? --this.toRespond : this.toRespond;
9085 values[outerIndex] = innerValue;
9086 if (toRespond === 0) {
9088 this._tryProject(values);
9091 this.destination.next(values.slice());
9095 CombineLatestSubscriber.prototype._tryProject = function (values) {
9098 result = this.project.apply(this, values);
9101 this.destination.error(err);
9104 this.destination.next(result);
9106 return CombineLatestSubscriber;
9107 }(OuterSubscriber_1.OuterSubscriber));
9108 exports.CombineLatestSubscriber = CombineLatestSubscriber;
9110 },{"../OuterSubscriber":31,"../observable/ArrayObservable":86,"../util/isArray":164,"../util/subscribeToResult":173}],113:[function(require,module,exports){
9112 var Observable_1 = require('../Observable');
9113 var isScheduler_1 = require('../util/isScheduler');
9114 var ArrayObservable_1 = require('../observable/ArrayObservable');
9115 var mergeAll_1 = require('./mergeAll');
9116 /* tslint:enable:max-line-length */
9118 * Creates an output Observable which sequentially emits all values from every
9119 * given input Observable after the current Observable.
9121 * <span class="informal">Concatenates multiple Observables together by
9122 * sequentially emitting their values, one Observable after the other.</span>
9124 * <img src="./img/concat.png" width="100%">
9126 * Joins this Observable with multiple other Observables by subscribing to them
9127 * one at a time, starting with the source, and merging their results into the
9128 * output Observable. Will wait for each Observable to complete before moving
9131 * @example <caption>Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10</caption>
9132 * var timer = Rx.Observable.interval(1000).take(4);
9133 * var sequence = Rx.Observable.range(1, 10);
9134 * var result = timer.concat(sequence);
9135 * result.subscribe(x => console.log(x));
9138 * // 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10
9140 * @example <caption>Concatenate 3 Observables</caption>
9141 * var timer1 = Rx.Observable.interval(1000).take(10);
9142 * var timer2 = Rx.Observable.interval(2000).take(6);
9143 * var timer3 = Rx.Observable.interval(500).take(10);
9144 * var result = timer1.concat(timer2, timer3);
9145 * result.subscribe(x => console.log(x));
9147 * // results in the following:
9148 * // (Prints to console sequentially)
9149 * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9
9150 * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5
9151 * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9
9153 * @see {@link concatAll}
9154 * @see {@link concatMap}
9155 * @see {@link concatMapTo}
9157 * @param {ObservableInput} other An input Observable to concatenate after the source
9158 * Observable. More than one input Observables may be given as argument.
9159 * @param {Scheduler} [scheduler=null] An optional IScheduler to schedule each
9160 * Observable subscription on.
9161 * @return {Observable} All values of each passed Observable merged into a
9162 * single Observable, in order, in serial fashion.
9167 var observables = [];
9168 for (var _i = 0; _i < arguments.length; _i++) {
9169 observables[_i - 0] = arguments[_i];
9171 return this.lift.call(concatStatic.apply(void 0, [this].concat(observables)));
9173 exports.concat = concat;
9174 /* tslint:enable:max-line-length */
9176 * Creates an output Observable which sequentially emits all values from given
9177 * Observable and then moves on to the next.
9179 * <span class="informal">Concatenates multiple Observables together by
9180 * sequentially emitting their values, one Observable after the other.</span>
9182 * <img src="./img/concat.png" width="100%">
9184 * `concat` joins multiple Observables together, by subscribing to them one at a time and
9185 * merging their results into the output Observable. You can pass either an array of
9186 * Observables, or put them directly as arguments. Passing an empty array will result
9187 * in Observable that completes immediately.
9189 * `concat` will subscribe to first input Observable and emit all its values, without
9190 * changing or affecting them in any way. When that Observable completes, it will
9191 * subscribe to then next Observable passed and, again, emit its values. This will be
9192 * repeated, until the operator runs out of Observables. When last input Observable completes,
9193 * `concat` will complete as well. At any given moment only one Observable passed to operator
9194 * emits values. If you would like to emit values from passed Observables concurrently, check out
9195 * {@link merge} instead, especially with optional `concurrent` parameter. As a matter of fact,
9196 * `concat` is an equivalent of `merge` operator with `concurrent` parameter set to `1`.
9198 * Note that if some input Observable never completes, `concat` will also never complete
9199 * and Observables following the one that did not complete will never be subscribed. On the other
9200 * hand, if some Observable simply completes immediately after it is subscribed, it will be
9201 * invisible for `concat`, which will just move on to the next Observable.
9203 * If any Observable in chain errors, instead of passing control to the next Observable,
9204 * `concat` will error immediately as well. Observables that would be subscribed after
9205 * the one that emitted error, never will.
9207 * If you pass to `concat` the same Observable many times, its stream of values
9208 * will be "replayed" on every subscription, which means you can repeat given Observable
9209 * as many times as you like. If passing the same Observable to `concat` 1000 times becomes tedious,
9210 * you can always use {@link repeat}.
9212 * @example <caption>Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10</caption>
9213 * var timer = Rx.Observable.interval(1000).take(4);
9214 * var sequence = Rx.Observable.range(1, 10);
9215 * var result = Rx.Observable.concat(timer, sequence);
9216 * result.subscribe(x => console.log(x));
9219 * // 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10
9222 * @example <caption>Concatenate an array of 3 Observables</caption>
9223 * var timer1 = Rx.Observable.interval(1000).take(10);
9224 * var timer2 = Rx.Observable.interval(2000).take(6);
9225 * var timer3 = Rx.Observable.interval(500).take(10);
9226 * var result = Rx.Observable.concat([timer1, timer2, timer3]); // note that array is passed
9227 * result.subscribe(x => console.log(x));
9229 * // results in the following:
9230 * // (Prints to console sequentially)
9231 * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9
9232 * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5
9233 * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9
9236 * @example <caption>Concatenate the same Observable to repeat it</caption>
9237 * const timer = Rx.Observable.interval(1000).take(2);
9239 * Rx.Observable.concat(timer, timer) // concating the same Observable!
9241 * value => console.log(value),
9243 * () => console.log('...and it is done!')
9251 * // "...and it is done!" also after 4s
9253 * @see {@link concatAll}
9254 * @see {@link concatMap}
9255 * @see {@link concatMapTo}
9257 * @param {ObservableInput} input1 An input Observable to concatenate with others.
9258 * @param {ObservableInput} input2 An input Observable to concatenate with others.
9259 * More than one input Observables may be given as argument.
9260 * @param {Scheduler} [scheduler=null] An optional IScheduler to schedule each
9261 * Observable subscription on.
9262 * @return {Observable} All values of each passed Observable merged into a
9263 * single Observable, in order, in serial fashion.
9268 function concatStatic() {
9269 var observables = [];
9270 for (var _i = 0; _i < arguments.length; _i++) {
9271 observables[_i - 0] = arguments[_i];
9273 var scheduler = null;
9274 var args = observables;
9275 if (isScheduler_1.isScheduler(args[observables.length - 1])) {
9276 scheduler = args.pop();
9278 if (scheduler === null && observables.length === 1 && observables[0] instanceof Observable_1.Observable) {
9279 return observables[0];
9281 return new ArrayObservable_1.ArrayObservable(observables, scheduler).lift(new mergeAll_1.MergeAllOperator(1));
9283 exports.concatStatic = concatStatic;
9285 },{"../Observable":29,"../observable/ArrayObservable":86,"../util/isScheduler":171,"./mergeAll":126}],114:[function(require,module,exports){
9287 var __extends = (this && this.__extends) || function (d, b) {
9288 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9289 function __() { this.constructor = d; }
9290 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9292 var Subscriber_1 = require('../Subscriber');
9293 var async_1 = require('../scheduler/async');
9295 * Emits a value from the source Observable only after a particular time span
9296 * has passed without another source emission.
9298 * <span class="informal">It's like {@link delay}, but passes only the most
9299 * recent value from each burst of emissions.</span>
9301 * <img src="./img/debounceTime.png" width="100%">
9303 * `debounceTime` delays values emitted by the source Observable, but drops
9304 * previous pending delayed emissions if a new value arrives on the source
9305 * Observable. This operator keeps track of the most recent value from the
9306 * source Observable, and emits that only when `dueTime` enough time has passed
9307 * without any other value appearing on the source Observable. If a new value
9308 * appears before `dueTime` silence occurs, the previous value will be dropped
9309 * and will not be emitted on the output Observable.
9311 * This is a rate-limiting operator, because it is impossible for more than one
9312 * value to be emitted in any time window of duration `dueTime`, but it is also
9313 * a delay-like operator since output emissions do not occur at the same time as
9314 * they did on the source Observable. Optionally takes a {@link IScheduler} for
9317 * @example <caption>Emit the most recent click after a burst of clicks</caption>
9318 * var clicks = Rx.Observable.fromEvent(document, 'click');
9319 * var result = clicks.debounceTime(1000);
9320 * result.subscribe(x => console.log(x));
9322 * @see {@link auditTime}
9323 * @see {@link debounce}
9324 * @see {@link delay}
9325 * @see {@link sampleTime}
9326 * @see {@link throttleTime}
9328 * @param {number} dueTime The timeout duration in milliseconds (or the time
9329 * unit determined internally by the optional `scheduler`) for the window of
9330 * time required to wait for emission silence before emitting the most recent
9332 * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
9333 * managing the timers that handle the timeout for each value.
9334 * @return {Observable} An Observable that delays the emissions of the source
9335 * Observable by the specified `dueTime`, and may drop some values if they occur
9337 * @method debounceTime
9340 function debounceTime(dueTime, scheduler) {
9341 if (scheduler === void 0) { scheduler = async_1.async; }
9342 return this.lift(new DebounceTimeOperator(dueTime, scheduler));
9344 exports.debounceTime = debounceTime;
9345 var DebounceTimeOperator = (function () {
9346 function DebounceTimeOperator(dueTime, scheduler) {
9347 this.dueTime = dueTime;
9348 this.scheduler = scheduler;
9350 DebounceTimeOperator.prototype.call = function (subscriber, source) {
9351 return source.subscribe(new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler));
9353 return DebounceTimeOperator;
9356 * We need this JSDoc comment for affecting ESDoc.
9358 * @extends {Ignored}
9360 var DebounceTimeSubscriber = (function (_super) {
9361 __extends(DebounceTimeSubscriber, _super);
9362 function DebounceTimeSubscriber(destination, dueTime, scheduler) {
9363 _super.call(this, destination);
9364 this.dueTime = dueTime;
9365 this.scheduler = scheduler;
9366 this.debouncedSubscription = null;
9367 this.lastValue = null;
9368 this.hasValue = false;
9370 DebounceTimeSubscriber.prototype._next = function (value) {
9371 this.clearDebounce();
9372 this.lastValue = value;
9373 this.hasValue = true;
9374 this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext, this.dueTime, this));
9376 DebounceTimeSubscriber.prototype._complete = function () {
9377 this.debouncedNext();
9378 this.destination.complete();
9380 DebounceTimeSubscriber.prototype.debouncedNext = function () {
9381 this.clearDebounce();
9382 if (this.hasValue) {
9383 this.destination.next(this.lastValue);
9384 this.lastValue = null;
9385 this.hasValue = false;
9388 DebounceTimeSubscriber.prototype.clearDebounce = function () {
9389 var debouncedSubscription = this.debouncedSubscription;
9390 if (debouncedSubscription !== null) {
9391 this.remove(debouncedSubscription);
9392 debouncedSubscription.unsubscribe();
9393 this.debouncedSubscription = null;
9396 return DebounceTimeSubscriber;
9397 }(Subscriber_1.Subscriber));
9398 function dispatchNext(subscriber) {
9399 subscriber.debouncedNext();
9402 },{"../Subscriber":36,"../scheduler/async":152}],115:[function(require,module,exports){
9404 var __extends = (this && this.__extends) || function (d, b) {
9405 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9406 function __() { this.constructor = d; }
9407 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9409 var async_1 = require('../scheduler/async');
9410 var isDate_1 = require('../util/isDate');
9411 var Subscriber_1 = require('../Subscriber');
9412 var Notification_1 = require('../Notification');
9414 * Delays the emission of items from the source Observable by a given timeout or
9415 * until a given Date.
9417 * <span class="informal">Time shifts each item by some specified amount of
9418 * milliseconds.</span>
9420 * <img src="./img/delay.png" width="100%">
9422 * If the delay argument is a Number, this operator time shifts the source
9423 * Observable by that amount of time expressed in milliseconds. The relative
9424 * time intervals between the values are preserved.
9426 * If the delay argument is a Date, this operator time shifts the start of the
9427 * Observable execution until the given date occurs.
9429 * @example <caption>Delay each click by one second</caption>
9430 * var clicks = Rx.Observable.fromEvent(document, 'click');
9431 * var delayedClicks = clicks.delay(1000); // each click emitted after 1 second
9432 * delayedClicks.subscribe(x => console.log(x));
9434 * @example <caption>Delay all clicks until a future date happens</caption>
9435 * var clicks = Rx.Observable.fromEvent(document, 'click');
9436 * var date = new Date('March 15, 2050 12:00:00'); // in the future
9437 * var delayedClicks = clicks.delay(date); // click emitted only after that date
9438 * delayedClicks.subscribe(x => console.log(x));
9440 * @see {@link debounceTime}
9441 * @see {@link delayWhen}
9443 * @param {number|Date} delay The delay duration in milliseconds (a `number`) or
9444 * a `Date` until which the emission of the source items is delayed.
9445 * @param {Scheduler} [scheduler=async] The IScheduler to use for
9446 * managing the timers that handle the time-shift for each item.
9447 * @return {Observable} An Observable that delays the emissions of the source
9448 * Observable by the specified timeout or Date.
9452 function delay(delay, scheduler) {
9453 if (scheduler === void 0) { scheduler = async_1.async; }
9454 var absoluteDelay = isDate_1.isDate(delay);
9455 var delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(delay);
9456 return this.lift(new DelayOperator(delayFor, scheduler));
9458 exports.delay = delay;
9459 var DelayOperator = (function () {
9460 function DelayOperator(delay, scheduler) {
9462 this.scheduler = scheduler;
9464 DelayOperator.prototype.call = function (subscriber, source) {
9465 return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler));
9467 return DelayOperator;
9470 * We need this JSDoc comment for affecting ESDoc.
9472 * @extends {Ignored}
9474 var DelaySubscriber = (function (_super) {
9475 __extends(DelaySubscriber, _super);
9476 function DelaySubscriber(destination, delay, scheduler) {
9477 _super.call(this, destination);
9479 this.scheduler = scheduler;
9481 this.active = false;
9482 this.errored = false;
9484 DelaySubscriber.dispatch = function (state) {
9485 var source = state.source;
9486 var queue = source.queue;
9487 var scheduler = state.scheduler;
9488 var destination = state.destination;
9489 while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) {
9490 queue.shift().notification.observe(destination);
9492 if (queue.length > 0) {
9493 var delay_1 = Math.max(0, queue[0].time - scheduler.now());
9494 this.schedule(state, delay_1);
9497 source.active = false;
9500 DelaySubscriber.prototype._schedule = function (scheduler) {
9502 this.add(scheduler.schedule(DelaySubscriber.dispatch, this.delay, {
9503 source: this, destination: this.destination, scheduler: scheduler
9506 DelaySubscriber.prototype.scheduleNotification = function (notification) {
9507 if (this.errored === true) {
9510 var scheduler = this.scheduler;
9511 var message = new DelayMessage(scheduler.now() + this.delay, notification);
9512 this.queue.push(message);
9513 if (this.active === false) {
9514 this._schedule(scheduler);
9517 DelaySubscriber.prototype._next = function (value) {
9518 this.scheduleNotification(Notification_1.Notification.createNext(value));
9520 DelaySubscriber.prototype._error = function (err) {
9521 this.errored = true;
9523 this.destination.error(err);
9525 DelaySubscriber.prototype._complete = function () {
9526 this.scheduleNotification(Notification_1.Notification.createComplete());
9528 return DelaySubscriber;
9529 }(Subscriber_1.Subscriber));
9530 var DelayMessage = (function () {
9531 function DelayMessage(time, notification) {
9533 this.notification = notification;
9535 return DelayMessage;
9538 },{"../Notification":28,"../Subscriber":36,"../scheduler/async":152,"../util/isDate":166}],116:[function(require,module,exports){
9540 var __extends = (this && this.__extends) || function (d, b) {
9541 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9542 function __() { this.constructor = d; }
9543 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9545 var OuterSubscriber_1 = require('../OuterSubscriber');
9546 var subscribeToResult_1 = require('../util/subscribeToResult');
9547 var Set_1 = require('../util/Set');
9549 * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from previous items.
9551 * If a keySelector function is provided, then it will project each value from the source observable into a new value that it will
9552 * check for equality with previously projected values. If a keySelector function is not provided, it will use each value from the
9553 * source observable directly with an equality check against previous values.
9555 * In JavaScript runtimes that support `Set`, this operator will use a `Set` to improve performance of the distinct value checking.
9557 * In other runtimes, this operator will use a minimal implementation of `Set` that relies on an `Array` and `indexOf` under the
9558 * hood, so performance will degrade as more values are checked for distinction. Even in newer browsers, a long-running `distinct`
9559 * use might result in memory leaks. To help alleviate this in some scenarios, an optional `flushes` parameter is also provided so
9560 * that the internal `Set` can be "flushed", basically clearing it of values.
9562 * @example <caption>A simple example with numbers</caption>
9563 * Observable.of(1, 1, 2, 2, 2, 1, 2, 3, 4, 3, 2, 1)
9565 * .subscribe(x => console.log(x)); // 1, 2, 3, 4
9567 * @example <caption>An example using a keySelector function</caption>
9568 * interface Person {
9573 * Observable.of<Person>(
9574 * { age: 4, name: 'Foo'},
9575 * { age: 7, name: 'Bar'},
9576 * { age: 5, name: 'Foo'})
9577 * .distinct((p: Person) => p.name)
9578 * .subscribe(x => console.log(x));
9581 * // { age: 4, name: 'Foo' }
9582 * // { age: 7, name: 'Bar' }
9584 * @see {@link distinctUntilChanged}
9585 * @see {@link distinctUntilKeyChanged}
9587 * @param {function} [keySelector] Optional function to select which value you want to check as distinct.
9588 * @param {Observable} [flushes] Optional Observable for flushing the internal HashSet of the operator.
9589 * @return {Observable} An Observable that emits items from the source Observable with distinct values.
9593 function distinct(keySelector, flushes) {
9594 return this.lift(new DistinctOperator(keySelector, flushes));
9596 exports.distinct = distinct;
9597 var DistinctOperator = (function () {
9598 function DistinctOperator(keySelector, flushes) {
9599 this.keySelector = keySelector;
9600 this.flushes = flushes;
9602 DistinctOperator.prototype.call = function (subscriber, source) {
9603 return source.subscribe(new DistinctSubscriber(subscriber, this.keySelector, this.flushes));
9605 return DistinctOperator;
9608 * We need this JSDoc comment for affecting ESDoc.
9610 * @extends {Ignored}
9612 var DistinctSubscriber = (function (_super) {
9613 __extends(DistinctSubscriber, _super);
9614 function DistinctSubscriber(destination, keySelector, flushes) {
9615 _super.call(this, destination);
9616 this.keySelector = keySelector;
9617 this.values = new Set_1.Set();
9619 this.add(subscribeToResult_1.subscribeToResult(this, flushes));
9622 DistinctSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
9623 this.values.clear();
9625 DistinctSubscriber.prototype.notifyError = function (error, innerSub) {
9628 DistinctSubscriber.prototype._next = function (value) {
9629 if (this.keySelector) {
9630 this._useKeySelector(value);
9633 this._finalizeNext(value, value);
9636 DistinctSubscriber.prototype._useKeySelector = function (value) {
9638 var destination = this.destination;
9640 key = this.keySelector(value);
9643 destination.error(err);
9646 this._finalizeNext(key, value);
9648 DistinctSubscriber.prototype._finalizeNext = function (key, value) {
9649 var values = this.values;
9650 if (!values.has(key)) {
9652 this.destination.next(value);
9655 return DistinctSubscriber;
9656 }(OuterSubscriber_1.OuterSubscriber));
9657 exports.DistinctSubscriber = DistinctSubscriber;
9659 },{"../OuterSubscriber":31,"../util/Set":161,"../util/subscribeToResult":173}],117:[function(require,module,exports){
9661 var __extends = (this && this.__extends) || function (d, b) {
9662 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9663 function __() { this.constructor = d; }
9664 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9666 var Subscriber_1 = require('../Subscriber');
9667 var tryCatch_1 = require('../util/tryCatch');
9668 var errorObject_1 = require('../util/errorObject');
9669 /* tslint:enable:max-line-length */
9671 * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item.
9673 * 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.
9675 * If a comparator function is not provided, an equality check is used by default.
9677 * @example <caption>A simple example with numbers</caption>
9678 * Observable.of(1, 1, 2, 2, 2, 1, 1, 2, 3, 3, 4)
9679 * .distinctUntilChanged()
9680 * .subscribe(x => console.log(x)); // 1, 2, 1, 2, 3, 4
9682 * @example <caption>An example using a compare function</caption>
9683 * interface Person {
9688 * Observable.of<Person>(
9689 * { age: 4, name: 'Foo'},
9690 * { age: 7, name: 'Bar'},
9691 * { age: 5, name: 'Foo'})
9692 * { age: 6, name: 'Foo'})
9693 * .distinctUntilChanged((p: Person, q: Person) => p.name === q.name)
9694 * .subscribe(x => console.log(x));
9697 * // { age: 4, name: 'Foo' }
9698 * // { age: 7, name: 'Bar' }
9699 * // { age: 5, name: 'Foo' }
9701 * @see {@link distinct}
9702 * @see {@link distinctUntilKeyChanged}
9704 * @param {function} [compare] Optional comparison function called to test if an item is distinct from the previous item in the source.
9705 * @return {Observable} An Observable that emits items from the source Observable with distinct values.
9706 * @method distinctUntilChanged
9709 function distinctUntilChanged(compare, keySelector) {
9710 return this.lift(new DistinctUntilChangedOperator(compare, keySelector));
9712 exports.distinctUntilChanged = distinctUntilChanged;
9713 var DistinctUntilChangedOperator = (function () {
9714 function DistinctUntilChangedOperator(compare, keySelector) {
9715 this.compare = compare;
9716 this.keySelector = keySelector;
9718 DistinctUntilChangedOperator.prototype.call = function (subscriber, source) {
9719 return source.subscribe(new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector));
9721 return DistinctUntilChangedOperator;
9724 * We need this JSDoc comment for affecting ESDoc.
9726 * @extends {Ignored}
9728 var DistinctUntilChangedSubscriber = (function (_super) {
9729 __extends(DistinctUntilChangedSubscriber, _super);
9730 function DistinctUntilChangedSubscriber(destination, compare, keySelector) {
9731 _super.call(this, destination);
9732 this.keySelector = keySelector;
9733 this.hasKey = false;
9734 if (typeof compare === 'function') {
9735 this.compare = compare;
9738 DistinctUntilChangedSubscriber.prototype.compare = function (x, y) {
9741 DistinctUntilChangedSubscriber.prototype._next = function (value) {
9742 var keySelector = this.keySelector;
9745 key = tryCatch_1.tryCatch(this.keySelector)(value);
9746 if (key === errorObject_1.errorObject) {
9747 return this.destination.error(errorObject_1.errorObject.e);
9752 result = tryCatch_1.tryCatch(this.compare)(this.key, key);
9753 if (result === errorObject_1.errorObject) {
9754 return this.destination.error(errorObject_1.errorObject.e);
9760 if (Boolean(result) === false) {
9762 this.destination.next(value);
9765 return DistinctUntilChangedSubscriber;
9766 }(Subscriber_1.Subscriber));
9768 },{"../Subscriber":36,"../util/errorObject":163,"../util/tryCatch":175}],118:[function(require,module,exports){
9770 var __extends = (this && this.__extends) || function (d, b) {
9771 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9772 function __() { this.constructor = d; }
9773 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9775 var Subscriber_1 = require('../Subscriber');
9776 /* tslint:enable:max-line-length */
9778 * Perform a side effect for every emission on the source Observable, but return
9779 * an Observable that is identical to the source.
9781 * <span class="informal">Intercepts each emission on the source and runs a
9782 * function, but returns an output which is identical to the source as long as errors don't occur.</span>
9784 * <img src="./img/do.png" width="100%">
9786 * Returns a mirrored Observable of the source Observable, but modified so that
9787 * the provided Observer is called to perform a side effect for every value,
9788 * error, and completion emitted by the source. Any errors that are thrown in
9789 * the aforementioned Observer or handlers are safely sent down the error path
9790 * of the output Observable.
9792 * This operator is useful for debugging your Observables for the correct values
9793 * or performing other side effects.
9795 * Note: this is different to a `subscribe` on the Observable. If the Observable
9796 * returned by `do` is not subscribed, the side effects specified by the
9797 * Observer will never happen. `do` therefore simply spies on existing
9798 * execution, it does not trigger an execution to happen like `subscribe` does.
9800 * @example <caption>Map every click to the clientX position of that click, while also logging the click event</caption>
9801 * var clicks = Rx.Observable.fromEvent(document, 'click');
9802 * var positions = clicks
9803 * .do(ev => console.log(ev))
9804 * .map(ev => ev.clientX);
9805 * positions.subscribe(x => console.log(x));
9808 * @see {@link subscribe}
9810 * @param {Observer|function} [nextOrObserver] A normal Observer object or a
9811 * callback for `next`.
9812 * @param {function} [error] Callback for errors in the source.
9813 * @param {function} [complete] Callback for the completion of the source.
9814 * @return {Observable} An Observable identical to the source, but runs the
9815 * specified Observer or callback(s) for each item.
9820 function _do(nextOrObserver, error, complete) {
9821 return this.lift(new DoOperator(nextOrObserver, error, complete));
9824 var DoOperator = (function () {
9825 function DoOperator(nextOrObserver, error, complete) {
9826 this.nextOrObserver = nextOrObserver;
9828 this.complete = complete;
9830 DoOperator.prototype.call = function (subscriber, source) {
9831 return source.subscribe(new DoSubscriber(subscriber, this.nextOrObserver, this.error, this.complete));
9836 * We need this JSDoc comment for affecting ESDoc.
9838 * @extends {Ignored}
9840 var DoSubscriber = (function (_super) {
9841 __extends(DoSubscriber, _super);
9842 function DoSubscriber(destination, nextOrObserver, error, complete) {
9843 _super.call(this, destination);
9844 var safeSubscriber = new Subscriber_1.Subscriber(nextOrObserver, error, complete);
9845 safeSubscriber.syncErrorThrowable = true;
9846 this.add(safeSubscriber);
9847 this.safeSubscriber = safeSubscriber;
9849 DoSubscriber.prototype._next = function (value) {
9850 var safeSubscriber = this.safeSubscriber;
9851 safeSubscriber.next(value);
9852 if (safeSubscriber.syncErrorThrown) {
9853 this.destination.error(safeSubscriber.syncErrorValue);
9856 this.destination.next(value);
9859 DoSubscriber.prototype._error = function (err) {
9860 var safeSubscriber = this.safeSubscriber;
9861 safeSubscriber.error(err);
9862 if (safeSubscriber.syncErrorThrown) {
9863 this.destination.error(safeSubscriber.syncErrorValue);
9866 this.destination.error(err);
9869 DoSubscriber.prototype._complete = function () {
9870 var safeSubscriber = this.safeSubscriber;
9871 safeSubscriber.complete();
9872 if (safeSubscriber.syncErrorThrown) {
9873 this.destination.error(safeSubscriber.syncErrorValue);
9876 this.destination.complete();
9879 return DoSubscriber;
9880 }(Subscriber_1.Subscriber));
9882 },{"../Subscriber":36}],119:[function(require,module,exports){
9884 var __extends = (this && this.__extends) || function (d, b) {
9885 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
9886 function __() { this.constructor = d; }
9887 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
9889 var tryCatch_1 = require('../util/tryCatch');
9890 var errorObject_1 = require('../util/errorObject');
9891 var OuterSubscriber_1 = require('../OuterSubscriber');
9892 var subscribeToResult_1 = require('../util/subscribeToResult');
9893 /* tslint:enable:max-line-length */
9895 * Recursively projects each source value to an Observable which is merged in
9896 * the output Observable.
9898 * <span class="informal">It's similar to {@link mergeMap}, but applies the
9899 * projection function to every source value as well as every output value.
9900 * It's recursive.</span>
9902 * <img src="./img/expand.png" width="100%">
9904 * Returns an Observable that emits items based on applying a function that you
9905 * supply to each item emitted by the source Observable, where that function
9906 * returns an Observable, and then merging those resulting Observables and
9907 * emitting the results of this merger. *Expand* will re-emit on the output
9908 * Observable every source value. Then, each output value is given to the
9909 * `project` function which returns an inner Observable to be merged on the
9910 * output Observable. Those output values resulting from the projection are also
9911 * given to the `project` function to produce new output values. This is how
9912 * *expand* behaves recursively.
9914 * @example <caption>Start emitting the powers of two on every click, at most 10 of them</caption>
9915 * var clicks = Rx.Observable.fromEvent(document, 'click');
9916 * var powersOfTwo = clicks
9918 * .expand(x => Rx.Observable.of(2 * x).delay(1000))
9920 * powersOfTwo.subscribe(x => console.log(x));
9922 * @see {@link mergeMap}
9923 * @see {@link mergeScan}
9925 * @param {function(value: T, index: number) => Observable} project A function
9926 * that, when applied to an item emitted by the source or the output Observable,
9927 * returns an Observable.
9928 * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
9929 * Observables being subscribed to concurrently.
9930 * @param {Scheduler} [scheduler=null] The IScheduler to use for subscribing to
9931 * each projected inner Observable.
9932 * @return {Observable} An Observable that emits the source values and also
9933 * result of applying the projection function to each value emitted on the
9934 * output Observable and and merging the results of the Observables obtained
9935 * from this transformation.
9939 function expand(project, concurrent, scheduler) {
9940 if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
9941 if (scheduler === void 0) { scheduler = undefined; }
9942 concurrent = (concurrent || 0) < 1 ? Number.POSITIVE_INFINITY : concurrent;
9943 return this.lift(new ExpandOperator(project, concurrent, scheduler));
9945 exports.expand = expand;
9946 var ExpandOperator = (function () {
9947 function ExpandOperator(project, concurrent, scheduler) {
9948 this.project = project;
9949 this.concurrent = concurrent;
9950 this.scheduler = scheduler;
9952 ExpandOperator.prototype.call = function (subscriber, source) {
9953 return source.subscribe(new ExpandSubscriber(subscriber, this.project, this.concurrent, this.scheduler));
9955 return ExpandOperator;
9957 exports.ExpandOperator = ExpandOperator;
9959 * We need this JSDoc comment for affecting ESDoc.
9961 * @extends {Ignored}
9963 var ExpandSubscriber = (function (_super) {
9964 __extends(ExpandSubscriber, _super);
9965 function ExpandSubscriber(destination, project, concurrent, scheduler) {
9966 _super.call(this, destination);
9967 this.project = project;
9968 this.concurrent = concurrent;
9969 this.scheduler = scheduler;
9972 this.hasCompleted = false;
9973 if (concurrent < Number.POSITIVE_INFINITY) {
9977 ExpandSubscriber.dispatch = function (arg) {
9978 var subscriber = arg.subscriber, result = arg.result, value = arg.value, index = arg.index;
9979 subscriber.subscribeToProjection(result, value, index);
9981 ExpandSubscriber.prototype._next = function (value) {
9982 var destination = this.destination;
9983 if (destination.closed) {
9987 var index = this.index++;
9988 if (this.active < this.concurrent) {
9989 destination.next(value);
9990 var result = tryCatch_1.tryCatch(this.project)(value, index);
9991 if (result === errorObject_1.errorObject) {
9992 destination.error(errorObject_1.errorObject.e);
9994 else if (!this.scheduler) {
9995 this.subscribeToProjection(result, value, index);
9998 var state = { subscriber: this, result: result, value: value, index: index };
9999 this.add(this.scheduler.schedule(ExpandSubscriber.dispatch, 0, state));
10003 this.buffer.push(value);
10006 ExpandSubscriber.prototype.subscribeToProjection = function (result, value, index) {
10008 this.add(subscribeToResult_1.subscribeToResult(this, result, value, index));
10010 ExpandSubscriber.prototype._complete = function () {
10011 this.hasCompleted = true;
10012 if (this.hasCompleted && this.active === 0) {
10013 this.destination.complete();
10016 ExpandSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
10017 this._next(innerValue);
10019 ExpandSubscriber.prototype.notifyComplete = function (innerSub) {
10020 var buffer = this.buffer;
10021 this.remove(innerSub);
10023 if (buffer && buffer.length > 0) {
10024 this._next(buffer.shift());
10026 if (this.hasCompleted && this.active === 0) {
10027 this.destination.complete();
10030 return ExpandSubscriber;
10031 }(OuterSubscriber_1.OuterSubscriber));
10032 exports.ExpandSubscriber = ExpandSubscriber;
10034 },{"../OuterSubscriber":31,"../util/errorObject":163,"../util/subscribeToResult":173,"../util/tryCatch":175}],120:[function(require,module,exports){
10036 var __extends = (this && this.__extends) || function (d, b) {
10037 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10038 function __() { this.constructor = d; }
10039 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10041 var Subscriber_1 = require('../Subscriber');
10042 /* tslint:enable:max-line-length */
10044 * Filter items emitted by the source Observable by only emitting those that
10045 * satisfy a specified predicate.
10047 * <span class="informal">Like
10048 * [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter),
10049 * it only emits a value from the source if it passes a criterion function.</span>
10051 * <img src="./img/filter.png" width="100%">
10053 * Similar to the well-known `Array.prototype.filter` method, this operator
10054 * takes values from the source Observable, passes them through a `predicate`
10055 * function and only emits those values that yielded `true`.
10057 * @example <caption>Emit only click events whose target was a DIV element</caption>
10058 * var clicks = Rx.Observable.fromEvent(document, 'click');
10059 * var clicksOnDivs = clicks.filter(ev => ev.target.tagName === 'DIV');
10060 * clicksOnDivs.subscribe(x => console.log(x));
10062 * @see {@link distinct}
10063 * @see {@link distinctUntilChanged}
10064 * @see {@link distinctUntilKeyChanged}
10065 * @see {@link ignoreElements}
10066 * @see {@link partition}
10067 * @see {@link skip}
10069 * @param {function(value: T, index: number): boolean} predicate A function that
10070 * evaluates each value emitted by the source Observable. If it returns `true`,
10071 * the value is emitted, if `false` the value is not passed to the output
10072 * Observable. The `index` parameter is the number `i` for the i-th source
10073 * emission that has happened since the subscription, starting from the number
10075 * @param {any} [thisArg] An optional argument to determine the value of `this`
10076 * in the `predicate` function.
10077 * @return {Observable} An Observable of values from the source that were
10078 * allowed by the `predicate` function.
10080 * @owner Observable
10082 function filter(predicate, thisArg) {
10083 return this.lift(new FilterOperator(predicate, thisArg));
10085 exports.filter = filter;
10086 var FilterOperator = (function () {
10087 function FilterOperator(predicate, thisArg) {
10088 this.predicate = predicate;
10089 this.thisArg = thisArg;
10091 FilterOperator.prototype.call = function (subscriber, source) {
10092 return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg));
10094 return FilterOperator;
10097 * We need this JSDoc comment for affecting ESDoc.
10099 * @extends {Ignored}
10101 var FilterSubscriber = (function (_super) {
10102 __extends(FilterSubscriber, _super);
10103 function FilterSubscriber(destination, predicate, thisArg) {
10104 _super.call(this, destination);
10105 this.predicate = predicate;
10106 this.thisArg = thisArg;
10108 this.predicate = predicate;
10110 // the try catch block below is left specifically for
10111 // optimization and perf reasons. a tryCatcher is not necessary here.
10112 FilterSubscriber.prototype._next = function (value) {
10115 result = this.predicate.call(this.thisArg, value, this.count++);
10118 this.destination.error(err);
10122 this.destination.next(value);
10125 return FilterSubscriber;
10126 }(Subscriber_1.Subscriber));
10128 },{"../Subscriber":36}],121:[function(require,module,exports){
10130 var __extends = (this && this.__extends) || function (d, b) {
10131 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10132 function __() { this.constructor = d; }
10133 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10135 var Subscriber_1 = require('../Subscriber');
10136 var Subscription_1 = require('../Subscription');
10138 * Returns an Observable that mirrors the source Observable, but will call a specified function when
10139 * the source terminates on complete or error.
10140 * @param {function} callback Function to be called when source terminates.
10141 * @return {Observable} An Observable that mirrors the source, but will call the specified function on termination.
10143 * @owner Observable
10145 function _finally(callback) {
10146 return this.lift(new FinallyOperator(callback));
10148 exports._finally = _finally;
10149 var FinallyOperator = (function () {
10150 function FinallyOperator(callback) {
10151 this.callback = callback;
10153 FinallyOperator.prototype.call = function (subscriber, source) {
10154 return source.subscribe(new FinallySubscriber(subscriber, this.callback));
10156 return FinallyOperator;
10159 * We need this JSDoc comment for affecting ESDoc.
10161 * @extends {Ignored}
10163 var FinallySubscriber = (function (_super) {
10164 __extends(FinallySubscriber, _super);
10165 function FinallySubscriber(destination, callback) {
10166 _super.call(this, destination);
10167 this.add(new Subscription_1.Subscription(callback));
10169 return FinallySubscriber;
10170 }(Subscriber_1.Subscriber));
10172 },{"../Subscriber":36,"../Subscription":37}],122:[function(require,module,exports){
10174 var __extends = (this && this.__extends) || function (d, b) {
10175 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10176 function __() { this.constructor = d; }
10177 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10179 var Subscriber_1 = require('../Subscriber');
10180 var EmptyError_1 = require('../util/EmptyError');
10182 * Emits only the first value (or the first value that meets some condition)
10183 * emitted by the source Observable.
10185 * <span class="informal">Emits only the first value. Or emits only the first
10186 * value that passes some test.</span>
10188 * <img src="./img/first.png" width="100%">
10190 * If called with no arguments, `first` emits the first value of the source
10191 * Observable, then completes. If called with a `predicate` function, `first`
10192 * emits the first value of the source that matches the specified condition. It
10193 * may also take a `resultSelector` function to produce the output value from
10194 * the input value, and a `defaultValue` to emit in case the source completes
10195 * before it is able to emit a valid value. Throws an error if `defaultValue`
10196 * was not provided and a matching element is not found.
10198 * @example <caption>Emit only the first click that happens on the DOM</caption>
10199 * var clicks = Rx.Observable.fromEvent(document, 'click');
10200 * var result = clicks.first();
10201 * result.subscribe(x => console.log(x));
10203 * @example <caption>Emits the first click that happens on a DIV</caption>
10204 * var clicks = Rx.Observable.fromEvent(document, 'click');
10205 * var result = clicks.first(ev => ev.target.tagName === 'DIV');
10206 * result.subscribe(x => console.log(x));
10208 * @see {@link filter}
10209 * @see {@link find}
10210 * @see {@link take}
10212 * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
10213 * callback if the Observable completes before any `next` notification was sent.
10215 * @param {function(value: T, index: number, source: Observable<T>): boolean} [predicate]
10216 * An optional function called with each item to test for condition matching.
10217 * @param {function(value: T, index: number): R} [resultSelector] A function to
10218 * produce the value on the output Observable based on the values
10219 * and the indices of the source Observable. The arguments passed to this
10221 * - `value`: the value that was emitted on the source.
10222 * - `index`: the "index" of the value from the source.
10223 * @param {R} [defaultValue] The default value emitted in case no valid value
10224 * was found on the source.
10225 * @return {Observable<T|R>} An Observable of the first item that matches the
10228 * @owner Observable
10230 function first(predicate, resultSelector, defaultValue) {
10231 return this.lift(new FirstOperator(predicate, resultSelector, defaultValue, this));
10233 exports.first = first;
10234 var FirstOperator = (function () {
10235 function FirstOperator(predicate, resultSelector, defaultValue, source) {
10236 this.predicate = predicate;
10237 this.resultSelector = resultSelector;
10238 this.defaultValue = defaultValue;
10239 this.source = source;
10241 FirstOperator.prototype.call = function (observer, source) {
10242 return source.subscribe(new FirstSubscriber(observer, this.predicate, this.resultSelector, this.defaultValue, this.source));
10244 return FirstOperator;
10247 * We need this JSDoc comment for affecting ESDoc.
10249 * @extends {Ignored}
10251 var FirstSubscriber = (function (_super) {
10252 __extends(FirstSubscriber, _super);
10253 function FirstSubscriber(destination, predicate, resultSelector, defaultValue, source) {
10254 _super.call(this, destination);
10255 this.predicate = predicate;
10256 this.resultSelector = resultSelector;
10257 this.defaultValue = defaultValue;
10258 this.source = source;
10260 this.hasCompleted = false;
10261 this._emitted = false;
10263 FirstSubscriber.prototype._next = function (value) {
10264 var index = this.index++;
10265 if (this.predicate) {
10266 this._tryPredicate(value, index);
10269 this._emit(value, index);
10272 FirstSubscriber.prototype._tryPredicate = function (value, index) {
10275 result = this.predicate(value, index, this.source);
10278 this.destination.error(err);
10282 this._emit(value, index);
10285 FirstSubscriber.prototype._emit = function (value, index) {
10286 if (this.resultSelector) {
10287 this._tryResultSelector(value, index);
10290 this._emitFinal(value);
10292 FirstSubscriber.prototype._tryResultSelector = function (value, index) {
10295 result = this.resultSelector(value, index);
10298 this.destination.error(err);
10301 this._emitFinal(result);
10303 FirstSubscriber.prototype._emitFinal = function (value) {
10304 var destination = this.destination;
10305 if (!this._emitted) {
10306 this._emitted = true;
10307 destination.next(value);
10308 destination.complete();
10309 this.hasCompleted = true;
10312 FirstSubscriber.prototype._complete = function () {
10313 var destination = this.destination;
10314 if (!this.hasCompleted && typeof this.defaultValue !== 'undefined') {
10315 destination.next(this.defaultValue);
10316 destination.complete();
10318 else if (!this.hasCompleted) {
10319 destination.error(new EmptyError_1.EmptyError);
10322 return FirstSubscriber;
10323 }(Subscriber_1.Subscriber));
10325 },{"../Subscriber":36,"../util/EmptyError":159}],123:[function(require,module,exports){
10327 var __extends = (this && this.__extends) || function (d, b) {
10328 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10329 function __() { this.constructor = d; }
10330 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10332 var Subscriber_1 = require('../Subscriber');
10333 var EmptyError_1 = require('../util/EmptyError');
10334 /* tslint:enable:max-line-length */
10336 * Returns an Observable that emits only the last item emitted by the source Observable.
10337 * It optionally takes a predicate function as a parameter, in which case, rather than emitting
10338 * the last item from the source Observable, the resulting Observable will emit the last item
10339 * from the source Observable that satisfies the predicate.
10341 * <img src="./img/last.png" width="100%">
10343 * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
10344 * callback if the Observable completes before any `next` notification was sent.
10345 * @param {function} predicate - The condition any source emitted item has to satisfy.
10346 * @return {Observable} An Observable that emits only the last item satisfying the given condition
10347 * from the source, or an NoSuchElementException if no such items are emitted.
10348 * @throws - Throws if no items that match the predicate are emitted by the source Observable.
10350 * @owner Observable
10352 function last(predicate, resultSelector, defaultValue) {
10353 return this.lift(new LastOperator(predicate, resultSelector, defaultValue, this));
10355 exports.last = last;
10356 var LastOperator = (function () {
10357 function LastOperator(predicate, resultSelector, defaultValue, source) {
10358 this.predicate = predicate;
10359 this.resultSelector = resultSelector;
10360 this.defaultValue = defaultValue;
10361 this.source = source;
10363 LastOperator.prototype.call = function (observer, source) {
10364 return source.subscribe(new LastSubscriber(observer, this.predicate, this.resultSelector, this.defaultValue, this.source));
10366 return LastOperator;
10369 * We need this JSDoc comment for affecting ESDoc.
10371 * @extends {Ignored}
10373 var LastSubscriber = (function (_super) {
10374 __extends(LastSubscriber, _super);
10375 function LastSubscriber(destination, predicate, resultSelector, defaultValue, source) {
10376 _super.call(this, destination);
10377 this.predicate = predicate;
10378 this.resultSelector = resultSelector;
10379 this.defaultValue = defaultValue;
10380 this.source = source;
10381 this.hasValue = false;
10383 if (typeof defaultValue !== 'undefined') {
10384 this.lastValue = defaultValue;
10385 this.hasValue = true;
10388 LastSubscriber.prototype._next = function (value) {
10389 var index = this.index++;
10390 if (this.predicate) {
10391 this._tryPredicate(value, index);
10394 if (this.resultSelector) {
10395 this._tryResultSelector(value, index);
10398 this.lastValue = value;
10399 this.hasValue = true;
10402 LastSubscriber.prototype._tryPredicate = function (value, index) {
10405 result = this.predicate(value, index, this.source);
10408 this.destination.error(err);
10412 if (this.resultSelector) {
10413 this._tryResultSelector(value, index);
10416 this.lastValue = value;
10417 this.hasValue = true;
10420 LastSubscriber.prototype._tryResultSelector = function (value, index) {
10423 result = this.resultSelector(value, index);
10426 this.destination.error(err);
10429 this.lastValue = result;
10430 this.hasValue = true;
10432 LastSubscriber.prototype._complete = function () {
10433 var destination = this.destination;
10434 if (this.hasValue) {
10435 destination.next(this.lastValue);
10436 destination.complete();
10439 destination.error(new EmptyError_1.EmptyError);
10442 return LastSubscriber;
10443 }(Subscriber_1.Subscriber));
10445 },{"../Subscriber":36,"../util/EmptyError":159}],124:[function(require,module,exports){
10447 var __extends = (this && this.__extends) || function (d, b) {
10448 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10449 function __() { this.constructor = d; }
10450 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10452 var Subscriber_1 = require('../Subscriber');
10454 * Applies a given `project` function to each value emitted by the source
10455 * Observable, and emits the resulting values as an Observable.
10457 * <span class="informal">Like [Array.prototype.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map),
10458 * it passes each source value through a transformation function to get
10459 * corresponding output values.</span>
10461 * <img src="./img/map.png" width="100%">
10463 * Similar to the well known `Array.prototype.map` function, this operator
10464 * applies a projection to each value and emits that projection in the output
10467 * @example <caption>Map every click to the clientX position of that click</caption>
10468 * var clicks = Rx.Observable.fromEvent(document, 'click');
10469 * var positions = clicks.map(ev => ev.clientX);
10470 * positions.subscribe(x => console.log(x));
10472 * @see {@link mapTo}
10473 * @see {@link pluck}
10475 * @param {function(value: T, index: number): R} project The function to apply
10476 * to each `value` emitted by the source Observable. The `index` parameter is
10477 * the number `i` for the i-th emission that has happened since the
10478 * subscription, starting from the number `0`.
10479 * @param {any} [thisArg] An optional argument to define what `this` is in the
10480 * `project` function.
10481 * @return {Observable<R>} An Observable that emits the values from the source
10482 * Observable transformed by the given `project` function.
10484 * @owner Observable
10486 function map(project, thisArg) {
10487 if (typeof project !== 'function') {
10488 throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');
10490 return this.lift(new MapOperator(project, thisArg));
10493 var MapOperator = (function () {
10494 function MapOperator(project, thisArg) {
10495 this.project = project;
10496 this.thisArg = thisArg;
10498 MapOperator.prototype.call = function (subscriber, source) {
10499 return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg));
10501 return MapOperator;
10503 exports.MapOperator = MapOperator;
10505 * We need this JSDoc comment for affecting ESDoc.
10507 * @extends {Ignored}
10509 var MapSubscriber = (function (_super) {
10510 __extends(MapSubscriber, _super);
10511 function MapSubscriber(destination, project, thisArg) {
10512 _super.call(this, destination);
10513 this.project = project;
10515 this.thisArg = thisArg || this;
10517 // NOTE: This looks unoptimized, but it's actually purposefully NOT
10518 // using try/catch optimizations.
10519 MapSubscriber.prototype._next = function (value) {
10522 result = this.project.call(this.thisArg, value, this.count++);
10525 this.destination.error(err);
10528 this.destination.next(result);
10530 return MapSubscriber;
10531 }(Subscriber_1.Subscriber));
10533 },{"../Subscriber":36}],125:[function(require,module,exports){
10535 var Observable_1 = require('../Observable');
10536 var ArrayObservable_1 = require('../observable/ArrayObservable');
10537 var mergeAll_1 = require('./mergeAll');
10538 var isScheduler_1 = require('../util/isScheduler');
10539 /* tslint:enable:max-line-length */
10541 * Creates an output Observable which concurrently emits all values from every
10542 * given input Observable.
10544 * <span class="informal">Flattens multiple Observables together by blending
10545 * their values into one Observable.</span>
10547 * <img src="./img/merge.png" width="100%">
10549 * `merge` subscribes to each given input Observable (either the source or an
10550 * Observable given as argument), and simply forwards (without doing any
10551 * transformation) all the values from all the input Observables to the output
10552 * Observable. The output Observable only completes once all input Observables
10553 * have completed. Any error delivered by an input Observable will be immediately
10554 * emitted on the output Observable.
10556 * @example <caption>Merge together two Observables: 1s interval and clicks</caption>
10557 * var clicks = Rx.Observable.fromEvent(document, 'click');
10558 * var timer = Rx.Observable.interval(1000);
10559 * var clicksOrTimer = clicks.merge(timer);
10560 * clicksOrTimer.subscribe(x => console.log(x));
10562 * @example <caption>Merge together 3 Observables, but only 2 run concurrently</caption>
10563 * var timer1 = Rx.Observable.interval(1000).take(10);
10564 * var timer2 = Rx.Observable.interval(2000).take(6);
10565 * var timer3 = Rx.Observable.interval(500).take(10);
10566 * var concurrent = 2; // the argument
10567 * var merged = timer1.merge(timer2, timer3, concurrent);
10568 * merged.subscribe(x => console.log(x));
10570 * @see {@link mergeAll}
10571 * @see {@link mergeMap}
10572 * @see {@link mergeMapTo}
10573 * @see {@link mergeScan}
10575 * @param {ObservableInput} other An input Observable to merge with the source
10576 * Observable. More than one input Observables may be given as argument.
10577 * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
10578 * Observables being subscribed to concurrently.
10579 * @param {Scheduler} [scheduler=null] The IScheduler to use for managing
10580 * concurrency of input Observables.
10581 * @return {Observable} An Observable that emits items that are the result of
10582 * every input Observable.
10584 * @owner Observable
10587 var observables = [];
10588 for (var _i = 0; _i < arguments.length; _i++) {
10589 observables[_i - 0] = arguments[_i];
10591 return this.lift.call(mergeStatic.apply(void 0, [this].concat(observables)));
10593 exports.merge = merge;
10594 /* tslint:enable:max-line-length */
10596 * Creates an output Observable which concurrently emits all values from every
10597 * given input Observable.
10599 * <span class="informal">Flattens multiple Observables together by blending
10600 * their values into one Observable.</span>
10602 * <img src="./img/merge.png" width="100%">
10604 * `merge` subscribes to each given input Observable (as arguments), and simply
10605 * forwards (without doing any transformation) all the values from all the input
10606 * Observables to the output Observable. The output Observable only completes
10607 * once all input Observables have completed. Any error delivered by an input
10608 * Observable will be immediately emitted on the output Observable.
10610 * @example <caption>Merge together two Observables: 1s interval and clicks</caption>
10611 * var clicks = Rx.Observable.fromEvent(document, 'click');
10612 * var timer = Rx.Observable.interval(1000);
10613 * var clicksOrTimer = Rx.Observable.merge(clicks, timer);
10614 * clicksOrTimer.subscribe(x => console.log(x));
10616 * // Results in the following:
10617 * // timer will emit ascending values, one every second(1000ms) to console
10618 * // clicks logs MouseEvents to console everytime the "document" is clicked
10619 * // Since the two streams are merged you see these happening
10620 * // as they occur.
10622 * @example <caption>Merge together 3 Observables, but only 2 run concurrently</caption>
10623 * var timer1 = Rx.Observable.interval(1000).take(10);
10624 * var timer2 = Rx.Observable.interval(2000).take(6);
10625 * var timer3 = Rx.Observable.interval(500).take(10);
10626 * var concurrent = 2; // the argument
10627 * var merged = Rx.Observable.merge(timer1, timer2, timer3, concurrent);
10628 * merged.subscribe(x => console.log(x));
10630 * // Results in the following:
10631 * // - First timer1 and timer2 will run concurrently
10632 * // - timer1 will emit a value every 1000ms for 10 iterations
10633 * // - timer2 will emit a value every 2000ms for 6 iterations
10634 * // - after timer1 hits it's max iteration, timer2 will
10635 * // continue, and timer3 will start to run concurrently with timer2
10636 * // - when timer2 hits it's max iteration it terminates, and
10637 * // timer3 will continue to emit a value every 500ms until it is complete
10639 * @see {@link mergeAll}
10640 * @see {@link mergeMap}
10641 * @see {@link mergeMapTo}
10642 * @see {@link mergeScan}
10644 * @param {...ObservableInput} observables Input Observables to merge together.
10645 * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
10646 * Observables being subscribed to concurrently.
10647 * @param {Scheduler} [scheduler=null] The IScheduler to use for managing
10648 * concurrency of input Observables.
10649 * @return {Observable} an Observable that emits items that are the result of
10650 * every input Observable.
10653 * @owner Observable
10655 function mergeStatic() {
10656 var observables = [];
10657 for (var _i = 0; _i < arguments.length; _i++) {
10658 observables[_i - 0] = arguments[_i];
10660 var concurrent = Number.POSITIVE_INFINITY;
10661 var scheduler = null;
10662 var last = observables[observables.length - 1];
10663 if (isScheduler_1.isScheduler(last)) {
10664 scheduler = observables.pop();
10665 if (observables.length > 1 && typeof observables[observables.length - 1] === 'number') {
10666 concurrent = observables.pop();
10669 else if (typeof last === 'number') {
10670 concurrent = observables.pop();
10672 if (scheduler === null && observables.length === 1 && observables[0] instanceof Observable_1.Observable) {
10673 return observables[0];
10675 return new ArrayObservable_1.ArrayObservable(observables, scheduler).lift(new mergeAll_1.MergeAllOperator(concurrent));
10677 exports.mergeStatic = mergeStatic;
10679 },{"../Observable":29,"../observable/ArrayObservable":86,"../util/isScheduler":171,"./mergeAll":126}],126:[function(require,module,exports){
10681 var __extends = (this && this.__extends) || function (d, b) {
10682 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10683 function __() { this.constructor = d; }
10684 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10686 var OuterSubscriber_1 = require('../OuterSubscriber');
10687 var subscribeToResult_1 = require('../util/subscribeToResult');
10689 * Converts a higher-order Observable into a first-order Observable which
10690 * concurrently delivers all values that are emitted on the inner Observables.
10692 * <span class="informal">Flattens an Observable-of-Observables.</span>
10694 * <img src="./img/mergeAll.png" width="100%">
10696 * `mergeAll` subscribes to an Observable that emits Observables, also known as
10697 * a higher-order Observable. Each time it observes one of these emitted inner
10698 * Observables, it subscribes to that and delivers all the values from the
10699 * inner Observable on the output Observable. The output Observable only
10700 * completes once all inner Observables have completed. Any error delivered by
10701 * a inner Observable will be immediately emitted on the output Observable.
10703 * @example <caption>Spawn a new interval Observable for each click event, and blend their outputs as one Observable</caption>
10704 * var clicks = Rx.Observable.fromEvent(document, 'click');
10705 * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000));
10706 * var firstOrder = higherOrder.mergeAll();
10707 * firstOrder.subscribe(x => console.log(x));
10709 * @example <caption>Count from 0 to 9 every second for each click, but only allow 2 concurrent timers</caption>
10710 * var clicks = Rx.Observable.fromEvent(document, 'click');
10711 * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000).take(10));
10712 * var firstOrder = higherOrder.mergeAll(2);
10713 * firstOrder.subscribe(x => console.log(x));
10715 * @see {@link combineAll}
10716 * @see {@link concatAll}
10717 * @see {@link exhaust}
10718 * @see {@link merge}
10719 * @see {@link mergeMap}
10720 * @see {@link mergeMapTo}
10721 * @see {@link mergeScan}
10722 * @see {@link switch}
10723 * @see {@link zipAll}
10725 * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of inner
10726 * Observables being subscribed to concurrently.
10727 * @return {Observable} An Observable that emits values coming from all the
10728 * inner Observables emitted by the source Observable.
10730 * @owner Observable
10732 function mergeAll(concurrent) {
10733 if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
10734 return this.lift(new MergeAllOperator(concurrent));
10736 exports.mergeAll = mergeAll;
10737 var MergeAllOperator = (function () {
10738 function MergeAllOperator(concurrent) {
10739 this.concurrent = concurrent;
10741 MergeAllOperator.prototype.call = function (observer, source) {
10742 return source.subscribe(new MergeAllSubscriber(observer, this.concurrent));
10744 return MergeAllOperator;
10746 exports.MergeAllOperator = MergeAllOperator;
10748 * We need this JSDoc comment for affecting ESDoc.
10750 * @extends {Ignored}
10752 var MergeAllSubscriber = (function (_super) {
10753 __extends(MergeAllSubscriber, _super);
10754 function MergeAllSubscriber(destination, concurrent) {
10755 _super.call(this, destination);
10756 this.concurrent = concurrent;
10757 this.hasCompleted = false;
10761 MergeAllSubscriber.prototype._next = function (observable) {
10762 if (this.active < this.concurrent) {
10764 this.add(subscribeToResult_1.subscribeToResult(this, observable));
10767 this.buffer.push(observable);
10770 MergeAllSubscriber.prototype._complete = function () {
10771 this.hasCompleted = true;
10772 if (this.active === 0 && this.buffer.length === 0) {
10773 this.destination.complete();
10776 MergeAllSubscriber.prototype.notifyComplete = function (innerSub) {
10777 var buffer = this.buffer;
10778 this.remove(innerSub);
10780 if (buffer.length > 0) {
10781 this._next(buffer.shift());
10783 else if (this.active === 0 && this.hasCompleted) {
10784 this.destination.complete();
10787 return MergeAllSubscriber;
10788 }(OuterSubscriber_1.OuterSubscriber));
10789 exports.MergeAllSubscriber = MergeAllSubscriber;
10791 },{"../OuterSubscriber":31,"../util/subscribeToResult":173}],127:[function(require,module,exports){
10793 var __extends = (this && this.__extends) || function (d, b) {
10794 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10795 function __() { this.constructor = d; }
10796 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10798 var subscribeToResult_1 = require('../util/subscribeToResult');
10799 var OuterSubscriber_1 = require('../OuterSubscriber');
10800 /* tslint:enable:max-line-length */
10802 * Projects each source value to an Observable which is merged in the output
10805 * <span class="informal">Maps each value to an Observable, then flattens all of
10806 * these inner Observables using {@link mergeAll}.</span>
10808 * <img src="./img/mergeMap.png" width="100%">
10810 * Returns an Observable that emits items based on applying a function that you
10811 * supply to each item emitted by the source Observable, where that function
10812 * returns an Observable, and then merging those resulting Observables and
10813 * emitting the results of this merger.
10815 * @example <caption>Map and flatten each letter to an Observable ticking every 1 second</caption>
10816 * var letters = Rx.Observable.of('a', 'b', 'c');
10817 * var result = letters.mergeMap(x =>
10818 * Rx.Observable.interval(1000).map(i => x+i)
10820 * result.subscribe(x => console.log(x));
10822 * // Results in the following:
10829 * // continues to list a,b,c with respective ascending integers
10831 * @see {@link concatMap}
10832 * @see {@link exhaustMap}
10833 * @see {@link merge}
10834 * @see {@link mergeAll}
10835 * @see {@link mergeMapTo}
10836 * @see {@link mergeScan}
10837 * @see {@link switchMap}
10839 * @param {function(value: T, ?index: number): ObservableInput} project A function
10840 * that, when applied to an item emitted by the source Observable, returns an
10842 * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
10843 * A function to produce the value on the output Observable based on the values
10844 * and the indices of the source (outer) emission and the inner Observable
10845 * emission. The arguments passed to this function are:
10846 * - `outerValue`: the value that came from the source
10847 * - `innerValue`: the value that came from the projected Observable
10848 * - `outerIndex`: the "index" of the value that came from the source
10849 * - `innerIndex`: the "index" of the value from the projected Observable
10850 * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
10851 * Observables being subscribed to concurrently.
10852 * @return {Observable} An Observable that emits the result of applying the
10853 * projection function (and the optional `resultSelector`) to each item emitted
10854 * by the source Observable and merging the results of the Observables obtained
10855 * from this transformation.
10857 * @owner Observable
10859 function mergeMap(project, resultSelector, concurrent) {
10860 if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
10861 if (typeof resultSelector === 'number') {
10862 concurrent = resultSelector;
10863 resultSelector = null;
10865 return this.lift(new MergeMapOperator(project, resultSelector, concurrent));
10867 exports.mergeMap = mergeMap;
10868 var MergeMapOperator = (function () {
10869 function MergeMapOperator(project, resultSelector, concurrent) {
10870 if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
10871 this.project = project;
10872 this.resultSelector = resultSelector;
10873 this.concurrent = concurrent;
10875 MergeMapOperator.prototype.call = function (observer, source) {
10876 return source.subscribe(new MergeMapSubscriber(observer, this.project, this.resultSelector, this.concurrent));
10878 return MergeMapOperator;
10880 exports.MergeMapOperator = MergeMapOperator;
10882 * We need this JSDoc comment for affecting ESDoc.
10884 * @extends {Ignored}
10886 var MergeMapSubscriber = (function (_super) {
10887 __extends(MergeMapSubscriber, _super);
10888 function MergeMapSubscriber(destination, project, resultSelector, concurrent) {
10889 if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
10890 _super.call(this, destination);
10891 this.project = project;
10892 this.resultSelector = resultSelector;
10893 this.concurrent = concurrent;
10894 this.hasCompleted = false;
10899 MergeMapSubscriber.prototype._next = function (value) {
10900 if (this.active < this.concurrent) {
10901 this._tryNext(value);
10904 this.buffer.push(value);
10907 MergeMapSubscriber.prototype._tryNext = function (value) {
10909 var index = this.index++;
10911 result = this.project(value, index);
10914 this.destination.error(err);
10918 this._innerSub(result, value, index);
10920 MergeMapSubscriber.prototype._innerSub = function (ish, value, index) {
10921 this.add(subscribeToResult_1.subscribeToResult(this, ish, value, index));
10923 MergeMapSubscriber.prototype._complete = function () {
10924 this.hasCompleted = true;
10925 if (this.active === 0 && this.buffer.length === 0) {
10926 this.destination.complete();
10929 MergeMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
10930 if (this.resultSelector) {
10931 this._notifyResultSelector(outerValue, innerValue, outerIndex, innerIndex);
10934 this.destination.next(innerValue);
10937 MergeMapSubscriber.prototype._notifyResultSelector = function (outerValue, innerValue, outerIndex, innerIndex) {
10940 result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex);
10943 this.destination.error(err);
10946 this.destination.next(result);
10948 MergeMapSubscriber.prototype.notifyComplete = function (innerSub) {
10949 var buffer = this.buffer;
10950 this.remove(innerSub);
10952 if (buffer.length > 0) {
10953 this._next(buffer.shift());
10955 else if (this.active === 0 && this.hasCompleted) {
10956 this.destination.complete();
10959 return MergeMapSubscriber;
10960 }(OuterSubscriber_1.OuterSubscriber));
10961 exports.MergeMapSubscriber = MergeMapSubscriber;
10963 },{"../OuterSubscriber":31,"../util/subscribeToResult":173}],128:[function(require,module,exports){
10965 var ConnectableObservable_1 = require('../observable/ConnectableObservable');
10966 /* tslint:enable:max-line-length */
10968 * Returns an Observable that emits the results of invoking a specified selector on items
10969 * emitted by a ConnectableObservable that shares a single subscription to the underlying stream.
10971 * <img src="./img/multicast.png" width="100%">
10973 * @param {Function|Subject} subjectOrSubjectFactory - Factory function to create an intermediate subject through
10974 * which the source sequence's elements will be multicast to the selector function
10975 * or Subject to push source elements into.
10976 * @param {Function} [selector] - Optional selector function that can use the multicasted source stream
10977 * as many times as needed, without causing multiple subscriptions to the source stream.
10978 * Subscribers to the given source will receive all notifications of the source from the
10979 * time of the subscription forward.
10980 * @return {Observable} An Observable that emits the results of invoking the selector
10981 * on the items emitted by a `ConnectableObservable` that shares a single subscription to
10982 * the underlying stream.
10983 * @method multicast
10984 * @owner Observable
10986 function multicast(subjectOrSubjectFactory, selector) {
10987 var subjectFactory;
10988 if (typeof subjectOrSubjectFactory === 'function') {
10989 subjectFactory = subjectOrSubjectFactory;
10992 subjectFactory = function subjectFactory() {
10993 return subjectOrSubjectFactory;
10996 if (typeof selector === 'function') {
10997 return this.lift(new MulticastOperator(subjectFactory, selector));
10999 var connectable = Object.create(this, ConnectableObservable_1.connectableObservableDescriptor);
11000 connectable.source = this;
11001 connectable.subjectFactory = subjectFactory;
11002 return connectable;
11004 exports.multicast = multicast;
11005 var MulticastOperator = (function () {
11006 function MulticastOperator(subjectFactory, selector) {
11007 this.subjectFactory = subjectFactory;
11008 this.selector = selector;
11010 MulticastOperator.prototype.call = function (subscriber, source) {
11011 var selector = this.selector;
11012 var subject = this.subjectFactory();
11013 var subscription = selector(subject).subscribe(subscriber);
11014 subscription.add(source.subscribe(subject));
11015 return subscription;
11017 return MulticastOperator;
11019 exports.MulticastOperator = MulticastOperator;
11021 },{"../observable/ConnectableObservable":87}],129:[function(require,module,exports){
11023 var __extends = (this && this.__extends) || function (d, b) {
11024 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11025 function __() { this.constructor = d; }
11026 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11028 var Subscriber_1 = require('../Subscriber');
11029 var Notification_1 = require('../Notification');
11032 * Re-emits all notifications from source Observable with specified scheduler.
11034 * <span class="informal">Ensure a specific scheduler is used, from outside of an Observable.</span>
11036 * `observeOn` is an operator that accepts a scheduler as a first parameter, which will be used to reschedule
11037 * notifications emitted by the source Observable. It might be useful, if you do not have control over
11038 * internal scheduler of a given Observable, but want to control when its values are emitted nevertheless.
11040 * Returned Observable emits the same notifications (nexted values, complete and error events) as the source Observable,
11041 * but rescheduled with provided scheduler. Note that this doesn't mean that source Observables internal
11042 * scheduler will be replaced in any way. Original scheduler still will be used, but when the source Observable emits
11043 * notification, it will be immediately scheduled again - this time with scheduler passed to `observeOn`.
11044 * An anti-pattern would be calling `observeOn` on Observable that emits lots of values synchronously, to split
11045 * that emissions into asynchronous chunks. For this to happen, scheduler would have to be passed into the source
11046 * Observable directly (usually into the operator that creates it). `observeOn` simply delays notifications a
11047 * little bit more, to ensure that they are emitted at expected moments.
11049 * As a matter of fact, `observeOn` accepts second parameter, which specifies in milliseconds with what delay notifications
11050 * will be emitted. The main difference between {@link delay} operator and `observeOn` is that `observeOn`
11051 * will delay all notifications - including error notifications - while `delay` will pass through error
11052 * from source Observable immediately when it is emitted. In general it is highly recommended to use `delay` operator
11053 * for any kind of delaying of values in the stream, while using `observeOn` to specify which scheduler should be used
11054 * for notification emissions in general.
11056 * @example <caption>Ensure values in subscribe are called just before browser repaint.</caption>
11057 * const intervals = Rx.Observable.interval(10); // Intervals are scheduled
11058 * // with async scheduler by default...
11061 * .observeOn(Rx.Scheduler.animationFrame) // ...but we will observe on animationFrame
11062 * .subscribe(val => { // scheduler to ensure smooth animation.
11063 * someDiv.style.height = val + 'px';
11066 * @see {@link delay}
11068 * @param {IScheduler} scheduler Scheduler that will be used to reschedule notifications from source Observable.
11069 * @param {number} [delay] Number of milliseconds that states with what delay every notification should be rescheduled.
11070 * @return {Observable<T>} Observable that emits the same notifications as the source Observable,
11071 * but with provided scheduler.
11073 * @method observeOn
11074 * @owner Observable
11076 function observeOn(scheduler, delay) {
11077 if (delay === void 0) { delay = 0; }
11078 return this.lift(new ObserveOnOperator(scheduler, delay));
11080 exports.observeOn = observeOn;
11081 var ObserveOnOperator = (function () {
11082 function ObserveOnOperator(scheduler, delay) {
11083 if (delay === void 0) { delay = 0; }
11084 this.scheduler = scheduler;
11085 this.delay = delay;
11087 ObserveOnOperator.prototype.call = function (subscriber, source) {
11088 return source.subscribe(new ObserveOnSubscriber(subscriber, this.scheduler, this.delay));
11090 return ObserveOnOperator;
11092 exports.ObserveOnOperator = ObserveOnOperator;
11094 * We need this JSDoc comment for affecting ESDoc.
11096 * @extends {Ignored}
11098 var ObserveOnSubscriber = (function (_super) {
11099 __extends(ObserveOnSubscriber, _super);
11100 function ObserveOnSubscriber(destination, scheduler, delay) {
11101 if (delay === void 0) { delay = 0; }
11102 _super.call(this, destination);
11103 this.scheduler = scheduler;
11104 this.delay = delay;
11106 ObserveOnSubscriber.dispatch = function (arg) {
11107 var notification = arg.notification, destination = arg.destination;
11108 notification.observe(destination);
11109 this.unsubscribe();
11111 ObserveOnSubscriber.prototype.scheduleMessage = function (notification) {
11112 this.add(this.scheduler.schedule(ObserveOnSubscriber.dispatch, this.delay, new ObserveOnMessage(notification, this.destination)));
11114 ObserveOnSubscriber.prototype._next = function (value) {
11115 this.scheduleMessage(Notification_1.Notification.createNext(value));
11117 ObserveOnSubscriber.prototype._error = function (err) {
11118 this.scheduleMessage(Notification_1.Notification.createError(err));
11120 ObserveOnSubscriber.prototype._complete = function () {
11121 this.scheduleMessage(Notification_1.Notification.createComplete());
11123 return ObserveOnSubscriber;
11124 }(Subscriber_1.Subscriber));
11125 exports.ObserveOnSubscriber = ObserveOnSubscriber;
11126 var ObserveOnMessage = (function () {
11127 function ObserveOnMessage(notification, destination) {
11128 this.notification = notification;
11129 this.destination = destination;
11131 return ObserveOnMessage;
11133 exports.ObserveOnMessage = ObserveOnMessage;
11135 },{"../Notification":28,"../Subscriber":36}],130:[function(require,module,exports){
11137 var __extends = (this && this.__extends) || function (d, b) {
11138 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11139 function __() { this.constructor = d; }
11140 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11142 var Subscriber_1 = require('../Subscriber');
11144 * Groups pairs of consecutive emissions together and emits them as an array of
11147 * <span class="informal">Puts the current value and previous value together as
11148 * an array, and emits that.</span>
11150 * <img src="./img/pairwise.png" width="100%">
11152 * The Nth emission from the source Observable will cause the output Observable
11153 * to emit an array [(N-1)th, Nth] of the previous and the current value, as a
11154 * pair. For this reason, `pairwise` emits on the second and subsequent
11155 * emissions from the source Observable, but not on the first emission, because
11156 * there is no previous value in that case.
11158 * @example <caption>On every click (starting from the second), emit the relative distance to the previous click</caption>
11159 * var clicks = Rx.Observable.fromEvent(document, 'click');
11160 * var pairs = clicks.pairwise();
11161 * var distance = pairs.map(pair => {
11162 * var x0 = pair[0].clientX;
11163 * var y0 = pair[0].clientY;
11164 * var x1 = pair[1].clientX;
11165 * var y1 = pair[1].clientY;
11166 * return Math.sqrt(Math.pow(x0 - x1, 2) + Math.pow(y0 - y1, 2));
11168 * distance.subscribe(x => console.log(x));
11170 * @see {@link buffer}
11171 * @see {@link bufferCount}
11173 * @return {Observable<Array<T>>} An Observable of pairs (as arrays) of
11174 * consecutive values from the source Observable.
11176 * @owner Observable
11178 function pairwise() {
11179 return this.lift(new PairwiseOperator());
11181 exports.pairwise = pairwise;
11182 var PairwiseOperator = (function () {
11183 function PairwiseOperator() {
11185 PairwiseOperator.prototype.call = function (subscriber, source) {
11186 return source.subscribe(new PairwiseSubscriber(subscriber));
11188 return PairwiseOperator;
11191 * We need this JSDoc comment for affecting ESDoc.
11193 * @extends {Ignored}
11195 var PairwiseSubscriber = (function (_super) {
11196 __extends(PairwiseSubscriber, _super);
11197 function PairwiseSubscriber(destination) {
11198 _super.call(this, destination);
11199 this.hasPrev = false;
11201 PairwiseSubscriber.prototype._next = function (value) {
11202 if (this.hasPrev) {
11203 this.destination.next([this.prev, value]);
11206 this.hasPrev = true;
11210 return PairwiseSubscriber;
11211 }(Subscriber_1.Subscriber));
11213 },{"../Subscriber":36}],131:[function(require,module,exports){
11215 var map_1 = require('./map');
11217 * Maps each source value (an object) to its specified nested property.
11219 * <span class="informal">Like {@link map}, but meant only for picking one of
11220 * the nested properties of every emitted object.</span>
11222 * <img src="./img/pluck.png" width="100%">
11224 * Given a list of strings describing a path to an object property, retrieves
11225 * the value of a specified nested property from all values in the source
11226 * Observable. If a property can't be resolved, it will return `undefined` for
11229 * @example <caption>Map every click to the tagName of the clicked target element</caption>
11230 * var clicks = Rx.Observable.fromEvent(document, 'click');
11231 * var tagNames = clicks.pluck('target', 'tagName');
11232 * tagNames.subscribe(x => console.log(x));
11236 * @param {...string} properties The nested properties to pluck from each source
11237 * value (an object).
11238 * @return {Observable} A new Observable of property values from the source values.
11240 * @owner Observable
11243 var properties = [];
11244 for (var _i = 0; _i < arguments.length; _i++) {
11245 properties[_i - 0] = arguments[_i];
11247 var length = properties.length;
11248 if (length === 0) {
11249 throw new Error('list of properties cannot be empty.');
11251 return map_1.map.call(this, plucker(properties, length));
11253 exports.pluck = pluck;
11254 function plucker(props, length) {
11255 var mapper = function (x) {
11256 var currentProp = x;
11257 for (var i = 0; i < length; i++) {
11258 var p = currentProp[props[i]];
11259 if (typeof p !== 'undefined') {
11266 return currentProp;
11271 },{"./map":124}],132:[function(require,module,exports){
11273 var Subject_1 = require('../Subject');
11274 var multicast_1 = require('./multicast');
11275 /* tslint:enable:max-line-length */
11277 * Returns a ConnectableObservable, which is a variety of Observable that waits until its connect method is called
11278 * before it begins emitting items to those Observers that have subscribed to it.
11280 * <img src="./img/publish.png" width="100%">
11282 * @param {Function} [selector] - Optional selector function which can use the multicasted source sequence as many times
11283 * as needed, without causing multiple subscriptions to the source sequence.
11284 * Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
11285 * @return A ConnectableObservable that upon connection causes the source Observable to emit items to its Observers.
11287 * @owner Observable
11289 function publish(selector) {
11290 return selector ? multicast_1.multicast.call(this, function () { return new Subject_1.Subject(); }, selector) :
11291 multicast_1.multicast.call(this, new Subject_1.Subject());
11293 exports.publish = publish;
11295 },{"../Subject":34,"./multicast":128}],133:[function(require,module,exports){
11297 var ReplaySubject_1 = require('../ReplaySubject');
11298 var multicast_1 = require('./multicast');
11300 * @param bufferSize
11301 * @param windowTime
11303 * @return {ConnectableObservable<T>}
11304 * @method publishReplay
11305 * @owner Observable
11307 function publishReplay(bufferSize, windowTime, scheduler) {
11308 if (bufferSize === void 0) { bufferSize = Number.POSITIVE_INFINITY; }
11309 if (windowTime === void 0) { windowTime = Number.POSITIVE_INFINITY; }
11310 return multicast_1.multicast.call(this, new ReplaySubject_1.ReplaySubject(bufferSize, windowTime, scheduler));
11312 exports.publishReplay = publishReplay;
11314 },{"../ReplaySubject":32,"./multicast":128}],134:[function(require,module,exports){
11316 var __extends = (this && this.__extends) || function (d, b) {
11317 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11318 function __() { this.constructor = d; }
11319 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11321 var Subscriber_1 = require('../Subscriber');
11322 /* tslint:enable:max-line-length */
11324 * Applies an accumulator function over the source Observable, and returns each
11325 * intermediate result, with an optional seed value.
11327 * <span class="informal">It's like {@link reduce}, but emits the current
11328 * accumulation whenever the source emits a value.</span>
11330 * <img src="./img/scan.png" width="100%">
11332 * Combines together all values emitted on the source, using an accumulator
11333 * function that knows how to join a new source value into the accumulation from
11334 * the past. Is similar to {@link reduce}, but emits the intermediate
11337 * Returns an Observable that applies a specified `accumulator` function to each
11338 * item emitted by the source Observable. If a `seed` value is specified, then
11339 * that value will be used as the initial value for the accumulator. If no seed
11340 * value is specified, the first item of the source is used as the seed.
11342 * @example <caption>Count the number of click events</caption>
11343 * var clicks = Rx.Observable.fromEvent(document, 'click');
11344 * var ones = clicks.mapTo(1);
11346 * var count = ones.scan((acc, one) => acc + one, seed);
11347 * count.subscribe(x => console.log(x));
11349 * @see {@link expand}
11350 * @see {@link mergeScan}
11351 * @see {@link reduce}
11353 * @param {function(acc: R, value: T, index: number): R} accumulator
11354 * The accumulator function called on each source value.
11355 * @param {T|R} [seed] The initial accumulation value.
11356 * @return {Observable<R>} An observable of the accumulated values.
11358 * @owner Observable
11360 function scan(accumulator, seed) {
11361 var hasSeed = false;
11362 // providing a seed of `undefined` *should* be valid and trigger
11363 // hasSeed! so don't use `seed !== undefined` checks!
11364 // For this reason, we have to check it here at the original call site
11365 // otherwise inside Operator/Subscriber we won't know if `undefined`
11366 // means they didn't provide anything or if they literally provided `undefined`
11367 if (arguments.length >= 2) {
11370 return this.lift(new ScanOperator(accumulator, seed, hasSeed));
11372 exports.scan = scan;
11373 var ScanOperator = (function () {
11374 function ScanOperator(accumulator, seed, hasSeed) {
11375 if (hasSeed === void 0) { hasSeed = false; }
11376 this.accumulator = accumulator;
11378 this.hasSeed = hasSeed;
11380 ScanOperator.prototype.call = function (subscriber, source) {
11381 return source.subscribe(new ScanSubscriber(subscriber, this.accumulator, this.seed, this.hasSeed));
11383 return ScanOperator;
11386 * We need this JSDoc comment for affecting ESDoc.
11388 * @extends {Ignored}
11390 var ScanSubscriber = (function (_super) {
11391 __extends(ScanSubscriber, _super);
11392 function ScanSubscriber(destination, accumulator, _seed, hasSeed) {
11393 _super.call(this, destination);
11394 this.accumulator = accumulator;
11395 this._seed = _seed;
11396 this.hasSeed = hasSeed;
11399 Object.defineProperty(ScanSubscriber.prototype, "seed", {
11403 set: function (value) {
11404 this.hasSeed = true;
11405 this._seed = value;
11410 ScanSubscriber.prototype._next = function (value) {
11411 if (!this.hasSeed) {
11413 this.destination.next(value);
11416 return this._tryNext(value);
11419 ScanSubscriber.prototype._tryNext = function (value) {
11420 var index = this.index++;
11423 result = this.accumulator(this.seed, value, index);
11426 this.destination.error(err);
11428 this.seed = result;
11429 this.destination.next(result);
11431 return ScanSubscriber;
11432 }(Subscriber_1.Subscriber));
11434 },{"../Subscriber":36}],135:[function(require,module,exports){
11436 var multicast_1 = require('./multicast');
11437 var Subject_1 = require('../Subject');
11438 function shareSubjectFactory() {
11439 return new Subject_1.Subject();
11442 * Returns a new Observable that multicasts (shares) the original Observable. As long as there is at least one
11443 * Subscriber this Observable will be subscribed and emitting data. When all subscribers have unsubscribed it will
11444 * unsubscribe from the source Observable. Because the Observable is multicasting it makes the stream `hot`.
11445 * This is an alias for .publish().refCount().
11447 * <img src="./img/share.png" width="100%">
11449 * @return {Observable<T>} An Observable that upon connection causes the source Observable to emit items to its Observers.
11451 * @owner Observable
11454 return multicast_1.multicast.call(this, shareSubjectFactory).refCount();
11456 exports.share = share;
11459 },{"../Subject":34,"./multicast":128}],136:[function(require,module,exports){
11461 var __extends = (this && this.__extends) || function (d, b) {
11462 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11463 function __() { this.constructor = d; }
11464 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11466 var Subscriber_1 = require('../Subscriber');
11468 * Returns an Observable that skips the first `count` items emitted by the source Observable.
11470 * <img src="./img/skip.png" width="100%">
11472 * @param {Number} count - The number of times, items emitted by source Observable should be skipped.
11473 * @return {Observable} An Observable that skips values emitted by the source Observable.
11476 * @owner Observable
11478 function skip(count) {
11479 return this.lift(new SkipOperator(count));
11481 exports.skip = skip;
11482 var SkipOperator = (function () {
11483 function SkipOperator(total) {
11484 this.total = total;
11486 SkipOperator.prototype.call = function (subscriber, source) {
11487 return source.subscribe(new SkipSubscriber(subscriber, this.total));
11489 return SkipOperator;
11492 * We need this JSDoc comment for affecting ESDoc.
11494 * @extends {Ignored}
11496 var SkipSubscriber = (function (_super) {
11497 __extends(SkipSubscriber, _super);
11498 function SkipSubscriber(destination, total) {
11499 _super.call(this, destination);
11500 this.total = total;
11503 SkipSubscriber.prototype._next = function (x) {
11504 if (++this.count > this.total) {
11505 this.destination.next(x);
11508 return SkipSubscriber;
11509 }(Subscriber_1.Subscriber));
11511 },{"../Subscriber":36}],137:[function(require,module,exports){
11513 var __extends = (this && this.__extends) || function (d, b) {
11514 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11515 function __() { this.constructor = d; }
11516 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11518 var OuterSubscriber_1 = require('../OuterSubscriber');
11519 var subscribeToResult_1 = require('../util/subscribeToResult');
11521 * Returns an Observable that skips items emitted by the source Observable until a second Observable emits an item.
11523 * <img src="./img/skipUntil.png" width="100%">
11525 * @param {Observable} notifier - The second Observable that has to emit an item before the source Observable's elements begin to
11526 * be mirrored by the resulting Observable.
11527 * @return {Observable<T>} An Observable that skips items from the source Observable until the second Observable emits
11528 * an item, then emits the remaining items.
11529 * @method skipUntil
11530 * @owner Observable
11532 function skipUntil(notifier) {
11533 return this.lift(new SkipUntilOperator(notifier));
11535 exports.skipUntil = skipUntil;
11536 var SkipUntilOperator = (function () {
11537 function SkipUntilOperator(notifier) {
11538 this.notifier = notifier;
11540 SkipUntilOperator.prototype.call = function (subscriber, source) {
11541 return source.subscribe(new SkipUntilSubscriber(subscriber, this.notifier));
11543 return SkipUntilOperator;
11546 * We need this JSDoc comment for affecting ESDoc.
11548 * @extends {Ignored}
11550 var SkipUntilSubscriber = (function (_super) {
11551 __extends(SkipUntilSubscriber, _super);
11552 function SkipUntilSubscriber(destination, notifier) {
11553 _super.call(this, destination);
11554 this.hasValue = false;
11555 this.isInnerStopped = false;
11556 this.add(subscribeToResult_1.subscribeToResult(this, notifier));
11558 SkipUntilSubscriber.prototype._next = function (value) {
11559 if (this.hasValue) {
11560 _super.prototype._next.call(this, value);
11563 SkipUntilSubscriber.prototype._complete = function () {
11564 if (this.isInnerStopped) {
11565 _super.prototype._complete.call(this);
11568 this.unsubscribe();
11571 SkipUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11572 this.hasValue = true;
11574 SkipUntilSubscriber.prototype.notifyComplete = function () {
11575 this.isInnerStopped = true;
11576 if (this.isStopped) {
11577 _super.prototype._complete.call(this);
11580 return SkipUntilSubscriber;
11581 }(OuterSubscriber_1.OuterSubscriber));
11583 },{"../OuterSubscriber":31,"../util/subscribeToResult":173}],138:[function(require,module,exports){
11585 var __extends = (this && this.__extends) || function (d, b) {
11586 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11587 function __() { this.constructor = d; }
11588 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11590 var Subscriber_1 = require('../Subscriber');
11592 * Returns an Observable that skips all items emitted by the source Observable as long as a specified condition holds
11593 * true, but emits all further source items as soon as the condition becomes false.
11595 * <img src="./img/skipWhile.png" width="100%">
11597 * @param {Function} predicate - A function to test each item emitted from the source Observable.
11598 * @return {Observable<T>} An Observable that begins emitting items emitted by the source Observable when the
11599 * specified predicate becomes false.
11600 * @method skipWhile
11601 * @owner Observable
11603 function skipWhile(predicate) {
11604 return this.lift(new SkipWhileOperator(predicate));
11606 exports.skipWhile = skipWhile;
11607 var SkipWhileOperator = (function () {
11608 function SkipWhileOperator(predicate) {
11609 this.predicate = predicate;
11611 SkipWhileOperator.prototype.call = function (subscriber, source) {
11612 return source.subscribe(new SkipWhileSubscriber(subscriber, this.predicate));
11614 return SkipWhileOperator;
11617 * We need this JSDoc comment for affecting ESDoc.
11619 * @extends {Ignored}
11621 var SkipWhileSubscriber = (function (_super) {
11622 __extends(SkipWhileSubscriber, _super);
11623 function SkipWhileSubscriber(destination, predicate) {
11624 _super.call(this, destination);
11625 this.predicate = predicate;
11626 this.skipping = true;
11629 SkipWhileSubscriber.prototype._next = function (value) {
11630 var destination = this.destination;
11631 if (this.skipping) {
11632 this.tryCallPredicate(value);
11634 if (!this.skipping) {
11635 destination.next(value);
11638 SkipWhileSubscriber.prototype.tryCallPredicate = function (value) {
11640 var result = this.predicate(value, this.index++);
11641 this.skipping = Boolean(result);
11644 this.destination.error(err);
11647 return SkipWhileSubscriber;
11648 }(Subscriber_1.Subscriber));
11650 },{"../Subscriber":36}],139:[function(require,module,exports){
11652 var ArrayObservable_1 = require('../observable/ArrayObservable');
11653 var ScalarObservable_1 = require('../observable/ScalarObservable');
11654 var EmptyObservable_1 = require('../observable/EmptyObservable');
11655 var concat_1 = require('./concat');
11656 var isScheduler_1 = require('../util/isScheduler');
11657 /* tslint:enable:max-line-length */
11659 * Returns an Observable that emits the items you specify as arguments before it begins to emit
11660 * items emitted by the source Observable.
11662 * <img src="./img/startWith.png" width="100%">
11664 * @param {...T} values - Items you want the modified Observable to emit first.
11665 * @param {Scheduler} [scheduler] - A {@link IScheduler} to use for scheduling
11666 * the emissions of the `next` notifications.
11667 * @return {Observable} An Observable that emits the items in the specified Iterable and then emits the items
11668 * emitted by the source Observable.
11669 * @method startWith
11670 * @owner Observable
11672 function startWith() {
11674 for (var _i = 0; _i < arguments.length; _i++) {
11675 array[_i - 0] = arguments[_i];
11677 var scheduler = array[array.length - 1];
11678 if (isScheduler_1.isScheduler(scheduler)) {
11684 var len = array.length;
11686 return concat_1.concatStatic(new ScalarObservable_1.ScalarObservable(array[0], scheduler), this);
11688 else if (len > 1) {
11689 return concat_1.concatStatic(new ArrayObservable_1.ArrayObservable(array, scheduler), this);
11692 return concat_1.concatStatic(new EmptyObservable_1.EmptyObservable(scheduler), this);
11695 exports.startWith = startWith;
11697 },{"../observable/ArrayObservable":86,"../observable/EmptyObservable":89,"../observable/ScalarObservable":95,"../util/isScheduler":171,"./concat":113}],140:[function(require,module,exports){
11699 var __extends = (this && this.__extends) || function (d, b) {
11700 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11701 function __() { this.constructor = d; }
11702 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11704 var OuterSubscriber_1 = require('../OuterSubscriber');
11705 var subscribeToResult_1 = require('../util/subscribeToResult');
11706 /* tslint:enable:max-line-length */
11708 * Projects each source value to an Observable which is merged in the output
11709 * Observable, emitting values only from the most recently projected Observable.
11711 * <span class="informal">Maps each value to an Observable, then flattens all of
11712 * these inner Observables using {@link switch}.</span>
11714 * <img src="./img/switchMap.png" width="100%">
11716 * Returns an Observable that emits items based on applying a function that you
11717 * supply to each item emitted by the source Observable, where that function
11718 * returns an (so-called "inner") Observable. Each time it observes one of these
11719 * inner Observables, the output Observable begins emitting the items emitted by
11720 * that inner Observable. When a new inner Observable is emitted, `switchMap`
11721 * stops emitting items from the earlier-emitted inner Observable and begins
11722 * emitting items from the new one. It continues to behave like this for
11723 * subsequent inner Observables.
11725 * @example <caption>Rerun an interval Observable on every click event</caption>
11726 * var clicks = Rx.Observable.fromEvent(document, 'click');
11727 * var result = clicks.switchMap((ev) => Rx.Observable.interval(1000));
11728 * result.subscribe(x => console.log(x));
11730 * @see {@link concatMap}
11731 * @see {@link exhaustMap}
11732 * @see {@link mergeMap}
11733 * @see {@link switch}
11734 * @see {@link switchMapTo}
11736 * @param {function(value: T, ?index: number): ObservableInput} project A function
11737 * that, when applied to an item emitted by the source Observable, returns an
11739 * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
11740 * A function to produce the value on the output Observable based on the values
11741 * and the indices of the source (outer) emission and the inner Observable
11742 * emission. The arguments passed to this function are:
11743 * - `outerValue`: the value that came from the source
11744 * - `innerValue`: the value that came from the projected Observable
11745 * - `outerIndex`: the "index" of the value that came from the source
11746 * - `innerIndex`: the "index" of the value from the projected Observable
11747 * @return {Observable} An Observable that emits the result of applying the
11748 * projection function (and the optional `resultSelector`) to each item emitted
11749 * by the source Observable and taking only the values from the most recently
11750 * projected inner Observable.
11751 * @method switchMap
11752 * @owner Observable
11754 function switchMap(project, resultSelector) {
11755 return this.lift(new SwitchMapOperator(project, resultSelector));
11757 exports.switchMap = switchMap;
11758 var SwitchMapOperator = (function () {
11759 function SwitchMapOperator(project, resultSelector) {
11760 this.project = project;
11761 this.resultSelector = resultSelector;
11763 SwitchMapOperator.prototype.call = function (subscriber, source) {
11764 return source.subscribe(new SwitchMapSubscriber(subscriber, this.project, this.resultSelector));
11766 return SwitchMapOperator;
11769 * We need this JSDoc comment for affecting ESDoc.
11771 * @extends {Ignored}
11773 var SwitchMapSubscriber = (function (_super) {
11774 __extends(SwitchMapSubscriber, _super);
11775 function SwitchMapSubscriber(destination, project, resultSelector) {
11776 _super.call(this, destination);
11777 this.project = project;
11778 this.resultSelector = resultSelector;
11781 SwitchMapSubscriber.prototype._next = function (value) {
11783 var index = this.index++;
11785 result = this.project(value, index);
11788 this.destination.error(error);
11791 this._innerSub(result, value, index);
11793 SwitchMapSubscriber.prototype._innerSub = function (result, value, index) {
11794 var innerSubscription = this.innerSubscription;
11795 if (innerSubscription) {
11796 innerSubscription.unsubscribe();
11798 this.add(this.innerSubscription = subscribeToResult_1.subscribeToResult(this, result, value, index));
11800 SwitchMapSubscriber.prototype._complete = function () {
11801 var innerSubscription = this.innerSubscription;
11802 if (!innerSubscription || innerSubscription.closed) {
11803 _super.prototype._complete.call(this);
11806 SwitchMapSubscriber.prototype._unsubscribe = function () {
11807 this.innerSubscription = null;
11809 SwitchMapSubscriber.prototype.notifyComplete = function (innerSub) {
11810 this.remove(innerSub);
11811 this.innerSubscription = null;
11812 if (this.isStopped) {
11813 _super.prototype._complete.call(this);
11816 SwitchMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11817 if (this.resultSelector) {
11818 this._tryNotifyNext(outerValue, innerValue, outerIndex, innerIndex);
11821 this.destination.next(innerValue);
11824 SwitchMapSubscriber.prototype._tryNotifyNext = function (outerValue, innerValue, outerIndex, innerIndex) {
11827 result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex);
11830 this.destination.error(err);
11833 this.destination.next(result);
11835 return SwitchMapSubscriber;
11836 }(OuterSubscriber_1.OuterSubscriber));
11838 },{"../OuterSubscriber":31,"../util/subscribeToResult":173}],141:[function(require,module,exports){
11840 var __extends = (this && this.__extends) || function (d, b) {
11841 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11842 function __() { this.constructor = d; }
11843 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11845 var Subscriber_1 = require('../Subscriber');
11846 var ArgumentOutOfRangeError_1 = require('../util/ArgumentOutOfRangeError');
11847 var EmptyObservable_1 = require('../observable/EmptyObservable');
11849 * Emits only the first `count` values emitted by the source Observable.
11851 * <span class="informal">Takes the first `count` values from the source, then
11852 * completes.</span>
11854 * <img src="./img/take.png" width="100%">
11856 * `take` returns an Observable that emits only the first `count` values emitted
11857 * by the source Observable. If the source emits fewer than `count` values then
11858 * all of its values are emitted. After that, it completes, regardless if the
11859 * source completes.
11861 * @example <caption>Take the first 5 seconds of an infinite 1-second interval Observable</caption>
11862 * var interval = Rx.Observable.interval(1000);
11863 * var five = interval.take(5);
11864 * five.subscribe(x => console.log(x));
11866 * @see {@link takeLast}
11867 * @see {@link takeUntil}
11868 * @see {@link takeWhile}
11869 * @see {@link skip}
11871 * @throws {ArgumentOutOfRangeError} When using `take(i)`, it delivers an
11872 * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0`.
11874 * @param {number} count The maximum number of `next` values to emit.
11875 * @return {Observable<T>} An Observable that emits only the first `count`
11876 * values emitted by the source Observable, or all of the values from the source
11877 * if the source emits fewer than `count` values.
11879 * @owner Observable
11881 function take(count) {
11883 return new EmptyObservable_1.EmptyObservable();
11886 return this.lift(new TakeOperator(count));
11889 exports.take = take;
11890 var TakeOperator = (function () {
11891 function TakeOperator(total) {
11892 this.total = total;
11893 if (this.total < 0) {
11894 throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError;
11897 TakeOperator.prototype.call = function (subscriber, source) {
11898 return source.subscribe(new TakeSubscriber(subscriber, this.total));
11900 return TakeOperator;
11903 * We need this JSDoc comment for affecting ESDoc.
11905 * @extends {Ignored}
11907 var TakeSubscriber = (function (_super) {
11908 __extends(TakeSubscriber, _super);
11909 function TakeSubscriber(destination, total) {
11910 _super.call(this, destination);
11911 this.total = total;
11914 TakeSubscriber.prototype._next = function (value) {
11915 var total = this.total;
11916 var count = ++this.count;
11917 if (count <= total) {
11918 this.destination.next(value);
11919 if (count === total) {
11920 this.destination.complete();
11921 this.unsubscribe();
11925 return TakeSubscriber;
11926 }(Subscriber_1.Subscriber));
11928 },{"../Subscriber":36,"../observable/EmptyObservable":89,"../util/ArgumentOutOfRangeError":158}],142:[function(require,module,exports){
11930 var __extends = (this && this.__extends) || function (d, b) {
11931 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11932 function __() { this.constructor = d; }
11933 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11935 var OuterSubscriber_1 = require('../OuterSubscriber');
11936 var subscribeToResult_1 = require('../util/subscribeToResult');
11938 * Emits the values emitted by the source Observable until a `notifier`
11939 * Observable emits a value.
11941 * <span class="informal">Lets values pass until a second Observable,
11942 * `notifier`, emits something. Then, it completes.</span>
11944 * <img src="./img/takeUntil.png" width="100%">
11946 * `takeUntil` subscribes and begins mirroring the source Observable. It also
11947 * monitors a second Observable, `notifier` that you provide. If the `notifier`
11948 * emits a value or a complete notification, the output Observable stops
11949 * mirroring the source Observable and completes.
11951 * @example <caption>Tick every second until the first click happens</caption>
11952 * var interval = Rx.Observable.interval(1000);
11953 * var clicks = Rx.Observable.fromEvent(document, 'click');
11954 * var result = interval.takeUntil(clicks);
11955 * result.subscribe(x => console.log(x));
11957 * @see {@link take}
11958 * @see {@link takeLast}
11959 * @see {@link takeWhile}
11960 * @see {@link skip}
11962 * @param {Observable} notifier The Observable whose first emitted value will
11963 * cause the output Observable of `takeUntil` to stop emitting values from the
11964 * source Observable.
11965 * @return {Observable<T>} An Observable that emits the values from the source
11966 * Observable until such time as `notifier` emits its first value.
11967 * @method takeUntil
11968 * @owner Observable
11970 function takeUntil(notifier) {
11971 return this.lift(new TakeUntilOperator(notifier));
11973 exports.takeUntil = takeUntil;
11974 var TakeUntilOperator = (function () {
11975 function TakeUntilOperator(notifier) {
11976 this.notifier = notifier;
11978 TakeUntilOperator.prototype.call = function (subscriber, source) {
11979 return source.subscribe(new TakeUntilSubscriber(subscriber, this.notifier));
11981 return TakeUntilOperator;
11984 * We need this JSDoc comment for affecting ESDoc.
11986 * @extends {Ignored}
11988 var TakeUntilSubscriber = (function (_super) {
11989 __extends(TakeUntilSubscriber, _super);
11990 function TakeUntilSubscriber(destination, notifier) {
11991 _super.call(this, destination);
11992 this.notifier = notifier;
11993 this.add(subscribeToResult_1.subscribeToResult(this, notifier));
11995 TakeUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11998 TakeUntilSubscriber.prototype.notifyComplete = function () {
12001 return TakeUntilSubscriber;
12002 }(OuterSubscriber_1.OuterSubscriber));
12004 },{"../OuterSubscriber":31,"../util/subscribeToResult":173}],143:[function(require,module,exports){
12006 var __extends = (this && this.__extends) || function (d, b) {
12007 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12008 function __() { this.constructor = d; }
12009 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12011 var OuterSubscriber_1 = require('../OuterSubscriber');
12012 var subscribeToResult_1 = require('../util/subscribeToResult');
12013 exports.defaultThrottleConfig = {
12018 * Emits a value from the source Observable, then ignores subsequent source
12019 * values for a duration determined by another Observable, then repeats this
12022 * <span class="informal">It's like {@link throttleTime}, but the silencing
12023 * duration is determined by a second Observable.</span>
12025 * <img src="./img/throttle.png" width="100%">
12027 * `throttle` emits the source Observable values on the output Observable
12028 * when its internal timer is disabled, and ignores source values when the timer
12029 * is enabled. Initially, the timer is disabled. As soon as the first source
12030 * value arrives, it is forwarded to the output Observable, and then the timer
12031 * is enabled by calling the `durationSelector` function with the source value,
12032 * which returns the "duration" Observable. When the duration Observable emits a
12033 * value or completes, the timer is disabled, and this process repeats for the
12034 * next source value.
12036 * @example <caption>Emit clicks at a rate of at most one click per second</caption>
12037 * var clicks = Rx.Observable.fromEvent(document, 'click');
12038 * var result = clicks.throttle(ev => Rx.Observable.interval(1000));
12039 * result.subscribe(x => console.log(x));
12041 * @see {@link audit}
12042 * @see {@link debounce}
12043 * @see {@link delayWhen}
12044 * @see {@link sample}
12045 * @see {@link throttleTime}
12047 * @param {function(value: T): SubscribableOrPromise} durationSelector A function
12048 * that receives a value from the source Observable, for computing the silencing
12049 * duration for each source value, returned as an Observable or a Promise.
12050 * @param {Object} config a configuration object to define `leading` and `trailing` behavior. Defaults
12051 * to `{ leading: true, trailing: false }`.
12052 * @return {Observable<T>} An Observable that performs the throttle operation to
12053 * limit the rate of emissions from the source.
12055 * @owner Observable
12057 function throttle(durationSelector, config) {
12058 if (config === void 0) { config = exports.defaultThrottleConfig; }
12059 return this.lift(new ThrottleOperator(durationSelector, config.leading, config.trailing));
12061 exports.throttle = throttle;
12062 var ThrottleOperator = (function () {
12063 function ThrottleOperator(durationSelector, leading, trailing) {
12064 this.durationSelector = durationSelector;
12065 this.leading = leading;
12066 this.trailing = trailing;
12068 ThrottleOperator.prototype.call = function (subscriber, source) {
12069 return source.subscribe(new ThrottleSubscriber(subscriber, this.durationSelector, this.leading, this.trailing));
12071 return ThrottleOperator;
12074 * We need this JSDoc comment for affecting ESDoc
12076 * @extends {Ignored}
12078 var ThrottleSubscriber = (function (_super) {
12079 __extends(ThrottleSubscriber, _super);
12080 function ThrottleSubscriber(destination, durationSelector, _leading, _trailing) {
12081 _super.call(this, destination);
12082 this.destination = destination;
12083 this.durationSelector = durationSelector;
12084 this._leading = _leading;
12085 this._trailing = _trailing;
12086 this._hasTrailingValue = false;
12088 ThrottleSubscriber.prototype._next = function (value) {
12089 if (this.throttled) {
12090 if (this._trailing) {
12091 this._hasTrailingValue = true;
12092 this._trailingValue = value;
12096 var duration = this.tryDurationSelector(value);
12098 this.add(this.throttled = subscribeToResult_1.subscribeToResult(this, duration));
12100 if (this._leading) {
12101 this.destination.next(value);
12102 if (this._trailing) {
12103 this._hasTrailingValue = true;
12104 this._trailingValue = value;
12109 ThrottleSubscriber.prototype.tryDurationSelector = function (value) {
12111 return this.durationSelector(value);
12114 this.destination.error(err);
12118 ThrottleSubscriber.prototype._unsubscribe = function () {
12119 var _a = this, throttled = _a.throttled, _trailingValue = _a._trailingValue, _hasTrailingValue = _a._hasTrailingValue, _trailing = _a._trailing;
12120 this._trailingValue = null;
12121 this._hasTrailingValue = false;
12123 this.remove(throttled);
12124 this.throttled = null;
12125 throttled.unsubscribe();
12128 ThrottleSubscriber.prototype._sendTrailing = function () {
12129 var _a = this, destination = _a.destination, throttled = _a.throttled, _trailing = _a._trailing, _trailingValue = _a._trailingValue, _hasTrailingValue = _a._hasTrailingValue;
12130 if (throttled && _trailing && _hasTrailingValue) {
12131 destination.next(_trailingValue);
12132 this._trailingValue = null;
12133 this._hasTrailingValue = false;
12136 ThrottleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
12137 this._sendTrailing();
12138 this._unsubscribe();
12140 ThrottleSubscriber.prototype.notifyComplete = function () {
12141 this._sendTrailing();
12142 this._unsubscribe();
12144 return ThrottleSubscriber;
12145 }(OuterSubscriber_1.OuterSubscriber));
12147 },{"../OuterSubscriber":31,"../util/subscribeToResult":173}],144:[function(require,module,exports){
12149 var __extends = (this && this.__extends) || function (d, b) {
12150 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12151 function __() { this.constructor = d; }
12152 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12154 var Subscriber_1 = require('../Subscriber');
12155 var async_1 = require('../scheduler/async');
12156 var throttle_1 = require('./throttle');
12158 * Emits a value from the source Observable, then ignores subsequent source
12159 * values for `duration` milliseconds, then repeats this process.
12161 * <span class="informal">Lets a value pass, then ignores source values for the
12162 * next `duration` milliseconds.</span>
12164 * <img src="./img/throttleTime.png" width="100%">
12166 * `throttleTime` emits the source Observable values on the output Observable
12167 * when its internal timer is disabled, and ignores source values when the timer
12168 * is enabled. Initially, the timer is disabled. As soon as the first source
12169 * value arrives, it is forwarded to the output Observable, and then the timer
12170 * is enabled. After `duration` milliseconds (or the time unit determined
12171 * internally by the optional `scheduler`) has passed, the timer is disabled,
12172 * and this process repeats for the next source value. Optionally takes a
12173 * {@link IScheduler} for managing timers.
12175 * @example <caption>Emit clicks at a rate of at most one click per second</caption>
12176 * var clicks = Rx.Observable.fromEvent(document, 'click');
12177 * var result = clicks.throttleTime(1000);
12178 * result.subscribe(x => console.log(x));
12180 * @see {@link auditTime}
12181 * @see {@link debounceTime}
12182 * @see {@link delay}
12183 * @see {@link sampleTime}
12184 * @see {@link throttle}
12186 * @param {number} duration Time to wait before emitting another value after
12187 * emitting the last value, measured in milliseconds or the time unit determined
12188 * internally by the optional `scheduler`.
12189 * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
12190 * managing the timers that handle the throttling.
12191 * @return {Observable<T>} An Observable that performs the throttle operation to
12192 * limit the rate of emissions from the source.
12193 * @method throttleTime
12194 * @owner Observable
12196 function throttleTime(duration, scheduler, config) {
12197 if (scheduler === void 0) { scheduler = async_1.async; }
12198 if (config === void 0) { config = throttle_1.defaultThrottleConfig; }
12199 return this.lift(new ThrottleTimeOperator(duration, scheduler, config.leading, config.trailing));
12201 exports.throttleTime = throttleTime;
12202 var ThrottleTimeOperator = (function () {
12203 function ThrottleTimeOperator(duration, scheduler, leading, trailing) {
12204 this.duration = duration;
12205 this.scheduler = scheduler;
12206 this.leading = leading;
12207 this.trailing = trailing;
12209 ThrottleTimeOperator.prototype.call = function (subscriber, source) {
12210 return source.subscribe(new ThrottleTimeSubscriber(subscriber, this.duration, this.scheduler, this.leading, this.trailing));
12212 return ThrottleTimeOperator;
12215 * We need this JSDoc comment for affecting ESDoc.
12217 * @extends {Ignored}
12219 var ThrottleTimeSubscriber = (function (_super) {
12220 __extends(ThrottleTimeSubscriber, _super);
12221 function ThrottleTimeSubscriber(destination, duration, scheduler, leading, trailing) {
12222 _super.call(this, destination);
12223 this.duration = duration;
12224 this.scheduler = scheduler;
12225 this.leading = leading;
12226 this.trailing = trailing;
12227 this._hasTrailingValue = false;
12228 this._trailingValue = null;
12230 ThrottleTimeSubscriber.prototype._next = function (value) {
12231 if (this.throttled) {
12232 if (this.trailing) {
12233 this._trailingValue = value;
12234 this._hasTrailingValue = true;
12238 this.add(this.throttled = this.scheduler.schedule(dispatchNext, this.duration, { subscriber: this }));
12239 if (this.leading) {
12240 this.destination.next(value);
12244 ThrottleTimeSubscriber.prototype.clearThrottle = function () {
12245 var throttled = this.throttled;
12247 if (this.trailing && this._hasTrailingValue) {
12248 this.destination.next(this._trailingValue);
12249 this._trailingValue = null;
12250 this._hasTrailingValue = false;
12252 throttled.unsubscribe();
12253 this.remove(throttled);
12254 this.throttled = null;
12257 return ThrottleTimeSubscriber;
12258 }(Subscriber_1.Subscriber));
12259 function dispatchNext(arg) {
12260 var subscriber = arg.subscriber;
12261 subscriber.clearThrottle();
12264 },{"../Subscriber":36,"../scheduler/async":152,"./throttle":143}],145:[function(require,module,exports){
12266 var __extends = (this && this.__extends) || function (d, b) {
12267 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12268 function __() { this.constructor = d; }
12269 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12271 var OuterSubscriber_1 = require('../OuterSubscriber');
12272 var subscribeToResult_1 = require('../util/subscribeToResult');
12273 /* tslint:enable:max-line-length */
12275 * Combines the source Observable with other Observables to create an Observable
12276 * whose values are calculated from the latest values of each, only when the
12279 * <span class="informal">Whenever the source Observable emits a value, it
12280 * computes a formula using that value plus the latest values from other input
12281 * Observables, then emits the output of that formula.</span>
12283 * <img src="./img/withLatestFrom.png" width="100%">
12285 * `withLatestFrom` combines each value from the source Observable (the
12286 * instance) with the latest values from the other input Observables only when
12287 * the source emits a value, optionally using a `project` function to determine
12288 * the value to be emitted on the output Observable. All input Observables must
12289 * emit at least one value before the output Observable will emit a value.
12291 * @example <caption>On every click event, emit an array with the latest timer event plus the click event</caption>
12292 * var clicks = Rx.Observable.fromEvent(document, 'click');
12293 * var timer = Rx.Observable.interval(1000);
12294 * var result = clicks.withLatestFrom(timer);
12295 * result.subscribe(x => console.log(x));
12297 * @see {@link combineLatest}
12299 * @param {ObservableInput} other An input Observable to combine with the source
12300 * Observable. More than one input Observables may be given as argument.
12301 * @param {Function} [project] Projection function for combining values
12302 * together. Receives all values in order of the Observables passed, where the
12303 * first parameter is a value from the source Observable. (e.g.
12304 * `a.withLatestFrom(b, c, (a1, b1, c1) => a1 + b1 + c1)`). If this is not
12305 * passed, arrays will be emitted on the output Observable.
12306 * @return {Observable} An Observable of projected values from the most recent
12307 * values from each input Observable, or an array of the most recent values from
12308 * each input Observable.
12309 * @method withLatestFrom
12310 * @owner Observable
12312 function withLatestFrom() {
12314 for (var _i = 0; _i < arguments.length; _i++) {
12315 args[_i - 0] = arguments[_i];
12318 if (typeof args[args.length - 1] === 'function') {
12319 project = args.pop();
12321 var observables = args;
12322 return this.lift(new WithLatestFromOperator(observables, project));
12324 exports.withLatestFrom = withLatestFrom;
12325 var WithLatestFromOperator = (function () {
12326 function WithLatestFromOperator(observables, project) {
12327 this.observables = observables;
12328 this.project = project;
12330 WithLatestFromOperator.prototype.call = function (subscriber, source) {
12331 return source.subscribe(new WithLatestFromSubscriber(subscriber, this.observables, this.project));
12333 return WithLatestFromOperator;
12336 * We need this JSDoc comment for affecting ESDoc.
12338 * @extends {Ignored}
12340 var WithLatestFromSubscriber = (function (_super) {
12341 __extends(WithLatestFromSubscriber, _super);
12342 function WithLatestFromSubscriber(destination, observables, project) {
12343 _super.call(this, destination);
12344 this.observables = observables;
12345 this.project = project;
12346 this.toRespond = [];
12347 var len = observables.length;
12348 this.values = new Array(len);
12349 for (var i = 0; i < len; i++) {
12350 this.toRespond.push(i);
12352 for (var i = 0; i < len; i++) {
12353 var observable = observables[i];
12354 this.add(subscribeToResult_1.subscribeToResult(this, observable, observable, i));
12357 WithLatestFromSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
12358 this.values[outerIndex] = innerValue;
12359 var toRespond = this.toRespond;
12360 if (toRespond.length > 0) {
12361 var found = toRespond.indexOf(outerIndex);
12362 if (found !== -1) {
12363 toRespond.splice(found, 1);
12367 WithLatestFromSubscriber.prototype.notifyComplete = function () {
12370 WithLatestFromSubscriber.prototype._next = function (value) {
12371 if (this.toRespond.length === 0) {
12372 var args = [value].concat(this.values);
12373 if (this.project) {
12374 this._tryProject(args);
12377 this.destination.next(args);
12381 WithLatestFromSubscriber.prototype._tryProject = function (args) {
12384 result = this.project.apply(this, args);
12387 this.destination.error(err);
12390 this.destination.next(result);
12392 return WithLatestFromSubscriber;
12393 }(OuterSubscriber_1.OuterSubscriber));
12395 },{"../OuterSubscriber":31,"../util/subscribeToResult":173}],146:[function(require,module,exports){
12397 var __extends = (this && this.__extends) || function (d, b) {
12398 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12399 function __() { this.constructor = d; }
12400 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12402 var ArrayObservable_1 = require('../observable/ArrayObservable');
12403 var isArray_1 = require('../util/isArray');
12404 var Subscriber_1 = require('../Subscriber');
12405 var OuterSubscriber_1 = require('../OuterSubscriber');
12406 var subscribeToResult_1 = require('../util/subscribeToResult');
12407 var iterator_1 = require('../symbol/iterator');
12408 /* tslint:enable:max-line-length */
12410 * @param observables
12411 * @return {Observable<R>}
12413 * @owner Observable
12415 function zipProto() {
12416 var observables = [];
12417 for (var _i = 0; _i < arguments.length; _i++) {
12418 observables[_i - 0] = arguments[_i];
12420 return this.lift.call(zipStatic.apply(void 0, [this].concat(observables)));
12422 exports.zipProto = zipProto;
12423 /* tslint:enable:max-line-length */
12425 * Combines multiple Observables to create an Observable whose values are calculated from the values, in order, of each
12426 * of its input Observables.
12428 * If the latest parameter is a function, this function is used to compute the created value from the input values.
12429 * Otherwise, an array of the input values is returned.
12431 * @example <caption>Combine age and name from different sources</caption>
12433 * let age$ = Observable.of<number>(27, 25, 29);
12434 * let name$ = Observable.of<string>('Foo', 'Bar', 'Beer');
12435 * let isDev$ = Observable.of<boolean>(true, true, false);
12441 * (age: number, name: string, isDev: boolean) => ({ age, name, isDev }))
12442 * .subscribe(x => console.log(x));
12445 * // { age: 27, name: 'Foo', isDev: true }
12446 * // { age: 25, name: 'Bar', isDev: true }
12447 * // { age: 29, name: 'Beer', isDev: false }
12449 * @param observables
12450 * @return {Observable<R>}
12453 * @owner Observable
12455 function zipStatic() {
12456 var observables = [];
12457 for (var _i = 0; _i < arguments.length; _i++) {
12458 observables[_i - 0] = arguments[_i];
12460 var project = observables[observables.length - 1];
12461 if (typeof project === 'function') {
12464 return new ArrayObservable_1.ArrayObservable(observables).lift(new ZipOperator(project));
12466 exports.zipStatic = zipStatic;
12467 var ZipOperator = (function () {
12468 function ZipOperator(project) {
12469 this.project = project;
12471 ZipOperator.prototype.call = function (subscriber, source) {
12472 return source.subscribe(new ZipSubscriber(subscriber, this.project));
12474 return ZipOperator;
12476 exports.ZipOperator = ZipOperator;
12478 * We need this JSDoc comment for affecting ESDoc.
12480 * @extends {Ignored}
12482 var ZipSubscriber = (function (_super) {
12483 __extends(ZipSubscriber, _super);
12484 function ZipSubscriber(destination, project, values) {
12485 if (values === void 0) { values = Object.create(null); }
12486 _super.call(this, destination);
12487 this.iterators = [];
12489 this.project = (typeof project === 'function') ? project : null;
12490 this.values = values;
12492 ZipSubscriber.prototype._next = function (value) {
12493 var iterators = this.iterators;
12494 if (isArray_1.isArray(value)) {
12495 iterators.push(new StaticArrayIterator(value));
12497 else if (typeof value[iterator_1.iterator] === 'function') {
12498 iterators.push(new StaticIterator(value[iterator_1.iterator]()));
12501 iterators.push(new ZipBufferIterator(this.destination, this, value));
12504 ZipSubscriber.prototype._complete = function () {
12505 var iterators = this.iterators;
12506 var len = iterators.length;
12508 this.destination.complete();
12512 for (var i = 0; i < len; i++) {
12513 var iterator = iterators[i];
12514 if (iterator.stillUnsubscribed) {
12515 this.add(iterator.subscribe(iterator, i));
12518 this.active--; // not an observable
12522 ZipSubscriber.prototype.notifyInactive = function () {
12524 if (this.active === 0) {
12525 this.destination.complete();
12528 ZipSubscriber.prototype.checkIterators = function () {
12529 var iterators = this.iterators;
12530 var len = iterators.length;
12531 var destination = this.destination;
12532 // abort if not all of them have values
12533 for (var i = 0; i < len; i++) {
12534 var iterator = iterators[i];
12535 if (typeof iterator.hasValue === 'function' && !iterator.hasValue()) {
12539 var shouldComplete = false;
12541 for (var i = 0; i < len; i++) {
12542 var iterator = iterators[i];
12543 var result = iterator.next();
12544 // check to see if it's completed now that you've gotten
12546 if (iterator.hasCompleted()) {
12547 shouldComplete = true;
12550 destination.complete();
12553 args.push(result.value);
12555 if (this.project) {
12556 this._tryProject(args);
12559 destination.next(args);
12561 if (shouldComplete) {
12562 destination.complete();
12565 ZipSubscriber.prototype._tryProject = function (args) {
12568 result = this.project.apply(this, args);
12571 this.destination.error(err);
12574 this.destination.next(result);
12576 return ZipSubscriber;
12577 }(Subscriber_1.Subscriber));
12578 exports.ZipSubscriber = ZipSubscriber;
12579 var StaticIterator = (function () {
12580 function StaticIterator(iterator) {
12581 this.iterator = iterator;
12582 this.nextResult = iterator.next();
12584 StaticIterator.prototype.hasValue = function () {
12587 StaticIterator.prototype.next = function () {
12588 var result = this.nextResult;
12589 this.nextResult = this.iterator.next();
12592 StaticIterator.prototype.hasCompleted = function () {
12593 var nextResult = this.nextResult;
12594 return nextResult && nextResult.done;
12596 return StaticIterator;
12598 var StaticArrayIterator = (function () {
12599 function StaticArrayIterator(array) {
12600 this.array = array;
12603 this.length = array.length;
12605 StaticArrayIterator.prototype[iterator_1.iterator] = function () {
12608 StaticArrayIterator.prototype.next = function (value) {
12609 var i = this.index++;
12610 var array = this.array;
12611 return i < this.length ? { value: array[i], done: false } : { value: null, done: true };
12613 StaticArrayIterator.prototype.hasValue = function () {
12614 return this.array.length > this.index;
12616 StaticArrayIterator.prototype.hasCompleted = function () {
12617 return this.array.length === this.index;
12619 return StaticArrayIterator;
12622 * We need this JSDoc comment for affecting ESDoc.
12624 * @extends {Ignored}
12626 var ZipBufferIterator = (function (_super) {
12627 __extends(ZipBufferIterator, _super);
12628 function ZipBufferIterator(destination, parent, observable) {
12629 _super.call(this, destination);
12630 this.parent = parent;
12631 this.observable = observable;
12632 this.stillUnsubscribed = true;
12634 this.isComplete = false;
12636 ZipBufferIterator.prototype[iterator_1.iterator] = function () {
12639 // NOTE: there is actually a name collision here with Subscriber.next and Iterator.next
12640 // this is legit because `next()` will never be called by a subscription in this case.
12641 ZipBufferIterator.prototype.next = function () {
12642 var buffer = this.buffer;
12643 if (buffer.length === 0 && this.isComplete) {
12644 return { value: null, done: true };
12647 return { value: buffer.shift(), done: false };
12650 ZipBufferIterator.prototype.hasValue = function () {
12651 return this.buffer.length > 0;
12653 ZipBufferIterator.prototype.hasCompleted = function () {
12654 return this.buffer.length === 0 && this.isComplete;
12656 ZipBufferIterator.prototype.notifyComplete = function () {
12657 if (this.buffer.length > 0) {
12658 this.isComplete = true;
12659 this.parent.notifyInactive();
12662 this.destination.complete();
12665 ZipBufferIterator.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
12666 this.buffer.push(innerValue);
12667 this.parent.checkIterators();
12669 ZipBufferIterator.prototype.subscribe = function (value, index) {
12670 return subscribeToResult_1.subscribeToResult(this, this.observable, this, index);
12672 return ZipBufferIterator;
12673 }(OuterSubscriber_1.OuterSubscriber));
12675 },{"../OuterSubscriber":31,"../Subscriber":36,"../observable/ArrayObservable":86,"../symbol/iterator":154,"../util/isArray":164,"../util/subscribeToResult":173}],147:[function(require,module,exports){
12677 var __extends = (this && this.__extends) || function (d, b) {
12678 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12679 function __() { this.constructor = d; }
12680 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12682 var Subscription_1 = require('../Subscription');
12684 * A unit of work to be executed in a {@link Scheduler}. An action is typically
12685 * created from within a Scheduler and an RxJS user does not need to concern
12686 * themselves about creating and manipulating an Action.
12689 * class Action<T> extends Subscription {
12690 * new (scheduler: Scheduler, work: (state?: T) => void);
12691 * schedule(state?: T, delay: number = 0): Subscription;
12697 var Action = (function (_super) {
12698 __extends(Action, _super);
12699 function Action(scheduler, work) {
12703 * Schedules this action on its parent Scheduler for execution. May be passed
12704 * some context object, `state`. May happen at some point in the future,
12705 * according to the `delay` parameter, if specified.
12706 * @param {T} [state] Some contextual data that the `work` function uses when
12707 * called by the Scheduler.
12708 * @param {number} [delay] Time to wait before executing the work, where the
12709 * time unit is implicit and defined by the Scheduler.
12712 Action.prototype.schedule = function (state, delay) {
12713 if (delay === void 0) { delay = 0; }
12717 }(Subscription_1.Subscription));
12718 exports.Action = Action;
12720 },{"../Subscription":37}],148:[function(require,module,exports){
12722 var __extends = (this && this.__extends) || function (d, b) {
12723 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12724 function __() { this.constructor = d; }
12725 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12727 var root_1 = require('../util/root');
12728 var Action_1 = require('./Action');
12730 * We need this JSDoc comment for affecting ESDoc.
12732 * @extends {Ignored}
12734 var AsyncAction = (function (_super) {
12735 __extends(AsyncAction, _super);
12736 function AsyncAction(scheduler, work) {
12737 _super.call(this, scheduler, work);
12738 this.scheduler = scheduler;
12740 this.pending = false;
12742 AsyncAction.prototype.schedule = function (state, delay) {
12743 if (delay === void 0) { delay = 0; }
12747 // Always replace the current state with the new state.
12748 this.state = state;
12749 // Set the pending flag indicating that this action has been scheduled, or
12750 // has recursively rescheduled itself.
12751 this.pending = true;
12753 var scheduler = this.scheduler;
12755 // Important implementation note:
12757 // Actions only execute once by default, unless rescheduled from within the
12758 // scheduled callback. This allows us to implement single and repeat
12759 // actions via the same code path, without adding API surface area, as well
12760 // as mimic traditional recursion but across asynchronous boundaries.
12762 // However, JS runtimes and timers distinguish between intervals achieved by
12763 // serial `setTimeout` calls vs. a single `setInterval` call. An interval of
12764 // serial `setTimeout` calls can be individually delayed, which delays
12765 // scheduling the next `setTimeout`, and so on. `setInterval` attempts to
12766 // guarantee the interval callback will be invoked more precisely to the
12767 // interval period, regardless of load.
12769 // Therefore, we use `setInterval` to schedule single and repeat actions.
12770 // If the action reschedules itself with the same delay, the interval is not
12771 // canceled. If the action doesn't reschedule, or reschedules with a
12772 // different delay, the interval will be canceled after scheduled callback
12776 this.id = this.recycleAsyncId(scheduler, id, delay);
12778 this.delay = delay;
12779 // If this action has already an async Id, don't request a new one.
12780 this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);
12783 AsyncAction.prototype.requestAsyncId = function (scheduler, id, delay) {
12784 if (delay === void 0) { delay = 0; }
12785 return root_1.root.setInterval(scheduler.flush.bind(scheduler, this), delay);
12787 AsyncAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
12788 if (delay === void 0) { delay = 0; }
12789 // If this action is rescheduled with the same delay time, don't clear the interval id.
12790 if (delay !== null && this.delay === delay && this.pending === false) {
12793 // Otherwise, if the action's delay time is different from the current delay,
12794 // or the action has been rescheduled before it's executed, clear the interval id
12795 return root_1.root.clearInterval(id) && undefined || undefined;
12798 * Immediately executes this action and the `work` it contains.
12801 AsyncAction.prototype.execute = function (state, delay) {
12803 return new Error('executing a cancelled action');
12805 this.pending = false;
12806 var error = this._execute(state, delay);
12810 else if (this.pending === false && this.id != null) {
12811 // Dequeue if the action didn't reschedule itself. Don't call
12812 // unsubscribe(), because the action could reschedule later.
12815 // scheduler.schedule(function doWork(counter) {
12816 // /* ... I'm a busy worker bee ... */
12817 // var originalAction = this;
12818 // /* wait 100ms before rescheduling the action */
12819 // setTimeout(function () {
12820 // originalAction.schedule(counter + 1);
12824 this.id = this.recycleAsyncId(this.scheduler, this.id, null);
12827 AsyncAction.prototype._execute = function (state, delay) {
12828 var errored = false;
12829 var errorValue = undefined;
12835 errorValue = !!e && e || new Error(e);
12838 this.unsubscribe();
12842 AsyncAction.prototype._unsubscribe = function () {
12844 var scheduler = this.scheduler;
12845 var actions = scheduler.actions;
12846 var index = actions.indexOf(this);
12849 this.pending = false;
12850 this.scheduler = null;
12851 if (index !== -1) {
12852 actions.splice(index, 1);
12855 this.id = this.recycleAsyncId(scheduler, id, null);
12859 return AsyncAction;
12860 }(Action_1.Action));
12861 exports.AsyncAction = AsyncAction;
12863 },{"../util/root":172,"./Action":147}],149:[function(require,module,exports){
12865 var __extends = (this && this.__extends) || function (d, b) {
12866 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12867 function __() { this.constructor = d; }
12868 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12870 var Scheduler_1 = require('../Scheduler');
12871 var AsyncScheduler = (function (_super) {
12872 __extends(AsyncScheduler, _super);
12873 function AsyncScheduler() {
12874 _super.apply(this, arguments);
12877 * A flag to indicate whether the Scheduler is currently executing a batch of
12881 this.active = false;
12883 * An internal ID used to track the latest asynchronous task such as those
12884 * coming from `setTimeout`, `setInterval`, `requestAnimationFrame`, and
12888 this.scheduled = undefined;
12890 AsyncScheduler.prototype.flush = function (action) {
12891 var actions = this.actions;
12893 actions.push(action);
12897 this.active = true;
12899 if (error = action.execute(action.state, action.delay)) {
12902 } while (action = actions.shift()); // exhaust the scheduler queue
12903 this.active = false;
12905 while (action = actions.shift()) {
12906 action.unsubscribe();
12911 return AsyncScheduler;
12912 }(Scheduler_1.Scheduler));
12913 exports.AsyncScheduler = AsyncScheduler;
12915 },{"../Scheduler":33}],150:[function(require,module,exports){
12917 var __extends = (this && this.__extends) || function (d, b) {
12918 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12919 function __() { this.constructor = d; }
12920 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12922 var AsyncAction_1 = require('./AsyncAction');
12924 * We need this JSDoc comment for affecting ESDoc.
12926 * @extends {Ignored}
12928 var QueueAction = (function (_super) {
12929 __extends(QueueAction, _super);
12930 function QueueAction(scheduler, work) {
12931 _super.call(this, scheduler, work);
12932 this.scheduler = scheduler;
12935 QueueAction.prototype.schedule = function (state, delay) {
12936 if (delay === void 0) { delay = 0; }
12938 return _super.prototype.schedule.call(this, state, delay);
12940 this.delay = delay;
12941 this.state = state;
12942 this.scheduler.flush(this);
12945 QueueAction.prototype.execute = function (state, delay) {
12946 return (delay > 0 || this.closed) ?
12947 _super.prototype.execute.call(this, state, delay) :
12948 this._execute(state, delay);
12950 QueueAction.prototype.requestAsyncId = function (scheduler, id, delay) {
12951 if (delay === void 0) { delay = 0; }
12952 // If delay exists and is greater than 0, or if the delay is null (the
12953 // action wasn't rescheduled) but was originally scheduled as an async
12954 // action, then recycle as an async action.
12955 if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
12956 return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
12958 // Otherwise flush the scheduler starting with this action.
12959 return scheduler.flush(this);
12961 return QueueAction;
12962 }(AsyncAction_1.AsyncAction));
12963 exports.QueueAction = QueueAction;
12965 },{"./AsyncAction":148}],151:[function(require,module,exports){
12967 var __extends = (this && this.__extends) || function (d, b) {
12968 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12969 function __() { this.constructor = d; }
12970 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12972 var AsyncScheduler_1 = require('./AsyncScheduler');
12973 var QueueScheduler = (function (_super) {
12974 __extends(QueueScheduler, _super);
12975 function QueueScheduler() {
12976 _super.apply(this, arguments);
12978 return QueueScheduler;
12979 }(AsyncScheduler_1.AsyncScheduler));
12980 exports.QueueScheduler = QueueScheduler;
12982 },{"./AsyncScheduler":149}],152:[function(require,module,exports){
12984 var AsyncAction_1 = require('./AsyncAction');
12985 var AsyncScheduler_1 = require('./AsyncScheduler');
12990 * <span class="informal">Schedule task as if you used setTimeout(task, duration)</span>
12992 * `async` scheduler schedules tasks asynchronously, by putting them on the JavaScript
12993 * event loop queue. It is best used to delay tasks in time or to schedule tasks repeating
12996 * If you just want to "defer" task, that is to perform it right after currently
12997 * executing synchronous code ends (commonly achieved by `setTimeout(deferredTask, 0)`),
12998 * better choice will be the {@link asap} scheduler.
13000 * @example <caption>Use async scheduler to delay task</caption>
13001 * const task = () => console.log('it works!');
13003 * Rx.Scheduler.async.schedule(task, 2000);
13005 * // After 2 seconds logs:
13009 * @example <caption>Use async scheduler to repeat task in intervals</caption>
13010 * function task(state) {
13011 * console.log(state);
13012 * this.schedule(state + 1, 1000); // `this` references currently executing Action,
13013 * // which we reschedule with new state and delay
13016 * Rx.Scheduler.async.schedule(task, 3000, 0);
13028 exports.async = new AsyncScheduler_1.AsyncScheduler(AsyncAction_1.AsyncAction);
13030 },{"./AsyncAction":148,"./AsyncScheduler":149}],153:[function(require,module,exports){
13032 var QueueAction_1 = require('./QueueAction');
13033 var QueueScheduler_1 = require('./QueueScheduler');
13038 * <span class="informal">Put every next task on a queue, instead of executing it immediately</span>
13040 * `queue` scheduler, when used with delay, behaves the same as {@link async} scheduler.
13042 * When used without delay, it schedules given task synchronously - executes it right when
13043 * it is scheduled. However when called recursively, that is when inside the scheduled task,
13044 * another task is scheduled with queue scheduler, instead of executing immediately as well,
13045 * that task will be put on a queue and wait for current one to finish.
13047 * This means that when you execute task with `queue` scheduler, you are sure it will end
13048 * before any other task scheduled with that scheduler will start.
13050 * @examples <caption>Schedule recursively first, then do something</caption>
13052 * Rx.Scheduler.queue.schedule(() => {
13053 * Rx.Scheduler.queue.schedule(() => console.log('second')); // will not happen now, but will be put on a queue
13055 * console.log('first');
13063 * @example <caption>Reschedule itself recursively</caption>
13065 * Rx.Scheduler.queue.schedule(function(state) {
13066 * if (state !== 0) {
13067 * console.log('before', state);
13068 * this.schedule(state - 1); // `this` references currently executing Action,
13069 * // which we reschedule with new state
13070 * console.log('after', state);
13074 * // In scheduler that runs recursively, you would expect:
13082 * // But with queue it logs:
13095 exports.queue = new QueueScheduler_1.QueueScheduler(QueueAction_1.QueueAction);
13097 },{"./QueueAction":150,"./QueueScheduler":151}],154:[function(require,module,exports){
13099 var root_1 = require('../util/root');
13100 function symbolIteratorPonyfill(root) {
13101 var Symbol = root.Symbol;
13102 if (typeof Symbol === 'function') {
13103 if (!Symbol.iterator) {
13104 Symbol.iterator = Symbol('iterator polyfill');
13106 return Symbol.iterator;
13109 // [for Mozilla Gecko 27-35:](https://mzl.la/2ewE1zC)
13110 var Set_1 = root.Set;
13111 if (Set_1 && typeof new Set_1()['@@iterator'] === 'function') {
13112 return '@@iterator';
13114 var Map_1 = root.Map;
13115 // required for compatability with es6-shim
13117 var keys = Object.getOwnPropertyNames(Map_1.prototype);
13118 for (var i = 0; i < keys.length; ++i) {
13120 // according to spec, Map.prototype[@@iterator] and Map.orototype.entries must be equal.
13121 if (key !== 'entries' && key !== 'size' && Map_1.prototype[key] === Map_1.prototype['entries']) {
13126 return '@@iterator';
13129 exports.symbolIteratorPonyfill = symbolIteratorPonyfill;
13130 exports.iterator = symbolIteratorPonyfill(root_1.root);
13132 * @deprecated use iterator instead
13134 exports.$$iterator = exports.iterator;
13136 },{"../util/root":172}],155:[function(require,module,exports){
13138 var root_1 = require('../util/root');
13139 function getSymbolObservable(context) {
13141 var Symbol = context.Symbol;
13142 if (typeof Symbol === 'function') {
13143 if (Symbol.observable) {
13144 $$observable = Symbol.observable;
13147 $$observable = Symbol('observable');
13148 Symbol.observable = $$observable;
13152 $$observable = '@@observable';
13154 return $$observable;
13156 exports.getSymbolObservable = getSymbolObservable;
13157 exports.observable = getSymbolObservable(root_1.root);
13159 * @deprecated use observable instead
13161 exports.$$observable = exports.observable;
13163 },{"../util/root":172}],156:[function(require,module,exports){
13165 var root_1 = require('../util/root');
13166 var Symbol = root_1.root.Symbol;
13167 exports.rxSubscriber = (typeof Symbol === 'function' && typeof Symbol.for === 'function') ?
13168 Symbol.for('rxSubscriber') : '@@rxSubscriber';
13170 * @deprecated use rxSubscriber instead
13172 exports.$$rxSubscriber = exports.rxSubscriber;
13174 },{"../util/root":172}],157:[function(require,module,exports){
13176 var root_1 = require('./root');
13177 var RequestAnimationFrameDefinition = (function () {
13178 function RequestAnimationFrameDefinition(root) {
13179 if (root.requestAnimationFrame) {
13180 this.cancelAnimationFrame = root.cancelAnimationFrame.bind(root);
13181 this.requestAnimationFrame = root.requestAnimationFrame.bind(root);
13183 else if (root.mozRequestAnimationFrame) {
13184 this.cancelAnimationFrame = root.mozCancelAnimationFrame.bind(root);
13185 this.requestAnimationFrame = root.mozRequestAnimationFrame.bind(root);
13187 else if (root.webkitRequestAnimationFrame) {
13188 this.cancelAnimationFrame = root.webkitCancelAnimationFrame.bind(root);
13189 this.requestAnimationFrame = root.webkitRequestAnimationFrame.bind(root);
13191 else if (root.msRequestAnimationFrame) {
13192 this.cancelAnimationFrame = root.msCancelAnimationFrame.bind(root);
13193 this.requestAnimationFrame = root.msRequestAnimationFrame.bind(root);
13195 else if (root.oRequestAnimationFrame) {
13196 this.cancelAnimationFrame = root.oCancelAnimationFrame.bind(root);
13197 this.requestAnimationFrame = root.oRequestAnimationFrame.bind(root);
13200 this.cancelAnimationFrame = root.clearTimeout.bind(root);
13201 this.requestAnimationFrame = function (cb) { return root.setTimeout(cb, 1000 / 60); };
13204 return RequestAnimationFrameDefinition;
13206 exports.RequestAnimationFrameDefinition = RequestAnimationFrameDefinition;
13207 exports.AnimationFrame = new RequestAnimationFrameDefinition(root_1.root);
13209 },{"./root":172}],158:[function(require,module,exports){
13211 var __extends = (this && this.__extends) || function (d, b) {
13212 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13213 function __() { this.constructor = d; }
13214 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13217 * An error thrown when an element was queried at a certain index of an
13218 * Observable, but no such index or position exists in that sequence.
13220 * @see {@link elementAt}
13221 * @see {@link take}
13222 * @see {@link takeLast}
13224 * @class ArgumentOutOfRangeError
13226 var ArgumentOutOfRangeError = (function (_super) {
13227 __extends(ArgumentOutOfRangeError, _super);
13228 function ArgumentOutOfRangeError() {
13229 var err = _super.call(this, 'argument out of range');
13230 this.name = err.name = 'ArgumentOutOfRangeError';
13231 this.stack = err.stack;
13232 this.message = err.message;
13234 return ArgumentOutOfRangeError;
13236 exports.ArgumentOutOfRangeError = ArgumentOutOfRangeError;
13238 },{}],159:[function(require,module,exports){
13240 var __extends = (this && this.__extends) || function (d, b) {
13241 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13242 function __() { this.constructor = d; }
13243 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13246 * An error thrown when an Observable or a sequence was queried but has no
13249 * @see {@link first}
13250 * @see {@link last}
13251 * @see {@link single}
13253 * @class EmptyError
13255 var EmptyError = (function (_super) {
13256 __extends(EmptyError, _super);
13257 function EmptyError() {
13258 var err = _super.call(this, 'no elements in sequence');
13259 this.name = err.name = 'EmptyError';
13260 this.stack = err.stack;
13261 this.message = err.message;
13265 exports.EmptyError = EmptyError;
13267 },{}],160:[function(require,module,exports){
13269 var __extends = (this && this.__extends) || function (d, b) {
13270 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13271 function __() { this.constructor = d; }
13272 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13275 * An error thrown when an action is invalid because the object has been
13278 * @see {@link Subject}
13279 * @see {@link BehaviorSubject}
13281 * @class ObjectUnsubscribedError
13283 var ObjectUnsubscribedError = (function (_super) {
13284 __extends(ObjectUnsubscribedError, _super);
13285 function ObjectUnsubscribedError() {
13286 var err = _super.call(this, 'object unsubscribed');
13287 this.name = err.name = 'ObjectUnsubscribedError';
13288 this.stack = err.stack;
13289 this.message = err.message;
13291 return ObjectUnsubscribedError;
13293 exports.ObjectUnsubscribedError = ObjectUnsubscribedError;
13295 },{}],161:[function(require,module,exports){
13297 var root_1 = require('./root');
13298 function minimalSetImpl() {
13299 // THIS IS NOT a full impl of Set, this is just the minimum
13300 // bits of functionality we need for this library.
13301 return (function () {
13302 function MinimalSet() {
13305 MinimalSet.prototype.add = function (value) {
13306 if (!this.has(value)) {
13307 this._values.push(value);
13310 MinimalSet.prototype.has = function (value) {
13311 return this._values.indexOf(value) !== -1;
13313 Object.defineProperty(MinimalSet.prototype, "size", {
13315 return this._values.length;
13320 MinimalSet.prototype.clear = function () {
13321 this._values.length = 0;
13326 exports.minimalSetImpl = minimalSetImpl;
13327 exports.Set = root_1.root.Set || minimalSetImpl();
13329 },{"./root":172}],162:[function(require,module,exports){
13331 var __extends = (this && this.__extends) || function (d, b) {
13332 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13333 function __() { this.constructor = d; }
13334 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13337 * An error thrown when one or more errors have occurred during the
13338 * `unsubscribe` of a {@link Subscription}.
13340 var UnsubscriptionError = (function (_super) {
13341 __extends(UnsubscriptionError, _super);
13342 function UnsubscriptionError(errors) {
13344 this.errors = errors;
13345 var err = Error.call(this, errors ?
13346 errors.length + " errors occurred during unsubscription:\n " + errors.map(function (err, i) { return ((i + 1) + ") " + err.toString()); }).join('\n ') : '');
13347 this.name = err.name = 'UnsubscriptionError';
13348 this.stack = err.stack;
13349 this.message = err.message;
13351 return UnsubscriptionError;
13353 exports.UnsubscriptionError = UnsubscriptionError;
13355 },{}],163:[function(require,module,exports){
13357 // typeof any so that it we don't have to cast when comparing a result to the error object
13358 exports.errorObject = { e: {} };
13360 },{}],164:[function(require,module,exports){
13362 exports.isArray = Array.isArray || (function (x) { return x && typeof x.length === 'number'; });
13364 },{}],165:[function(require,module,exports){
13366 exports.isArrayLike = (function (x) { return x && typeof x.length === 'number'; });
13368 },{}],166:[function(require,module,exports){
13370 function isDate(value) {
13371 return value instanceof Date && !isNaN(+value);
13373 exports.isDate = isDate;
13375 },{}],167:[function(require,module,exports){
13377 function isFunction(x) {
13378 return typeof x === 'function';
13380 exports.isFunction = isFunction;
13382 },{}],168:[function(require,module,exports){
13384 var isArray_1 = require('../util/isArray');
13385 function isNumeric(val) {
13386 // parseFloat NaNs numeric-cast false positives (null|true|false|"")
13387 // ...but misinterprets leading-number strings, particularly hex literals ("0x...")
13388 // subtraction forces infinities to NaN
13389 // adding 1 corrects loss of precision from parseFloat (#15100)
13390 return !isArray_1.isArray(val) && (val - parseFloat(val) + 1) >= 0;
13392 exports.isNumeric = isNumeric;
13395 },{"../util/isArray":164}],169:[function(require,module,exports){
13397 function isObject(x) {
13398 return x != null && typeof x === 'object';
13400 exports.isObject = isObject;
13402 },{}],170:[function(require,module,exports){
13404 function isPromise(value) {
13405 return value && typeof value.subscribe !== 'function' && typeof value.then === 'function';
13407 exports.isPromise = isPromise;
13409 },{}],171:[function(require,module,exports){
13411 function isScheduler(value) {
13412 return value && typeof value.schedule === 'function';
13414 exports.isScheduler = isScheduler;
13416 },{}],172:[function(require,module,exports){
13417 (function (global){
13419 // CommonJS / Node have global context exposed as "global" variable.
13420 // We don't want to include the whole node.d.ts this this compilation unit so we'll just fake
13421 // the global "global" var for now.
13422 var __window = typeof window !== 'undefined' && window;
13423 var __self = typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' &&
13424 self instanceof WorkerGlobalScope && self;
13425 var __global = typeof global !== 'undefined' && global;
13426 var _root = __window || __global || __self;
13427 exports.root = _root;
13428 // Workaround Closure Compiler restriction: The body of a goog.module cannot use throw.
13429 // This is needed when used with angular/tsickle which inserts a goog.module statement.
13433 throw new Error('RxJS could not find any global context (window, self, global)');
13437 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
13439 },{}],173:[function(require,module,exports){
13441 var root_1 = require('./root');
13442 var isArrayLike_1 = require('./isArrayLike');
13443 var isPromise_1 = require('./isPromise');
13444 var isObject_1 = require('./isObject');
13445 var Observable_1 = require('../Observable');
13446 var iterator_1 = require('../symbol/iterator');
13447 var InnerSubscriber_1 = require('../InnerSubscriber');
13448 var observable_1 = require('../symbol/observable');
13449 function subscribeToResult(outerSubscriber, result, outerValue, outerIndex) {
13450 var destination = new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex);
13451 if (destination.closed) {
13454 if (result instanceof Observable_1.Observable) {
13455 if (result._isScalar) {
13456 destination.next(result.value);
13457 destination.complete();
13461 return result.subscribe(destination);
13464 else if (isArrayLike_1.isArrayLike(result)) {
13465 for (var i = 0, len = result.length; i < len && !destination.closed; i++) {
13466 destination.next(result[i]);
13468 if (!destination.closed) {
13469 destination.complete();
13472 else if (isPromise_1.isPromise(result)) {
13473 result.then(function (value) {
13474 if (!destination.closed) {
13475 destination.next(value);
13476 destination.complete();
13478 }, function (err) { return destination.error(err); })
13479 .then(null, function (err) {
13480 // Escaping the Promise trap: globally throw unhandled errors
13481 root_1.root.setTimeout(function () { throw err; });
13483 return destination;
13485 else if (result && typeof result[iterator_1.iterator] === 'function') {
13486 var iterator = result[iterator_1.iterator]();
13488 var item = iterator.next();
13490 destination.complete();
13493 destination.next(item.value);
13494 if (destination.closed) {
13499 else if (result && typeof result[observable_1.observable] === 'function') {
13500 var obs = result[observable_1.observable]();
13501 if (typeof obs.subscribe !== 'function') {
13502 destination.error(new TypeError('Provided object does not correctly implement Symbol.observable'));
13505 return obs.subscribe(new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex));
13509 var value = isObject_1.isObject(result) ? 'an invalid object' : "'" + result + "'";
13510 var msg = ("You provided " + value + " where a stream was expected.")
13511 + ' You can provide an Observable, Promise, Array, or Iterable.';
13512 destination.error(new TypeError(msg));
13516 exports.subscribeToResult = subscribeToResult;
13518 },{"../InnerSubscriber":27,"../Observable":29,"../symbol/iterator":154,"../symbol/observable":155,"./isArrayLike":165,"./isObject":169,"./isPromise":170,"./root":172}],174:[function(require,module,exports){
13520 var Subscriber_1 = require('../Subscriber');
13521 var rxSubscriber_1 = require('../symbol/rxSubscriber');
13522 var Observer_1 = require('../Observer');
13523 function toSubscriber(nextOrObserver, error, complete) {
13524 if (nextOrObserver) {
13525 if (nextOrObserver instanceof Subscriber_1.Subscriber) {
13526 return nextOrObserver;
13528 if (nextOrObserver[rxSubscriber_1.rxSubscriber]) {
13529 return nextOrObserver[rxSubscriber_1.rxSubscriber]();
13532 if (!nextOrObserver && !error && !complete) {
13533 return new Subscriber_1.Subscriber(Observer_1.empty);
13535 return new Subscriber_1.Subscriber(nextOrObserver, error, complete);
13537 exports.toSubscriber = toSubscriber;
13539 },{"../Observer":30,"../Subscriber":36,"../symbol/rxSubscriber":156}],175:[function(require,module,exports){
13541 var errorObject_1 = require('./errorObject');
13542 var tryCatchTarget;
13543 function tryCatcher() {
13545 return tryCatchTarget.apply(this, arguments);
13548 errorObject_1.errorObject.e = e;
13549 return errorObject_1.errorObject;
13552 function tryCatch(fn) {
13553 tryCatchTarget = fn;
13556 exports.tryCatch = tryCatch;
13559 },{"./errorObject":163}],176:[function(require,module,exports){
13560 // threejs.org/license
13561 (function(l,xa){"object"===typeof exports&&"undefined"!==typeof module?xa(exports):"function"===typeof define&&define.amd?define(["exports"],xa):xa(l.THREE=l.THREE||{})})(this,function(l){function xa(){}function C(a,b){this.x=a||0;this.y=b||0}function ba(a,b,c,d,e,f,g,h,k,m){Object.defineProperty(this,"id",{value:hf++});this.uuid=Y.generateUUID();this.name="";this.image=void 0!==a?a:ba.DEFAULT_IMAGE;this.mipmaps=[];this.mapping=void 0!==b?b:ba.DEFAULT_MAPPING;this.wrapS=void 0!==c?c:1001;this.wrapT=
13562 void 0!==d?d:1001;this.magFilter=void 0!==e?e:1006;this.minFilter=void 0!==f?f:1008;this.anisotropy=void 0!==k?k:1;this.format=void 0!==g?g:1023;this.type=void 0!==h?h:1009;this.offset=new C(0,0);this.repeat=new C(1,1);this.generateMipmaps=!0;this.premultiplyAlpha=!1;this.flipY=!0;this.unpackAlignment=4;this.encoding=void 0!==m?m:3E3;this.version=0;this.onUpdate=null}function fa(a,b,c,d){this.x=a||0;this.y=b||0;this.z=c||0;this.w=void 0!==d?d:1}function Cb(a,b,c){this.uuid=Y.generateUUID();this.width=
13563 a;this.height=b;this.scissor=new fa(0,0,a,b);this.scissorTest=!1;this.viewport=new fa(0,0,a,b);c=c||{};void 0===c.minFilter&&(c.minFilter=1006);this.texture=new ba(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 Db(a,b,c){Cb.call(this,a,b,c);this.activeMipMapLevel=
13564 this.activeCubeFace=0}function oa(a,b,c,d){this._x=a||0;this._y=b||0;this._z=c||0;this._w=void 0!==d?d:1}function n(a,b,c){this.x=a||0;this.y=b||0;this.z=c||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 db(a,b,c,d,e,f,g,h,k,m,q,v){ba.call(this,null,f,g,h,k,m,d,e,q,v);this.image={data:a,width:b,height:c};this.magFilter=void 0!==k?k:1003;this.minFilter=void 0!==
13565 m?m:1003;this.flipY=this.generateMipmaps=!1;this.unpackAlignment=1}function Xa(a,b,c,d,e,f,g,h,k,m){a=void 0!==a?a:[];ba.call(this,a,void 0!==b?b:301,c,d,e,f,g,h,k,m);this.flipY=!1}function Eb(a,b,c){var d=a[0];if(0>=d||0<d)return a;var e=b*c,f=xe[e];void 0===f&&(f=new Float32Array(e),xe[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 ye(a,b){var c=ze[b];void 0===c&&(c=new Int32Array(b),ze[b]=c);for(var d=0;d!==b;++d)c[d]=a.allocTextureUnit();return c}
13566 function jf(a,b){a.uniform1f(this.addr,b)}function kf(a,b){a.uniform1i(this.addr,b)}function lf(a,b){void 0===b.x?a.uniform2fv(this.addr,b):a.uniform2f(this.addr,b.x,b.y)}function mf(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,b)}function nf(a,b){void 0===b.x?a.uniform4fv(this.addr,b):a.uniform4f(this.addr,b.x,b.y,b.z,b.w)}function of(a,b){a.uniformMatrix2fv(this.addr,!1,b.elements||b)}function pf(a,b){void 0===b.elements?
13567 a.uniformMatrix3fv(this.addr,!1,b):(Ae.set(b.elements),a.uniformMatrix3fv(this.addr,!1,Ae))}function qf(a,b){void 0===b.elements?a.uniformMatrix4fv(this.addr,!1,b):(Be.set(b.elements),a.uniformMatrix4fv(this.addr,!1,Be))}function rf(a,b,c){var d=c.allocTextureUnit();a.uniform1i(this.addr,d);c.setTexture2D(b||Ce,d)}function sf(a,b,c){var d=c.allocTextureUnit();a.uniform1i(this.addr,d);c.setTextureCube(b||De,d)}function Ee(a,b){a.uniform2iv(this.addr,b)}function Fe(a,b){a.uniform3iv(this.addr,b)}function Ge(a,
13568 b){a.uniform4iv(this.addr,b)}function tf(a){switch(a){case 5126:return jf;case 35664:return lf;case 35665:return mf;case 35666:return nf;case 35674:return of;case 35675:return pf;case 35676:return qf;case 35678:case 36198:return rf;case 35680:return sf;case 5124:case 35670:return kf;case 35667:case 35671:return Ee;case 35668:case 35672:return Fe;case 35669:case 35673:return Ge}}function uf(a,b){a.uniform1fv(this.addr,b)}function vf(a,b){a.uniform1iv(this.addr,b)}function wf(a,b){a.uniform2fv(this.addr,
13569 Eb(b,this.size,2))}function xf(a,b){a.uniform3fv(this.addr,Eb(b,this.size,3))}function yf(a,b){a.uniform4fv(this.addr,Eb(b,this.size,4))}function zf(a,b){a.uniformMatrix2fv(this.addr,!1,Eb(b,this.size,4))}function Af(a,b){a.uniformMatrix3fv(this.addr,!1,Eb(b,this.size,9))}function Bf(a,b){a.uniformMatrix4fv(this.addr,!1,Eb(b,this.size,16))}function Cf(a,b,c){var d=b.length,e=ye(c,d);a.uniform1iv(this.addr,e);for(a=0;a!==d;++a)c.setTexture2D(b[a]||Ce,e[a])}function Df(a,b,c){var d=b.length,e=ye(c,
13570 d);a.uniform1iv(this.addr,e);for(a=0;a!==d;++a)c.setTextureCube(b[a]||De,e[a])}function Ef(a){switch(a){case 5126:return uf;case 35664:return wf;case 35665:return xf;case 35666:return yf;case 35674:return zf;case 35675:return Af;case 35676:return Bf;case 35678:return Cf;case 35680:return Df;case 5124:case 35670:return vf;case 35667:case 35671:return Ee;case 35668:case 35672:return Fe;case 35669:case 35673:return Ge}}function Ff(a,b,c){this.id=a;this.addr=c;this.setValue=tf(b.type)}function Gf(a,b,
13571 c){this.id=a;this.addr=c;this.size=b.size;this.setValue=Ef(b.type)}function He(a){this.id=a;this.seq=[];this.map={}}function eb(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=h.length;for(Pd.lastIndex=0;;){var m=Pd.exec(h),q=Pd.lastIndex,v=m[1],p=m[3];"]"===m[2]&&(v|=0);if(void 0===p||"["===p&&q+2===k){h=g;e=void 0===p?new Ff(v,e,f):new Gf(v,e,f);h.seq.push(e);
13572 h.map[e.id]=e;break}else p=g.map[v],void 0===p&&(p=new He(v),v=g,g=p,v.seq.push(g),v.map[g.id]=g),g=p}}}function G(a,b,c){return void 0===b&&void 0===c?this.set(a):this.setRGB(a,b,c)}function fd(a,b){this.min=void 0!==a?a:new C(Infinity,Infinity);this.max=void 0!==b?b:new C(-Infinity,-Infinity)}function Hf(a,b){var c,d,e,f,g,h,k,m,q,v,p=a.context,r=a.state,l,t,y,x,u,H;this.render=function(w,I,W){if(0!==b.length){w=new n;var D=W.w/W.z,O=.5*W.z,aa=.5*W.w,F=16/W.w,ja=new C(F*D,F),T=new n(1,1,0),fb=new C(1,
13573 1),Ya=new fd;Ya.min.set(W.x,W.y);Ya.max.set(W.x+(W.z-16),W.y+(W.w-16));if(void 0===x){var F=new Float32Array([-1,-1,0,0,1,-1,1,0,1,1,1,1,-1,1,0,1]),ka=new Uint16Array([0,1,2,0,2,3]);l=p.createBuffer();t=p.createBuffer();p.bindBuffer(p.ARRAY_BUFFER,l);p.bufferData(p.ARRAY_BUFFER,F,p.STATIC_DRAW);p.bindBuffer(p.ELEMENT_ARRAY_BUFFER,t);p.bufferData(p.ELEMENT_ARRAY_BUFFER,ka,p.STATIC_DRAW);u=p.createTexture();H=p.createTexture();r.bindTexture(p.TEXTURE_2D,u);p.texImage2D(p.TEXTURE_2D,0,p.RGB,16,16,0,
13574 p.RGB,p.UNSIGNED_BYTE,null);p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_S,p.CLAMP_TO_EDGE);p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_T,p.CLAMP_TO_EDGE);p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MAG_FILTER,p.NEAREST);p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MIN_FILTER,p.NEAREST);r.bindTexture(p.TEXTURE_2D,H);p.texImage2D(p.TEXTURE_2D,0,p.RGBA,16,16,0,p.RGBA,p.UNSIGNED_BYTE,null);p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_S,p.CLAMP_TO_EDGE);p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_T,p.CLAMP_TO_EDGE);
13575 p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MAG_FILTER,p.NEAREST);p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MIN_FILTER,p.NEAREST);var F=y={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() {\nvUV = uv;\nvec2 pos = position;\nif ( renderType == 2 ) {\nvec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );\nvisibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );\nvVisibility = visibility.r / 9.0;\nvVisibility *= 1.0 - visibility.g / 9.0;\nvVisibility *= visibility.b / 9.0;\nvVisibility *= 1.0 - visibility.a / 9.0;\npos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;\npos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;\n}\ngl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );\n}",
13576 fragmentShader:"uniform lowp int renderType;\nuniform sampler2D map;\nuniform float opacity;\nuniform vec3 color;\nvarying vec2 vUV;\nvarying float vVisibility;\nvoid main() {\nif ( renderType == 0 ) {\ngl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );\n} else if ( renderType == 1 ) {\ngl_FragColor = texture2D( map, vUV );\n} else {\nvec4 texture = texture2D( map, vUV );\ntexture.a *= opacity * vVisibility;\ngl_FragColor = texture;\ngl_FragColor.rgb *= color;\n}\n}"},ka=p.createProgram(),P=p.createShader(p.FRAGMENT_SHADER),
13577 M=p.createShader(p.VERTEX_SHADER),V="precision "+a.getPrecision()+" float;\n";p.shaderSource(P,V+F.fragmentShader);p.shaderSource(M,V+F.vertexShader);p.compileShader(P);p.compileShader(M);p.attachShader(ka,P);p.attachShader(ka,M);p.linkProgram(ka);x=ka;q=p.getAttribLocation(x,"position");v=p.getAttribLocation(x,"uv");c=p.getUniformLocation(x,"renderType");d=p.getUniformLocation(x,"map");e=p.getUniformLocation(x,"occlusionMap");f=p.getUniformLocation(x,"opacity");g=p.getUniformLocation(x,"color");
13578 h=p.getUniformLocation(x,"scale");k=p.getUniformLocation(x,"rotation");m=p.getUniformLocation(x,"screenPosition")}p.useProgram(x);r.initAttributes();r.enableAttribute(q);r.enableAttribute(v);r.disableUnusedAttributes();p.uniform1i(e,0);p.uniform1i(d,1);p.bindBuffer(p.ARRAY_BUFFER,l);p.vertexAttribPointer(q,2,p.FLOAT,!1,16,0);p.vertexAttribPointer(v,2,p.FLOAT,!1,16,8);p.bindBuffer(p.ELEMENT_ARRAY_BUFFER,t);r.disable(p.CULL_FACE);r.buffers.depth.setMask(!1);ka=0;for(P=b.length;ka<P;ka++)if(F=16/W.w,
13579 ja.set(F*D,F),M=b[ka],w.set(M.matrixWorld.elements[12],M.matrixWorld.elements[13],M.matrixWorld.elements[14]),w.applyMatrix4(I.matrixWorldInverse),w.applyMatrix4(I.projectionMatrix),T.copy(w),fb.x=W.x+T.x*O+O-8,fb.y=W.y+T.y*aa+aa-8,!0===Ya.containsPoint(fb)){r.activeTexture(p.TEXTURE0);r.bindTexture(p.TEXTURE_2D,null);r.activeTexture(p.TEXTURE1);r.bindTexture(p.TEXTURE_2D,u);p.copyTexImage2D(p.TEXTURE_2D,0,p.RGB,fb.x,fb.y,16,16,0);p.uniform1i(c,0);p.uniform2f(h,ja.x,ja.y);p.uniform3f(m,T.x,T.y,T.z);
13580 r.disable(p.BLEND);r.enable(p.DEPTH_TEST);p.drawElements(p.TRIANGLES,6,p.UNSIGNED_SHORT,0);r.activeTexture(p.TEXTURE0);r.bindTexture(p.TEXTURE_2D,H);p.copyTexImage2D(p.TEXTURE_2D,0,p.RGBA,fb.x,fb.y,16,16,0);p.uniform1i(c,1);r.disable(p.DEPTH_TEST);r.activeTexture(p.TEXTURE1);r.bindTexture(p.TEXTURE_2D,u);p.drawElements(p.TRIANGLES,6,p.UNSIGNED_SHORT,0);M.positionScreen.copy(T);M.customUpdateCallback?M.customUpdateCallback(M):M.updateLensFlares();p.uniform1i(c,2);r.enable(p.BLEND);for(var V=0,pa=M.lensFlares.length;V<
13581 pa;V++){var S=M.lensFlares[V];.001<S.opacity&&.001<S.scale&&(T.x=S.x,T.y=S.y,T.z=S.z,F=S.size*S.scale/W.w,ja.x=F*D,ja.y=F,p.uniform3f(m,T.x,T.y,T.z),p.uniform2f(h,ja.x,ja.y),p.uniform1f(k,S.rotation),p.uniform1f(f,S.opacity),p.uniform3f(g,S.color.r,S.color.g,S.color.b),r.setBlending(S.blending,S.blendEquation,S.blendSrc,S.blendDst),a.setTexture2D(S.texture,1),p.drawElements(p.TRIANGLES,6,p.UNSIGNED_SHORT,0))}}r.enable(p.CULL_FACE);r.enable(p.DEPTH_TEST);r.buffers.depth.setMask(!0);a.resetGLState()}}}
13582 function If(a,b){var c,d,e,f,g,h,k,m,q,v,p,r,l,t,y,x,u;function H(a,b){return a.renderOrder!==b.renderOrder?a.renderOrder-b.renderOrder:a.z!==b.z?b.z-a.z:b.id-a.id}var w=a.context,I=a.state,W,D,O,aa,F=new n,ja=new oa,T=new n;this.render=function(n,Ya){if(0!==b.length){if(void 0===O){var ka=new Float32Array([-.5,-.5,0,0,.5,-.5,1,0,.5,.5,1,1,-.5,.5,0,1]),P=new Uint16Array([0,1,2,0,2,3]);W=w.createBuffer();D=w.createBuffer();w.bindBuffer(w.ARRAY_BUFFER,W);w.bufferData(w.ARRAY_BUFFER,ka,w.STATIC_DRAW);
13583 w.bindBuffer(w.ELEMENT_ARRAY_BUFFER,D);w.bufferData(w.ELEMENT_ARRAY_BUFFER,P,w.STATIC_DRAW);var ka=w.createProgram(),P=w.createShader(w.VERTEX_SHADER),M=w.createShader(w.FRAGMENT_SHADER);w.shaderSource(P,["precision "+a.getPrecision()+" 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;\nvoid main() {\nvUV = uvOffset + uv * uvScale;\nvec2 alignedPosition = position * scale;\nvec2 rotatedPosition;\nrotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\nrotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\nvec4 finalPosition;\nfinalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\nfinalPosition.xy += rotatedPosition;\nfinalPosition = projectionMatrix * finalPosition;\ngl_Position = finalPosition;\n}"].join("\n"));
13584 w.shaderSource(M,["precision "+a.getPrecision()+" 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;\nvoid main() {\nvec4 texture = texture2D( map, vUV );\nif ( texture.a < alphaTest ) discard;\ngl_FragColor = vec4( color * texture.xyz, texture.a * opacity );\nif ( fogType > 0 ) {\nfloat depth = gl_FragCoord.z / gl_FragCoord.w;\nfloat fogFactor = 0.0;\nif ( fogType == 1 ) {\nfogFactor = smoothstep( fogNear, fogFar, depth );\n} else {\nconst float LOG2 = 1.442695;\nfogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );\nfogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );\n}\ngl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );\n}\n}"].join("\n"));
13585 w.compileShader(P);w.compileShader(M);w.attachShader(ka,P);w.attachShader(ka,M);w.linkProgram(ka);O=ka;x=w.getAttribLocation(O,"position");u=w.getAttribLocation(O,"uv");c=w.getUniformLocation(O,"uvOffset");d=w.getUniformLocation(O,"uvScale");e=w.getUniformLocation(O,"rotation");f=w.getUniformLocation(O,"scale");g=w.getUniformLocation(O,"color");h=w.getUniformLocation(O,"map");k=w.getUniformLocation(O,"opacity");m=w.getUniformLocation(O,"modelViewMatrix");q=w.getUniformLocation(O,"projectionMatrix");
13586 v=w.getUniformLocation(O,"fogType");p=w.getUniformLocation(O,"fogDensity");r=w.getUniformLocation(O,"fogNear");l=w.getUniformLocation(O,"fogFar");t=w.getUniformLocation(O,"fogColor");y=w.getUniformLocation(O,"alphaTest");ka=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");ka.width=8;ka.height=8;P=ka.getContext("2d");P.fillStyle="white";P.fillRect(0,0,8,8);aa=new ba(ka);aa.needsUpdate=!0}w.useProgram(O);I.initAttributes();I.enableAttribute(x);I.enableAttribute(u);I.disableUnusedAttributes();
13587 I.disable(w.CULL_FACE);I.enable(w.BLEND);w.bindBuffer(w.ARRAY_BUFFER,W);w.vertexAttribPointer(x,2,w.FLOAT,!1,16,0);w.vertexAttribPointer(u,2,w.FLOAT,!1,16,8);w.bindBuffer(w.ELEMENT_ARRAY_BUFFER,D);w.uniformMatrix4fv(q,!1,Ya.projectionMatrix.elements);I.activeTexture(w.TEXTURE0);w.uniform1i(h,0);P=ka=0;(M=n.fog)?(w.uniform3f(t,M.color.r,M.color.g,M.color.b),M.isFog?(w.uniform1f(r,M.near),w.uniform1f(l,M.far),w.uniform1i(v,1),P=ka=1):M.isFogExp2&&(w.uniform1f(p,M.density),w.uniform1i(v,2),P=ka=2)):
13588 (w.uniform1i(v,0),P=ka=0);for(var M=0,V=b.length;M<V;M++){var pa=b[M];pa.modelViewMatrix.multiplyMatrices(Ya.matrixWorldInverse,pa.matrixWorld);pa.z=-pa.modelViewMatrix.elements[14]}b.sort(H);for(var S=[],M=0,V=b.length;M<V;M++){var pa=b[M],N=pa.material;if(!1!==N.visible){pa.onBeforeRender(a,n,Ya,void 0,N,void 0);w.uniform1f(y,N.alphaTest);w.uniformMatrix4fv(m,!1,pa.modelViewMatrix.elements);pa.matrixWorld.decompose(F,ja,T);S[0]=T.x;S[1]=T.y;var C=0;n.fog&&N.fog&&(C=P);ka!==C&&(w.uniform1i(v,C),
13589 ka=C);null!==N.map?(w.uniform2f(c,N.map.offset.x,N.map.offset.y),w.uniform2f(d,N.map.repeat.x,N.map.repeat.y)):(w.uniform2f(c,0,0),w.uniform2f(d,1,1));w.uniform1f(k,N.opacity);w.uniform3f(g,N.color.r,N.color.g,N.color.b);w.uniform1f(e,N.rotation);w.uniform2fv(f,S);I.setBlending(N.blending,N.blendEquation,N.blendSrc,N.blendDst,N.blendEquationAlpha,N.blendSrcAlpha,N.blendDstAlpha,N.premultipliedAlpha);I.buffers.depth.setTest(N.depthTest);I.buffers.depth.setMask(N.depthWrite);N.map?a.setTexture2D(N.map,
13590 0):a.setTexture2D(aa,0);w.drawElements(w.TRIANGLES,6,w.UNSIGNED_SHORT,0);pa.onAfterRender(a,n,Ya,void 0,N,void 0)}}I.enable(w.CULL_FACE);a.resetGLState()}}}function U(){Object.defineProperty(this,"id",{value:Jf++});this.uuid=Y.generateUUID();this.name="";this.type="Material";this.lights=this.fog=!0;this.blending=1;this.side=0;this.shading=2;this.vertexColors=0;this.opacity=1;this.transparent=!1;this.blendSrc=204;this.blendDst=205;this.blendEquation=100;this.blendEquationAlpha=this.blendDstAlpha=this.blendSrcAlpha=
13591 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.needsUpdate=this.visible=!0}function ra(a){U.call(this);this.type="ShaderMaterial";this.defines={};this.uniforms={};this.vertexShader="void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
13592 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,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."),
13593 this.setValues(a))}function Za(a){U.call(this);this.type="MeshDepthMaterial";this.depthPacking=3200;this.morphTargets=this.skinning=!1;this.displacementMap=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 Ra(a,b){this.min=void 0!==a?a:new n(Infinity,Infinity,Infinity);this.max=void 0!==b?b:new n(-Infinity,-Infinity,-Infinity)}function Ea(a,b){this.center=void 0!==a?a:new n;this.radius=
13594 void 0!==b?b:0}function Ba(){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 Aa(a,b){this.normal=void 0!==a?a:new n(1,0,0);this.constant=void 0!==b?b:0}function gd(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,d){function e(b,c,d,e){var f=b.geometry,g;g=t;var h=b.customDepthMaterial;
13595 d&&(g=y,h=b.customDistanceMaterial);h?g=h:(h=!1,c.morphTargets&&(f&&f.isBufferGeometry?h=f.morphAttributes&&f.morphAttributes.position&&0<f.morphAttributes.position.length:f&&f.isGeometry&&(h=f.morphTargets&&0<f.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,f=0,h&&(f|=1),b&&(f|=2),g=g[f]);a.localClippingEnabled&&!0===c.clipShadows&&0!==c.clippingPlanes.length&&(f=
13596 g.uuid,h=c.uuid,b=x[f],void 0===b&&(b={},x[f]=b),f=b[h],void 0===f&&(f=g.clone(),b[h]=f),g=f);g.visible=c.visible;g.wireframe=c.wireframe;h=c.side;F.renderSingleSided&&2==h&&(h=0);F.renderReverseSided&&(0===h?h=1:1===h&&(h=0));g.side=h;g.clipShadows=c.clipShadows;g.clippingPlanes=c.clippingPlanes;g.wireframeLinewidth=c.wireframeLinewidth;g.linewidth=c.linewidth;d&&void 0!==g.uniforms.lightPos&&g.uniforms.lightPos.value.copy(e);return g}function f(b,d,g,h){if(!1!==b.visible){if(b.layers.test(d.layers)&&
13597 (b.isMesh||b.isLine||b.isPoints)&&b.castShadow&&(!b.frustumCulled||k.intersectsObject(b))){b.modelViewMatrix.multiplyMatrices(g.matrixWorldInverse,b.matrixWorld);var m=c.update(b),p=b.material;if(Array.isArray(p))for(var q=m.groups,v=0,r=q.length;v<r;v++){var u=q[v],w=p[u.materialIndex];w&&w.visible&&(w=e(b,w,h,l),a.renderBufferDirect(g,null,m,w,b,u))}else p.visible&&(w=e(b,p,h,l),a.renderBufferDirect(g,null,m,w,b,null))}b=b.children;m=0;for(p=b.length;m<p;m++)f(b[m],d,g,h)}}var g=a.context,h=a.state,
13598 k=new gd,m=new K,q=b.shadows,v=new C,p=new C(d.maxTextureSize,d.maxTextureSize),r=new n,l=new n,t=Array(4),y=Array(4),x={},u=[new n(1,0,0),new n(-1,0,0),new n(0,0,1),new n(0,0,-1),new n(0,1,0),new n(0,-1,0)],H=[new n(0,1,0),new n(0,1,0),new n(0,1,0),new n(0,1,0),new n(0,0,1),new n(0,0,-1)],w=[new fa,new fa,new fa,new fa,new fa,new fa];b=new Za;b.depthPacking=3201;b.clipping=!0;d=$a.distanceRGBA;for(var I=Ca.clone(d.uniforms),W=0;4!==W;++W){var D=0!==(W&1),O=0!==(W&2),aa=b.clone();aa.morphTargets=
13599 D;aa.skinning=O;t[W]=aa;D=new ra({defines:{USE_SHADOWMAP:""},uniforms:I,vertexShader:d.vertexShader,fragmentShader:d.fragmentShader,morphTargets:D,skinning:O,clipping:!0});y[W]=D}var F=this;this.enabled=!1;this.autoUpdate=!0;this.needsUpdate=!1;this.type=1;this.renderSingleSided=this.renderReverseSided=!0;this.render=function(b,c){if(!1!==F.enabled&&(!1!==F.autoUpdate||!1!==F.needsUpdate)&&0!==q.length){h.disable(g.BLEND);h.buffers.color.setClear(1,1,1,1);h.buffers.depth.setTest(!0);h.setScissorTest(!1);
13600 for(var d,e=0,t=q.length;e<t;e++){var n=q[e];d=n.shadow;var y=n&&n.isPointLight;if(void 0===d)console.warn("THREE.WebGLShadowMap:",n,"has no shadow.");else{var x=d.camera;v.copy(d.mapSize);v.min(p);if(y){var D=v.x,I=v.y;w[0].set(2*D,I,D,I);w[1].set(0,I,D,I);w[2].set(3*D,I,D,I);w[3].set(D,I,D,I);w[4].set(3*D,0,D,I);w[5].set(D,0,D,I);v.x*=4;v.y*=2}null===d.map&&(d.map=new Cb(v.x,v.y,{minFilter:1003,magFilter:1003,format:1023}),d.map.texture.name=n.name+".shadowMap",x.updateProjectionMatrix());d.isSpotLightShadow&&
13601 d.update(n);D=d.map;I=d.matrix;l.setFromMatrixPosition(n.matrixWorld);x.position.copy(l);y?(d=6,I.makeTranslation(-l.x,-l.y,-l.z)):(d=1,r.setFromMatrixPosition(n.target.matrixWorld),x.lookAt(r),x.updateMatrixWorld(),I.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),I.multiply(x.projectionMatrix),I.multiply(x.matrixWorldInverse));a.setRenderTarget(D);a.clear();for(n=0;n<d;n++)y&&(r.copy(x.position),r.add(u[n]),x.up.copy(H[n]),x.lookAt(r),x.updateMatrixWorld(),h.viewport(w[n])),m.multiplyMatrices(x.projectionMatrix,
13602 x.matrixWorldInverse),k.setFromMatrix(m),f(b,c,x,y)}}e=a.getClearColor();t=a.getClearAlpha();a.setClearColor(e,t);F.needsUpdate=!1}}}function Kf(a){var b={};return{get:function(a){a.isInterleavedBufferAttribute&&(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,g=f.array,h=f.dynamic?
13603 a.DYNAMIC_DRAW:a.STATIC_DRAW,k=a.createBuffer();a.bindBuffer(d,k);a.bufferData(d,g,h);f.onUploadCallback();h=a.FLOAT;g instanceof Float32Array?h=a.FLOAT:g instanceof Float64Array?console.warn("THREE.WebGLAttributes: Unsupported data buffer format: Float64Array."):g instanceof Uint16Array?h=a.UNSIGNED_SHORT:g instanceof Int16Array?h=a.SHORT:g instanceof Uint32Array?h=a.UNSIGNED_INT:g instanceof Int32Array?h=a.INT:g instanceof Int8Array?h=a.BYTE:g instanceof Uint8Array&&(h=a.UNSIGNED_BYTE);b[e]={buffer:k,
13604 type:h,bytesPerElement:g.BYTES_PER_ELEMENT,version:f.version}}else e.version<c.version&&(f=c,g=f.array,k=f.updateRange,a.bindBuffer(d,e.buffer),!1===f.dynamic?a.bufferData(d,g,a.STATIC_DRAW):-1===k.count?a.bufferSubData(d,0,g):0===k.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."):(a.bufferSubData(d,k.offset*g.BYTES_PER_ELEMENT,g.subarray(k.offset,k.offset+
13605 k.count)),k.count=-1),e.version=c.version)}}}function ab(a,b,c,d){this._x=a||0;this._y=b||0;this._z=c||0;this._order=d||ab.DefaultOrder}function Qd(){this.mask=1}function z(){Object.defineProperty(this,"id",{value:Lf++});this.uuid=Y.generateUUID();this.name="";this.type="Object3D";this.parent=null;this.children=[];this.up=z.DefaultUp.clone();var a=new n,b=new ab,c=new oa,d=new n(1,1,1);b.onChange(function(){c.setFromEuler(b,!1)});c.onChange(function(){b.setFromQuaternion(c,void 0,!1)});Object.defineProperties(this,
13606 {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 Ba}});this.matrix=new K;this.matrixWorld=new K;this.matrixAutoUpdate=z.DefaultMatrixAutoUpdate;this.matrixWorldNeedsUpdate=!1;this.layers=new Qd;this.visible=!0;this.receiveShadow=this.castShadow=!1;this.frustumCulled=!0;this.renderOrder=0;this.userData={}}function Na(){z.call(this);this.type="Camera";this.matrixWorldInverse=
13607 new K;this.projectionMatrix=new K}function Fb(a,b,c,d,e,f){Na.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 qa(a,b,c,d){Na.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=
13608 0;this.updateProjectionMatrix()}function Sa(a,b,c,d,e,f){this.a=a;this.b=b;this.c=c;this.normal=d&&d.isVector3?d:new n;this.vertexNormals=Array.isArray(d)?d:[];this.color=e&&e.isColor?e:new G;this.vertexColors=Array.isArray(e)?e:[];this.materialIndex=void 0!==f?f:0}function J(){Object.defineProperty(this,"id",{value:Rd++});this.uuid=Y.generateUUID();this.name="";this.type="Geometry";this.vertices=[];this.colors=[];this.faces=[];this.faceVertexUvs=[[]];this.morphTargets=[];this.morphNormals=[];this.skinWeights=
13609 [];this.skinIndices=[];this.lineDistances=[];this.boundingSphere=this.boundingBox=null;this.groupsNeedUpdate=this.lineDistancesNeedUpdate=this.colorsNeedUpdate=this.normalsNeedUpdate=this.uvsNeedUpdate=this.verticesNeedUpdate=this.elementsNeedUpdate=!1}function Z(a,b,c){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.uuid=Y.generateUUID();this.name="";this.array=a;this.itemSize=b;this.count=void 0!==a?a.length/b:0;this.normalized=!0===c;this.dynamic=
13610 !1;this.updateRange={offset:0,count:-1};this.onUploadCallback=function(){};this.version=0}function pc(a,b){Z.call(this,new Int8Array(a),b)}function qc(a,b){Z.call(this,new Uint8Array(a),b)}function rc(a,b){Z.call(this,new Uint8ClampedArray(a),b)}function sc(a,b){Z.call(this,new Int16Array(a),b)}function gb(a,b){Z.call(this,new Uint16Array(a),b)}function tc(a,b){Z.call(this,new Int32Array(a),b)}function hb(a,b){Z.call(this,new Uint32Array(a),b)}function B(a,b){Z.call(this,new Float32Array(a),b)}function uc(a,
13611 b){Z.call(this,new Float64Array(a),b)}function Je(){this.indices=[];this.vertices=[];this.normals=[];this.colors=[];this.uvs=[];this.uvs2=[];this.groups=[];this.morphTargets={};this.skinWeights=[];this.skinIndices=[];this.boundingSphere=this.boundingBox=null;this.groupsNeedUpdate=this.uvsNeedUpdate=this.colorsNeedUpdate=this.normalsNeedUpdate=this.verticesNeedUpdate=!1}function Sd(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 E(){Object.defineProperty(this,
13612 "id",{value:Rd++});this.uuid=Y.generateUUID();this.name="";this.type="BufferGeometry";this.index=null;this.attributes={};this.morphAttributes={};this.groups=[];this.boundingSphere=this.boundingBox=null;this.drawRange={start:0,count:Infinity}}function Gb(a,b,c,d,e,f){J.call(this);this.type="BoxGeometry";this.parameters={width:a,height:b,depth:c,widthSegments:d,heightSegments:e,depthSegments:f};this.fromBufferGeometry(new ib(a,b,c,d,e,f));this.mergeVertices()}function ib(a,b,c,d,e,f){function g(a,b,
13613 c,d,e,f,g,l,W,D,O){var aa=f/W,F=g/D,ja=f/2,T=g/2,C=l/2;g=W+1;var B=D+1,z=f=0,P,M,V=new n;for(M=0;M<B;M++){var pa=M*F-T;for(P=0;P<g;P++)V[a]=(P*aa-ja)*d,V[b]=pa*e,V[c]=C,m.push(V.x,V.y,V.z),V[a]=0,V[b]=0,V[c]=0<l?1:-1,q.push(V.x,V.y,V.z),v.push(P/W),v.push(1-M/D),f+=1}for(M=0;M<D;M++)for(P=0;P<W;P++)a=p+P+g*(M+1),b=p+(P+1)+g*(M+1),c=p+(P+1)+g*M,k.push(p+P+g*M,a,c),k.push(a,b,c),z+=6;h.addGroup(r,z,O);r+=z;p+=f}E.call(this);this.type="BoxBufferGeometry";this.parameters={width:a,height:b,depth:c,widthSegments:d,
13614 heightSegments:e,depthSegments:f};var h=this;d=Math.floor(d)||1;e=Math.floor(e)||1;f=Math.floor(f)||1;var k=[],m=[],q=[],v=[],p=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 B(m,3));this.addAttribute("normal",new B(q,3));this.addAttribute("uv",new B(v,2))}function vc(a,b,c,d){J.call(this);this.type=
13615 "PlaneGeometry";this.parameters={width:a,height:b,widthSegments:c,heightSegments:d};this.fromBufferGeometry(new jb(a,b,c,d));this.mergeVertices()}function jb(a,b,c,d){E.call(this);this.type="PlaneBufferGeometry";this.parameters={width:a,height:b,widthSegments:c,heightSegments:d};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,m=b/d,q=[],v=[],p=[],r=[];for(a=0;a<h;a++){var l=a*m-f;for(b=0;b<g;b++)v.push(b*k-e,-l,0),p.push(0,0,1),r.push(b/c),r.push(1-a/d)}for(a=0;a<d;a++)for(b=
13616 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",new B(v,3));this.addAttribute("normal",new B(p,3));this.addAttribute("uv",new B(r,2))}function ya(a){U.call(this);this.type="MeshBasicMaterial";this.color=new G(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=
13617 !1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.lights=this.morphTargets=this.skinning=!1;this.setValues(a)}function kb(a,b){this.origin=void 0!==a?a:new n;this.direction=void 0!==b?b:new n}function Hb(a,b){this.start=void 0!==a?a:new n;this.end=void 0!==b?b:new n}function Ta(a,b,c){this.a=void 0!==a?a:new n;this.b=void 0!==b?b:new n;this.c=void 0!==c?c:new n}function la(a,b){z.call(this);this.type="Mesh";this.geometry=void 0!==a?a:new E;this.material=void 0!==
13618 b?b:new ya({color:16777215*Math.random()});this.drawMode=0;this.updateMorphTargets()}function Mf(a,b,c,d){function e(a,c){b.buffers.color.setClear(a.r,a.g,a.b,c,d)}var f=new G(0),g=0,h,k,m,q;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,g)},render:function(b,d,r){b=b.background;null===b?e(f,g):b&&b.isColor&&(e(b,1),r=!0);(a.autoClear||r)&&a.clear(a.autoClearColor,a.autoClearDepth,
13619 a.autoClearStencil);b&&b.isCubeTexture?(void 0===m&&(m=new qa,q=new la(new ib(5,5,5),new ra({uniforms:$a.cube.uniforms,vertexShader:$a.cube.vertexShader,fragmentShader:$a.cube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1}))),m.projectionMatrix.copy(d.projectionMatrix),m.matrixWorld.extractRotation(d.matrixWorld),m.matrixWorldInverse.getInverse(m.matrixWorld),q.material.uniforms.tCube.value=b,q.modelViewMatrix.multiplyMatrices(m.matrixWorldInverse,q.matrixWorld),c.update(q),a.renderBufferDirect(m,
13620 null,q.geometry,q.material,q,null)):b&&b.isTexture&&(void 0===h&&(h=new Fb(-1,1,1,-1,0,1),k=new la(new jb(2,2),new ya({depthTest:!1,depthWrite:!1,fog:!1}))),k.material.map=b,c.update(k),a.renderBufferDirect(h,null,k.geometry,k.material,k,null))}}}function Nf(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-b.material.id:a.z!==b.z?a.z-b.z:a.id-b.id}function Of(a,b){return a.renderOrder!==
13621 b.renderOrder?a.renderOrder-b.renderOrder:a.z!==b.z?b.z-a.z:a.id-b.id}function Pf(){var a=[],b=-1,c=[],d=-1;return{opaque:a,transparent:c,init:function(){d=b=-1},push:function(e,f,g,h,k){var m,q;g.transparent?(m=c,q=++d):(m=a,q=++b);(q=m[q])?(q.id=e.id,q.object=e,q.geometry=f,q.material=g,q.program=g.program,q.renderOrder=e.renderOrder,q.z=h,q.group=k):(q={id:e.id,object:e,geometry:f,material:g,program:g.program,renderOrder:e.renderOrder,z:h,group:k},m.push(q))},finish:function(){a.length=b+1;c.length=
13622 d+1},sort:function(){a.sort(Nf);c.sort(Of)}}}function Qf(){var a={};return{get:function(b,c){var d=b.id+","+c.id,e=a[d];void 0===e&&(e=new Pf,a[d]=e);return e},dispose:function(){a={}}}}function Rf(a,b,c){var d,e,f;this.setMode=function(a){d=a};this.setIndex=function(a){e=a.type;f=a.bytesPerElement};this.render=function(b,h){a.drawElements(d,h,e,b*f);c.calls++;c.vertices+=h;d===a.TRIANGLES&&(c.faces+=h/3)};this.renderInstances=function(g,h,k){var m=b.get("ANGLE_instanced_arrays");null===m?console.error("THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays."):
13623 (m.drawElementsInstancedANGLE(d,k,e,h*f,g.maxInstancedCount),c.calls++,c.vertices+=k*g.maxInstancedCount,d===a.TRIANGLES&&(c.faces+=g.maxInstancedCount*k/3))}}function Sf(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)};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.");
13624 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)}}}function Tf(a,b,c){function d(a){a=a.target;var h=e[a.id];null!==h.index&&b.remove(h.index);for(var k in h.attributes)b.remove(h.attributes[k]);a.removeEventListener("dispose",d);delete e[a.id];if(k=f[a.id])b.remove(k),
13625 delete f[a.id];if(k=f[h.id])b.remove(k),delete f[h.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 E).setFromObject(a)),f=b._bufferGeometry);e[b.id]=f;c.geometries++;return f},update:function(c){var d=c.index,e=c.attributes;null!==d&&b.update(d,a.ELEMENT_ARRAY_BUFFER);for(var f in e)b.update(e[f],a.ARRAY_BUFFER);c=c.morphAttributes;for(f in c)for(var d=
13626 c[f],e=0,q=d.length;e<q;e++)b.update(d[e],a.ARRAY_BUFFER)},getWireframeAttribute:function(c){var d=f[c.id];if(d)return d;var d=[],e=c.index,m=c.attributes;if(null!==e)for(var e=e.array,m=0,q=e.length;m<q;m+=3){var v=e[m+0],p=e[m+1],r=e[m+2];d.push(v,p,p,r,r,v)}else for(e=m.position.array,m=0,q=e.length/3-1;m<q;m+=3)v=m+0,p=m+1,r=m+2,d.push(v,p,p,r,r,v);d=new (65535<Sd(d)?hb:gb)(d,1);b.update(d,a.ELEMENT_ARRAY_BUFFER);return f[c.id]=d}}}function Uf(){var a={};return{get:function(b){if(void 0!==a[b.id])return a[b.id];
13627 var c;switch(b.type){case "DirectionalLight":c={direction:new n,color:new G,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new C};break;case "SpotLight":c={position:new n,direction:new n,color:new G,distance:0,coneCos:0,penumbraCos:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new C};break;case "PointLight":c={position:new n,color:new G,distance:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new C};break;case "HemisphereLight":c={direction:new n,skyColor:new G,
13628 groundColor:new G};break;case "RectAreaLight":c={color:new G,position:new n,halfWidth:new n,halfHeight:new n}}return a[b.id]=c}}}function Vf(a,b,c){var d={};return{update:function(a){var f=c.frame,g=a.geometry,h=b.get(a,g);d[h.id]!==f&&(g.isGeometry&&h.updateFromObject(a),b.update(h),d[h.id]=f);return h},clear:function(){d={}}}}function Wf(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);
13629 !1===a.getShaderParameter(d,a.COMPILE_STATUS)&&console.error("THREE.WebGLShader: Shader couldn't compile.");""!==a.getShaderInfoLog(d)&&console.warn("THREE.WebGLShader: gl.getShaderInfoLog()",b===a.VERTEX_SHADER?"vertex":"fragment",a.getShaderInfoLog(d),Wf(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",
13630 "( value, 256.0 )"];case 3007:return["Gamma","( value, float( GAMMA_FACTOR ) )"];default:throw Error("unsupported encoding: "+a);}}function Td(a,b){var c=Le(b);return"vec4 "+a+"( vec4 value ) { return "+c[0]+"ToLinear"+c[1]+"; }"}function Xf(a,b){var c=Le(b);return"vec4 "+a+"( vec4 value ) { return LinearTo"+c[0]+c[1]+"; }"}function Yf(a,b){var c;switch(b){case 1:c="Linear";break;case 2:c="Reinhard";break;case 3:c="Uncharted2";break;case 4:c="OptimizedCineon";break;default:throw Error("unsupported toneMapping: "+
13631 b);}return"vec3 "+a+"( vec3 color ) { return "+c+"ToneMapping( color ); }"}function Zf(a,b,c){a=a||{};return[a.derivatives||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":
13632 ""].filter(wc).join("\n")}function $f(a){var b=[],c;for(c in a){var d=a[c];!1!==d&&b.push("#define "+c+" "+d)}return b.join("\n")}function wc(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 Ud(a){return a.replace(/^[ \t]*#include +<([\w\d.]+)>/gm,function(a,c){var d=X[c];
13633 if(void 0===d)throw Error("Can not resolve #include <"+c+">");return Ud(d)})}function Ne(a){return a.replace(/for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g,function(a,c,d,e){a="";for(c=parseInt(c);c<parseInt(d);c++)a+=e.replace(/\[ i \]/g,"[ "+c+" ]");return a})}function ag(a,b,c,d,e){var f=a.context,g=c.extensions,h=c.defines,k=d.vertexShader,m=d.fragmentShader,q="SHADOWMAP_TYPE_BASIC";1===e.shadowMapType?q="SHADOWMAP_TYPE_PCF":2===e.shadowMapType&&(q="SHADOWMAP_TYPE_PCF_SOFT");
13634 var v="ENVMAP_TYPE_CUBE",p="ENVMAP_MODE_REFLECTION",r="ENVMAP_BLENDING_MULTIPLY";if(e.envMap){switch(c.envMap.mapping){case 301:case 302:v="ENVMAP_TYPE_CUBE";break;case 306:case 307:v="ENVMAP_TYPE_CUBE_UV";break;case 303:case 304:v="ENVMAP_TYPE_EQUIREC";break;case 305:v="ENVMAP_TYPE_SPHERE"}switch(c.envMap.mapping){case 302:case 304:p="ENVMAP_MODE_REFRACTION"}switch(c.combine){case 0:r="ENVMAP_BLENDING_MULTIPLY";break;case 1:r="ENVMAP_BLENDING_MIX";break;case 2:r="ENVMAP_BLENDING_ADD"}}var l=0<a.gammaFactor?
13635 a.gammaFactor:1,g=Zf(g,e,a.extensions),t=$f(h),n=f.createProgram();c.isRawShaderMaterial?(h=[t,"\n"].filter(wc).join("\n"),d=[g,t,"\n"].filter(wc).join("\n")):(h=["precision "+e.precision+" float;","precision "+e.precision+" int;","#define SHADER_NAME "+d.name,t,e.supportsVertexTextures?"#define VERTEX_TEXTURES":"","#define GAMMA_FACTOR "+l,"#define MAX_BONES "+e.maxBones,e.useFog&&e.fog?"#define USE_FOG":"",e.useFog&&e.fogExp?"#define FOG_EXP2":"",e.map?"#define USE_MAP":"",e.envMap?"#define USE_ENVMAP":
13636 "",e.envMap?"#define "+p:"",e.lightMap?"#define USE_LIGHTMAP":"",e.aoMap?"#define USE_AOMAP":"",e.emissiveMap?"#define USE_EMISSIVEMAP":"",e.bumpMap?"#define USE_BUMPMAP":"",e.normalMap?"#define USE_NORMALMAP":"",e.displacementMap&&e.supportsVertexTextures?"#define USE_DISPLACEMENTMAP":"",e.specularMap?"#define USE_SPECULARMAP":"",e.roughnessMap?"#define USE_ROUGHNESSMAP":"",e.metalnessMap?"#define USE_METALNESSMAP":"",e.alphaMap?"#define USE_ALPHAMAP":"",e.vertexColors?"#define USE_COLOR":"",e.flatShading?
13637 "#define FLAT_SHADED":"",e.skinning?"#define USE_SKINNING":"",e.useVertexTexture?"#define BONE_TEXTURE":"",e.morphTargets?"#define USE_MORPHTARGETS":"",e.morphNormals&&!1===e.flatShading?"#define USE_MORPHNORMALS":"",e.doubleSided?"#define DOUBLE_SIDED":"",e.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+e.numClippingPlanes,e.shadowMapEnabled?"#define USE_SHADOWMAP":"",e.shadowMapEnabled?"#define "+q:"",e.sizeAttenuation?"#define USE_SIZEATTENUATION":"",e.logarithmicDepthBuffer?
13638 "#define USE_LOGDEPTHBUF":"",e.logarithmicDepthBuffer&&a.extensions.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","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;",
13639 "\tattribute vec3 morphTarget2;","\tattribute vec3 morphTarget3;","\t#ifdef USE_MORPHNORMALS","\t\tattribute vec3 morphNormal0;","\t\tattribute vec3 morphNormal1;","\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(wc).join("\n"),
13640 d=[g,"precision "+e.precision+" float;","precision "+e.precision+" int;","#define SHADER_NAME "+d.name,t,e.alphaTest?"#define ALPHATEST "+e.alphaTest:"","#define GAMMA_FACTOR "+l,e.useFog&&e.fog?"#define USE_FOG":"",e.useFog&&e.fogExp?"#define FOG_EXP2":"",e.map?"#define USE_MAP":"",e.envMap?"#define USE_ENVMAP":"",e.envMap?"#define "+v:"",e.envMap?"#define "+p:"",e.envMap?"#define "+r:"",e.lightMap?"#define USE_LIGHTMAP":"",e.aoMap?"#define USE_AOMAP":"",e.emissiveMap?"#define USE_EMISSIVEMAP":"",
13641 e.bumpMap?"#define USE_BUMPMAP":"",e.normalMap?"#define USE_NORMALMAP":"",e.specularMap?"#define USE_SPECULARMAP":"",e.roughnessMap?"#define USE_ROUGHNESSMAP":"",e.metalnessMap?"#define USE_METALNESSMAP":"",e.alphaMap?"#define USE_ALPHAMAP":"",e.vertexColors?"#define USE_COLOR":"",e.gradientMap?"#define USE_GRADIENTMAP":"",e.flatShading?"#define FLAT_SHADED":"",e.doubleSided?"#define DOUBLE_SIDED":"",e.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+e.numClippingPlanes,"#define UNION_CLIPPING_PLANES "+
13642 (e.numClippingPlanes-e.numClipIntersection),e.shadowMapEnabled?"#define USE_SHADOWMAP":"",e.shadowMapEnabled?"#define "+q:"",e.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",e.physicallyCorrectLights?"#define PHYSICALLY_CORRECT_LIGHTS":"",e.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",e.logarithmicDepthBuffer&&a.extensions.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"",e.envMap&&a.extensions.get("EXT_shader_texture_lod")?"#define TEXTURE_LOD_EXT":"","uniform mat4 viewMatrix;",
13643 "uniform vec3 cameraPosition;",0!==e.toneMapping?"#define TONE_MAPPING":"",0!==e.toneMapping?X.tonemapping_pars_fragment:"",0!==e.toneMapping?Yf("toneMapping",e.toneMapping):"",e.dithering?"#define DITHERING":"",e.outputEncoding||e.mapEncoding||e.envMapEncoding||e.emissiveMapEncoding?X.encodings_pars_fragment:"",e.mapEncoding?Td("mapTexelToLinear",e.mapEncoding):"",e.envMapEncoding?Td("envMapTexelToLinear",e.envMapEncoding):"",e.emissiveMapEncoding?Td("emissiveMapTexelToLinear",e.emissiveMapEncoding):
13644 "",e.outputEncoding?Xf("linearToOutputTexel",e.outputEncoding):"",e.depthPacking?"#define DEPTH_PACKING "+c.depthPacking:"","\n"].filter(wc).join("\n"));k=Ud(k);k=Me(k,e);m=Ud(m);m=Me(m,e);c.isShaderMaterial||(k=Ne(k),m=Ne(m));m=d+m;k=Ke(f,f.VERTEX_SHADER,h+k);m=Ke(f,f.FRAGMENT_SHADER,m);f.attachShader(n,k);f.attachShader(n,m);void 0!==c.index0AttributeName?f.bindAttribLocation(n,0,c.index0AttributeName):!0===e.morphTargets&&f.bindAttribLocation(n,0,"position");f.linkProgram(n);e=f.getProgramInfoLog(n);
13645 q=f.getShaderInfoLog(k);v=f.getShaderInfoLog(m);r=p=!0;if(!1===f.getProgramParameter(n,f.LINK_STATUS))p=!1,console.error("THREE.WebGLProgram: shader error: ",f.getError(),"gl.VALIDATE_STATUS",f.getProgramParameter(n,f.VALIDATE_STATUS),"gl.getProgramInfoLog",e,q,v);else if(""!==e)console.warn("THREE.WebGLProgram: gl.getProgramInfoLog()",e);else if(""===q||""===v)r=!1;r&&(this.diagnostics={runnable:p,material:c,programLog:e,vertexShader:{log:q,prefix:h},fragmentShader:{log:v,prefix:d}});f.deleteShader(k);
13646 f.deleteShader(m);var x;this.getUniforms=function(){void 0===x&&(x=new eb(f,n,a));return x};var u;this.getAttributes=function(){if(void 0===u){for(var a={},b=f.getProgramParameter(n,f.ACTIVE_ATTRIBUTES),c=0;c<b;c++){var d=f.getActiveAttrib(n,c).name;a[d]=f.getAttribLocation(n,d)}u=a}return u};this.destroy=function(){f.deleteProgram(n);this.program=void 0};Object.defineProperties(this,{uniforms:{get:function(){console.warn("THREE.WebGLProgram: .uniforms is now .getUniforms().");return this.getUniforms()}},
13647 attributes:{get:function(){console.warn("THREE.WebGLProgram: .attributes is now .getAttributes().");return this.getAttributes()}}});this.id=bg++;this.code=b;this.usedTimes=1;this.program=n;this.vertexShader=k;this.fragmentShader=m;return this}function cg(a,b){function c(a,b){var c;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):c=3E3;3E3===
13648 c&&b&&(c=3007);return c}var d=[],e={MeshDepthMaterial:"depth",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"phong",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points"},f="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(" ");
13649 this.getParameters=function(d,f,k,m,q,v){var p=e[d.type],r;if(v.isSkinnedMesh)if(r=v.skeleton.bones,b.floatVertexTextures)r=1024;else{var l=Math.min(Math.floor((b.maxVertexUniforms-20)/4),r.length);l<r.length?(console.warn("THREE.WebGLRenderer: Skeleton has "+r.length+" bones. This GPU supports "+l+"."),r=0):r=l}else r=0;l=a.getPrecision();null!==d.precision&&(l=b.getMaxPrecision(d.precision),l!==d.precision&&console.warn("THREE.WebGLProgram.getParameters:",d.precision,"not supported, using",l,"instead."));
13650 var t=a.getRenderTarget();return{shaderID:p,precision:l,supportsVertexTextures:b.vertexTextures,outputEncoding:c(t?t.texture:null,a.gammaOutput),map:!!d.map,mapEncoding:c(d.map,a.gammaInput),envMap:!!d.envMap,envMapMode:d.envMap&&d.envMap.mapping,envMapEncoding:c(d.envMap,a.gammaInput),envMapCubeUV:!!d.envMap&&(306===d.envMap.mapping||307===d.envMap.mapping),lightMap:!!d.lightMap,aoMap:!!d.aoMap,emissiveMap:!!d.emissiveMap,emissiveMapEncoding:c(d.emissiveMap,a.gammaInput),bumpMap:!!d.bumpMap,normalMap:!!d.normalMap,
13651 displacementMap:!!d.displacementMap,roughnessMap:!!d.roughnessMap,metalnessMap:!!d.metalnessMap,specularMap:!!d.specularMap,alphaMap:!!d.alphaMap,gradientMap:!!d.gradientMap,combine:d.combine,vertexColors:d.vertexColors,fog:!!k,useFog:d.fog,fogExp:k&&k.isFogExp2,flatShading:1===d.shading,sizeAttenuation:d.sizeAttenuation,logarithmicDepthBuffer:b.logarithmicDepthBuffer,skinning:d.skinning&&0<r,maxBones:r,useVertexTexture:b.floatVertexTextures,morphTargets:d.morphTargets,morphNormals:d.morphNormals,
13652 maxMorphTargets:a.maxMorphTargets,maxMorphNormals:a.maxMorphNormals,numDirLights:f.directional.length,numPointLights:f.point.length,numSpotLights:f.spot.length,numRectAreaLights:f.rectArea.length,numHemiLights:f.hemi.length,numClippingPlanes:m,numClipIntersection:q,dithering:d.dithering,shadowMapEnabled:a.shadowMap.enabled&&v.receiveShadow&&0<f.shadows.length,shadowMapType:a.shadowMap.type,toneMapping:a.toneMapping,physicallyCorrectLights:a.physicallyCorrectLights,premultipliedAlpha:d.premultipliedAlpha,
13653 alphaTest:d.alphaTest,doubleSided:2===d.side,flipSided:1===d.side,depthPacking:void 0!==d.depthPacking?d.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<f.length;e++)d.push(c[f[e]]);d.push(b.onBeforeCompile.toString());d.push(a.gammaOutput);return d.join()};this.acquireProgram=function(b,c,e,f){for(var q,v=0,p=d.length;v<
13654 p;v++){var r=d[v];if(r.code===f){q=r;++q.usedTimes;break}}void 0===q&&(q=new ag(a,f,b,c,e),d.push(q));return q};this.releaseProgram=function(a){if(0===--a.usedTimes){var b=d.indexOf(a);d[b]=d[d.length-1];d.pop();a.destroy()}};this.programs=d}function dg(a,b,c,d,e,f,g){function h(a,b){if(a.width>b||a.height>b){var c=b/Math.max(a.width,a.height),d=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");d.width=Math.floor(a.width*c);d.height=Math.floor(a.height*c);d.getContext("2d").drawImage(a,
13655 0,0,a.width,a.height,0,0,d.width,d.height);console.warn("THREE.WebGLRenderer: image is too big ("+a.width+"x"+a.height+"). Resized to "+d.width+"x"+d.height,a);return d}return a}function k(a){return Y.isPowerOfTwo(a.width)&&Y.isPowerOfTwo(a.height)}function m(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 v(b){b=b.target;b.removeEventListener("dispose",v);a:{var c=d.get(b);if(b.image&&c.__image__webglTextureCube)a.deleteTexture(c.__image__webglTextureCube);
13656 else{if(void 0===c.__webglInit)break a;a.deleteTexture(c.__webglTexture)}d.remove(b)}g.textures--}function p(b){b=b.target;b.removeEventListener("dispose",p);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),
13657 c.__webglDepthbuffer&&a.deleteRenderbuffer(c.__webglDepthbuffer);d.remove(b.texture);d.remove(b)}g.textures--}function r(b,p){var q=d.get(b);if(0<b.version&&q.__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===q.__webglInit&&(q.__webglInit=!0,b.addEventListener("dispose",v),q.__webglTexture=
13658 a.createTexture(),g.textures++);c.activeTexture(a.TEXTURE0+p);c.bindTexture(a.TEXTURE_2D,q.__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 t=h(b.image,e.maxTextureSize);if((1001!==b.wrapS||1001!==b.wrapT||1003!==b.minFilter&&1006!==b.minFilter)&&!1===k(t))if(r=t,r instanceof HTMLImageElement||r instanceof HTMLCanvasElement){var n=document.createElementNS("http://www.w3.org/1999/xhtml",
13659 "canvas");n.width=Y.nearestPowerOfTwo(r.width);n.height=Y.nearestPowerOfTwo(r.height);n.getContext("2d").drawImage(r,0,0,n.width,n.height);console.warn("THREE.WebGLRenderer: image is not power of two ("+r.width+"x"+r.height+"). Resized to "+n.width+"x"+n.height,r);t=n}else t=r;var r=k(t),n=f(b.format),y=f(b.type);l(a.TEXTURE_2D,b,r);var aa=b.mipmaps;if(b.isDepthTexture){aa=a.DEPTH_COMPONENT;if(1015===b.type){if(!x)throw Error("Float Depth Texture only supported in WebGL2.0");aa=a.DEPTH_COMPONENT32F}else x&&
13660 (aa=a.DEPTH_COMPONENT16);1026===b.format&&aa===a.DEPTH_COMPONENT&&1012!==b.type&&1014!==b.type&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),b.type=1012,y=f(b.type));1027===b.format&&(aa=a.DEPTH_STENCIL,1020!==b.type&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),b.type=1020,y=f(b.type)));c.texImage2D(a.TEXTURE_2D,0,aa,t.width,t.height,0,n,y,null)}else if(b.isDataTexture)if(0<aa.length&&
13661 r){for(var F=0,ja=aa.length;F<ja;F++)t=aa[F],c.texImage2D(a.TEXTURE_2D,F,n,t.width,t.height,0,n,y,t.data);b.generateMipmaps=!1}else c.texImage2D(a.TEXTURE_2D,0,n,t.width,t.height,0,n,y,t.data);else if(b.isCompressedTexture)for(F=0,ja=aa.length;F<ja;F++)t=aa[F],1023!==b.format&&1022!==b.format?-1<c.getCompressedTextureFormats().indexOf(n)?c.compressedTexImage2D(a.TEXTURE_2D,F,n,t.width,t.height,0,t.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):
13662 c.texImage2D(a.TEXTURE_2D,F,n,t.width,t.height,0,n,y,t.data);else if(0<aa.length&&r){F=0;for(ja=aa.length;F<ja;F++)t=aa[F],c.texImage2D(a.TEXTURE_2D,F,n,n,y,t);b.generateMipmaps=!1}else c.texImage2D(a.TEXTURE_2D,0,n,n,y,t);m(b,r)&&a.generateMipmap(a.TEXTURE_2D);q.__version=b.version;if(b.onUpdate)b.onUpdate(b);return}}c.activeTexture(a.TEXTURE0+p);c.bindTexture(a.TEXTURE_2D,q.__webglTexture)}function l(c,g,h){h?(a.texParameteri(c,a.TEXTURE_WRAP_S,f(g.wrapS)),a.texParameteri(c,a.TEXTURE_WRAP_T,f(g.wrapT)),
13663 a.texParameteri(c,a.TEXTURE_MAG_FILTER,f(g.magFilter)),a.texParameteri(c,a.TEXTURE_MIN_FILTER,f(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,a.TEXTURE_MIN_FILTER,q(g.minFilter)),
13664 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,e.getMaxAnisotropy())),d.get(g).__currentAnisotropy=
13665 g.anisotropy)}function t(b,e,g,h){var k=f(e.texture.format),m=f(e.texture.type);c.texImage2D(h,0,k,e.width,e.height,0,k,m,null);a.bindFramebuffer(a.FRAMEBUFFER,b);a.framebufferTexture2D(a.FRAMEBUFFER,g,h,d.get(e.texture).__webglTexture,0);a.bindFramebuffer(a.FRAMEBUFFER,null)}function n(b,c){a.bindRenderbuffer(a.RENDERBUFFER,b);c.depthBuffer&&!c.stencilBuffer?(a.renderbufferStorage(a.RENDERBUFFER,a.DEPTH_COMPONENT16,c.width,c.height),a.framebufferRenderbuffer(a.FRAMEBUFFER,a.DEPTH_ATTACHMENT,a.RENDERBUFFER,
13666 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 WebGL2RenderingContext;this.setTexture2D=r;this.setTextureCube=function(b,p){var q=d.get(b);if(6===b.image.length)if(0<b.version&&q.__version!==
13667 b.version){q.__image__webglTextureCube||(b.addEventListener("dispose",v),q.__image__webglTextureCube=a.createTexture(),g.textures++);c.activeTexture(a.TEXTURE0+p);c.bindTexture(a.TEXTURE_CUBE_MAP,q.__image__webglTextureCube);a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,b.flipY);for(var r=b&&b.isCompressedTexture,t=b.image[0]&&b.image[0].isDataTexture,n=[],y=0;6>y;y++)n[y]=r||t?t?b.image[y].image:b.image[y]:h(b.image[y],e.maxCubemapSize);var x=k(n[0]),F=f(b.format),ja=f(b.type);l(a.TEXTURE_CUBE_MAP,b,x);for(y=
13668 0;6>y;y++)if(r)for(var T,C=n[y].mipmaps,z=0,B=C.length;z<B;z++)T=C[z],1023!==b.format&&1022!==b.format?-1<c.getCompressedTextureFormats().indexOf(F)?c.compressedTexImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+y,z,F,T.width,T.height,0,T.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+y,z,F,T.width,T.height,0,F,ja,T.data);else t?c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+y,0,F,n[y].width,n[y].height,
13669 0,F,ja,n[y].data):c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+y,0,F,F,ja,n[y]);m(b,x)&&a.generateMipmap(a.TEXTURE_CUBE_MAP);q.__version=b.version;if(b.onUpdate)b.onUpdate(b)}else c.activeTexture(a.TEXTURE0+p),c.bindTexture(a.TEXTURE_CUBE_MAP,q.__image__webglTextureCube)};this.setTextureCubeDynamic=function(b,e){c.activeTexture(a.TEXTURE0+e);c.bindTexture(a.TEXTURE_CUBE_MAP,d.get(b).__webglTexture)};this.setupRenderTarget=function(b){var e=d.get(b),f=d.get(b.texture);b.addEventListener("dispose",p);
13670 f.__webglTexture=a.createTexture();g.textures++;var h=!0===b.isWebGLRenderTargetCube,q=k(b);if(h){e.__webglFramebuffer=[];for(var v=0;6>v;v++)e.__webglFramebuffer[v]=a.createFramebuffer()}else e.__webglFramebuffer=a.createFramebuffer();if(h){c.bindTexture(a.TEXTURE_CUBE_MAP,f.__webglTexture);l(a.TEXTURE_CUBE_MAP,b.texture,q);for(v=0;6>v;v++)t(e.__webglFramebuffer[v],b,a.COLOR_ATTACHMENT0,a.TEXTURE_CUBE_MAP_POSITIVE_X+v);m(b.texture,q)&&a.generateMipmap(a.TEXTURE_CUBE_MAP);c.bindTexture(a.TEXTURE_CUBE_MAP,
13671 null)}else c.bindTexture(a.TEXTURE_2D,f.__webglTexture),l(a.TEXTURE_2D,b.texture,q),t(e.__webglFramebuffer,b,a.COLOR_ATTACHMENT0,a.TEXTURE_2D),m(b.texture,q)&&a.generateMipmap(a.TEXTURE_2D),c.bindTexture(a.TEXTURE_2D,null);if(b.depthBuffer){e=d.get(b);f=!0===b.isWebGLRenderTargetCube;if(b.depthTexture){if(f)throw Error("target.depthTexture not supported in Cube render targets");if(b&&b.isWebGLRenderTargetCube)throw Error("Depth Texture with cube render targets is not supported!");a.bindFramebuffer(a.FRAMEBUFFER,
13672 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,
13673 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(),n(e.__webglDepthbuffer[f],b);else a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer),e.__webglDepthbuffer=a.createRenderbuffer(),n(e.__webglDepthbuffer,
13674 b);a.bindFramebuffer(a.FRAMEBUFFER,null)}};this.updateRenderTargetMipmap=function(b){var e=b.texture,f=k(b);m(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 eg(){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 fg(a,b,c){function d(b,c,d){var e=new Uint8Array(4),f=a.createTexture();
13675 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!==u[b]&&(a.enable(b),u[b]=!0)}function f(b){!1!==u[b]&&(a.disable(b),u[b]=!1)}function g(b,d,g,h,k,m,p,q){0!==b?e(a.BLEND):f(a.BLEND);5===b||b===w&&q===ja||(2===b?q?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ONE,a.ONE,a.ONE,a.ONE)):(a.blendEquation(a.FUNC_ADD),
13676 a.blendFunc(a.SRC_ALPHA,a.ONE)):3===b?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)):4===b?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)):q?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ONE,a.ONE_MINUS_SRC_ALPHA,
13677 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)),w=b,ja=q);if(5===b){k=k||d;m=m||g;p=p||h;if(d!==I||k!==O)a.blendEquationSeparate(c(d),c(k)),I=d,O=k;if(g!==W||h!==D||m!==aa||p!==F)a.blendFuncSeparate(c(g),c(h),c(m),c(p)),W=g,D=h,aa=m,F=p}else F=aa=O=D=W=I=null}function h(b){T!==b&&(b?a.frontFace(a.CW):a.frontFace(a.CCW),T=b)}function k(b){0!==b?(e(a.CULL_FACE),b!==C&&(1===b?a.cullFace(a.BACK):
13678 2===b?a.cullFace(a.FRONT):a.cullFace(a.FRONT_AND_BACK))):f(a.CULL_FACE);C=b}function m(b,c,d){if(b){if(e(a.POLYGON_OFFSET_FILL),B!==c||P!==d)a.polygonOffset(c,d),B=c,P=d}else f(a.POLYGON_OFFSET_FILL)}function q(b){void 0===b&&(b=a.TEXTURE0+V-1);S!==b&&(a.activeTexture(b),S=b)}var v=new function(){var b=!1,c=new fa,d=null,e=new fa;return{setMask:function(c){d===c||b||(a.colorMask(c,c,c,c),d=c)},setLocked:function(a){b=a},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)&&
13679 (a.clearColor(b,d,f,g),e.copy(c))},reset:function(){b=!1;d=null;e.set(0,0,0,1)}}},p=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);break;case 4:a.depthFunc(a.EQUAL);break;case 5:a.depthFunc(a.GEQUAL);break;case 6:a.depthFunc(a.GREATER);
13680 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,k=null,m=null,p=null,q=null;return{setTest:function(b){b?e(a.STENCIL_TEST):f(a.STENCIL_TEST)},setMask:function(d){c===d||b||(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},
13681 setOp:function(b,c,d){if(k!==b||m!==c||p!==d)a.stencilOp(b,c,d),k=b,m=c,p=d},setLocked:function(a){b=a},setClear:function(b){q!==b&&(a.clearStencil(b),q=b)},reset:function(){b=!1;q=p=m=k=h=g=d=c=null}}},l=a.getParameter(a.MAX_VERTEX_ATTRIBS),t=new Uint8Array(l),n=new Uint8Array(l),x=new Uint8Array(l),u={},H=null,w=null,I=null,W=null,D=null,O=null,aa=null,F=null,ja=!1,T=null,C=null,z=null,B=null,P=null,M=null,V=a.getParameter(a.MAX_COMBINED_TEXTURE_IMAGE_UNITS),l=parseFloat(/^WebGL\ ([0-9])/.exec(a.getParameter(a.VERSION))[1]),
13682 pa=1<=parseFloat(l),S=null,N={},E=new fa,G=new fa,K={};K[a.TEXTURE_2D]=d(a.TEXTURE_2D,a.TEXTURE_2D,1);K[a.TEXTURE_CUBE_MAP]=d(a.TEXTURE_CUBE_MAP,a.TEXTURE_CUBE_MAP_POSITIVE_X,6);return{buffers:{color:v,depth:p,stencil:r},init:function(){v.setClear(0,0,0,1);p.setClear(1);r.setClear(0);e(a.DEPTH_TEST);p.setFunc(3);h(!1);k(1);e(a.CULL_FACE);e(a.BLEND);g(1)},initAttributes:function(){for(var a=0,b=t.length;a<b;a++)t[a]=0},enableAttribute:function(c){t[c]=1;0===n[c]&&(a.enableVertexAttribArray(c),n[c]=
13683 1);0!==x[c]&&(b.get("ANGLE_instanced_arrays").vertexAttribDivisorANGLE(c,0),x[c]=0)},enableAttributeAndDivisor:function(c,d){t[c]=1;0===n[c]&&(a.enableVertexAttribArray(c),n[c]=1);x[c]!==d&&(b.get("ANGLE_instanced_arrays").vertexAttribDivisorANGLE(c,d),x[c]=d)},disableUnusedAttributes:function(){for(var b=0,c=n.length;b!==c;++b)n[b]!==t[b]&&(a.disableVertexAttribArray(b),n[b]=0)},enable:e,disable:f,getCompressedTextureFormats:function(){if(null===H&&(H=[],b.get("WEBGL_compressed_texture_pvrtc")||
13684 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++)H.push(c[d]);return H},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,b.blendDst,b.blendEquationAlpha,b.blendSrcAlpha,b.blendDstAlpha,b.premultipliedAlpha):g(0);p.setFunc(b.depthFunc);p.setTest(b.depthTest);p.setMask(b.depthWrite);v.setMask(b.colorWrite);
13685 m(b.polygonOffset,b.polygonOffsetFactor,b.polygonOffsetUnits)},setFlipSided:h,setCullFace:k,setLineWidth:function(b){b!==z&&(pa&&a.lineWidth(b),z=b)},setPolygonOffset:m,getScissorTest:function(){return M},setScissorTest:function(b){(M=b)?e(a.SCISSOR_TEST):f(a.SCISSOR_TEST)},activeTexture:q,bindTexture:function(b,c){null===S&&q();var d=N[S];void 0===d&&(d={type:void 0,texture:void 0},N[S]=d);if(d.type!==b||d.texture!==c)a.bindTexture(b,c||K[b]),d.type=b,d.texture=c},compressedTexImage2D:function(){try{a.compressedTexImage2D.apply(a,
13686 arguments)}catch(b){console.error("THREE.WebGLState:",b)}},texImage2D:function(){try{a.texImage2D.apply(a,arguments)}catch(b){console.error("THREE.WebGLState:",b)}},scissor:function(b){!1===E.equals(b)&&(a.scissor(b.x,b.y,b.z,b.w),E.copy(b))},viewport:function(b){!1===G.equals(b)&&(a.viewport(b.x,b.y,b.z,b.w),G.copy(b))},reset:function(){for(var b=0;b<n.length;b++)1===n[b]&&(a.disableVertexAttribArray(b),n[b]=0);u={};S=H=null;N={};C=T=w=null;v.reset();p.reset();r.reset()}}}function gg(a,b,c){function d(b){if("highp"===
13687 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,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=
13688 !0===c.logarithmicDepthBuffer&&!!b.get("EXT_frag_depth");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),m=a.getParameter(a.MAX_CUBE_MAP_TEXTURE_SIZE),q=a.getParameter(a.MAX_VERTEX_ATTRIBS),v=a.getParameter(a.MAX_VERTEX_UNIFORM_VECTORS),p=a.getParameter(a.MAX_VARYING_VECTORS),r=a.getParameter(a.MAX_FRAGMENT_UNIFORM_VECTORS),l=0<h,t=!!b.get("OES_texture_float");return{getMaxAnisotropy:function(){if(void 0!==e)return e;
13689 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:m,maxAttributes:q,maxVertexUniforms:v,maxVaryings:p,maxFragmentUniforms:r,vertexTextures:l,floatFragmentTextures:t,floatVertexTextures:l&&t}}function kd(a){qa.call(this);this.cameras=a||[]}function hg(a){var b=this,c=null,d=null;"VRFrameData"in window&&(d=new window.VRFrameData);
13690 var e=new K,f=new K,g=new K,h=new qa;h.bounds=new fa(0,0,.5,1);h.layers.enable(1);var k=new qa;k.bounds=new fa(.5,0,.5,1);k.layers.enable(2);var m=new kd([h,k]);m.layers.enable(1);m.layers.enable(2);var q,v;window.addEventListener("vrdisplaypresentchange",function(){if(c.isPresenting){var d=c.getEyeParameters("left"),e=d.renderWidth,d=d.renderHeight;v=a.getPixelRatio();q=a.getSize();a.setDrawingBufferSize(2*e,d,1)}else b.enabled&&a.setDrawingBufferSize(q.width,q.height,v)},!1);this.standing=this.enabled=
13691 !1;this.getDevice=function(){return c};this.setDevice=function(a){void 0!==a&&(c=a)};this.getCamera=function(a){if(null===c)return a;c.depthNear=a.near;c.depthFar=a.far;c.getFrameData(d);var b=d.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=c.stageParameters;this.standing&&b&&(f.fromArray(b.sittingToStandingTransform),g.getInverse(f),a.matrixWorld.multiply(f),a.matrixWorldInverse.multiply(g));
13692 if(!1===c.isPresenting)return a;m.matrixWorld.copy(a.matrixWorld);m.matrixWorldInverse.copy(a.matrixWorldInverse);h.matrixWorldInverse.fromArray(d.leftViewMatrix);k.matrixWorldInverse.fromArray(d.rightViewMatrix);this.standing&&b&&(h.matrixWorldInverse.multiply(g),k.matrixWorldInverse.multiply(g));a=a.parent;null!==a&&(e.getInverse(a.matrixWorld),h.matrixWorldInverse.multiply(e),k.matrixWorldInverse.multiply(e));h.matrixWorld.getInverse(h.matrixWorldInverse);k.matrixWorld.getInverse(k.matrixWorldInverse);
13693 h.projectionMatrix.fromArray(d.leftProjectionMatrix);k.projectionMatrix.fromArray(d.rightProjectionMatrix);m.projectionMatrix.copy(h.projectionMatrix);a=c.getLayers();a.length&&(a=a[0],null!==a.leftBounds&&4===a.leftBounds.length&&h.bounds.fromArray(a.leftBounds),null!==a.rightBounds&&4===a.rightBounds.length&&k.bounds.fromArray(a.rightBounds));return m};this.getStandingMatrix=function(){return f};this.submitFrame=function(){c&&c.isPresenting&&c.submitFrame()}}function ig(a){var b={};return{get:function(c){if(void 0!==
13694 b[c])return b[c];var d;switch(c){case "WEBGL_depth_texture":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")||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")||
13695 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");break;default:d=a.getExtension(c)}null===d&&console.warn("THREE.WebGLRenderer: "+c+" extension not supported.");return b[c]=d}}}function jg(){function a(){m.value!==d&&(m.value=d,m.needsUpdate=0<e);c.numPlanes=
13696 e;c.numIntersection=0}function b(a,b,d,e){var f=null!==a?a.length:0,g=null;if(0!==f){g=m.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+3]=h.constant}m.value=g;m.needsUpdate=!0}c.numPlanes=f;return g}var c=this,d=null,e=0,f=!1,g=!1,h=new Aa,k=new Ba,m={value:null,needsUpdate:!1};this.uniform=m;this.numIntersection=this.numPlanes=0;this.init=
13697 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,l,t){if(!f||null===c||0===c.length||g&&!k)g?b(null):a();else{k=g?0:e;var n=4*k,x=l.clippingState||null;m.value=x;x=b(c,r,n,t);for(c=0;c!==n;++c)x[c]=d[c];l.clippingState=x;this.numIntersection=h?this.numPlanes:0;this.numPlanes+=k}}}function Xd(a){function b(){ga.init();ga.scissor(J.copy(ea).multiplyScalar(Q));
13698 ga.viewport(U.copy(hd).multiplyScalar(Q))}function c(){S=G=null;pa="";V=-1;ga.reset()}function d(a){a.preventDefault();c();b();ha.clear();xa.clear()}function e(a){a=a.target;a.removeEventListener("dispose",e);f(a);ha.remove(a)}function f(a){var b=ha.get(a).program;a.program=void 0;void 0!==b&&va.releaseProgram(b)}function g(a,b,c){a.render(function(a){B.renderBufferImmediate(a,b,c)})}function h(a,b){return Math.abs(b[0])-Math.abs(a[0])}function k(a,b,c){if(a.visible){if(a.layers.test(b.layers))if(a.isLight)aa.push(a);
13699 else if(a.isSprite)a.frustumCulled&&!Vd.intersectsSprite(a)||C.push(a);else if(a.isLensFlare)z.push(a);else if(a.isImmediateRenderObject)c&&Oa.setFromMatrixPosition(a.matrixWorld).applyMatrix4(jd),F.push(a,null,a.material,Oa.z,null);else if(a.isMesh||a.isLine||a.isPoints)if(a.isSkinnedMesh&&a.skeleton.update(),!a.frustumCulled||Vd.intersectsObject(a)){c&&Oa.setFromMatrixPosition(a.matrixWorld).applyMatrix4(jd);var d=xa.update(a),e=a.material;if(Array.isArray(e))for(var f=d.groups,g=0,h=f.length;g<
13700 h;g++){var m=f[g],q=e[m.materialIndex];q&&q.visible&&F.push(a,d,q,Oa.z,m)}else e.visible&&F.push(a,d,e,Oa.z,null)}a=a.children;g=0;for(h=a.length;g<h;g++)k(a[g],b,c)}}function m(a,b,c,d){for(var e=0,f=a.length;e<f;e++){var g=a[e],h=g.object,k=g.geometry,m=void 0===d?g.material:d,g=g.group;if(c.isArrayCamera){N=c;for(var p=c.cameras,v=0,r=p.length;v<r;v++){var l=p[v];if(h.layers.test(l.layers)){var t=l.bounds,n=t.x*ba,ca=t.y*L,u=t.z*ba,t=t.w*L;B.setViewport(n,ca,u,t);B.setScissor(n,ca,u,t);B.setScissorTest(!0);
13701 q(h,b,l,k,m,g)}}}else N=null,q(h,b,c,k,m,g)}}function q(a,b,c,d,e,f){a.modelViewMatrix.multiplyMatrices(c.matrixWorldInverse,a.matrixWorld);a.normalMatrix.getNormalMatrix(a.modelViewMatrix);a.onBeforeRender(B,b,c,d,e,f);if(a.isImmediateRenderObject){ga.setMaterial(e);var h=p(c,b.fog,e,a);pa="";g(a,h,e)}else B.renderBufferDirect(c,b.fog,d,e,a,f);a.onAfterRender(B,b,c,d,e,f)}function v(a,b,c){var d=ha.get(a);c=va.getParameters(a,da,b,Ha.numPlanes,Ha.numIntersection,c);var g=va.getProgramCode(a,c),h=
13702 d.program,k=!0;if(void 0===h)a.addEventListener("dispose",e);else if(h.code!==g)f(a);else{if(void 0!==c.shaderID)return;k=!1}k&&(c.shaderID?(h=$a[c.shaderID],d.shader={name:a.type,uniforms:Ca.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=va.acquireProgram(a,d.shader,c,g),d.program=h,a.program=h);c=h.getAttributes();if(a.morphTargets)for(g=
13703 a.numSupportedMorphTargets=0;g<B.maxMorphTargets;g++)0<=c["morphTarget"+g]&&a.numSupportedMorphTargets++;if(a.morphNormals)for(g=a.numSupportedMorphNormals=0;g<B.maxMorphNormals;g++)0<=c["morphNormal"+g]&&a.numSupportedMorphNormals++;c=d.shader.uniforms;if(!a.isShaderMaterial&&!a.isRawShaderMaterial||!0===a.clipping)d.numClippingPlanes=Ha.numPlanes,d.numIntersection=Ha.numIntersection,c.clippingPlanes=Ha.uniform;d.fog=b;d.lightsHash=da.hash;a.lights&&(c.ambientLightColor.value=da.ambient,c.directionalLights.value=
13704 da.directional,c.spotLights.value=da.spot,c.rectAreaLights.value=da.rectArea,c.pointLights.value=da.point,c.hemisphereLights.value=da.hemi,c.directionalShadowMap.value=da.directionalShadowMap,c.directionalShadowMatrix.value=da.directionalShadowMatrix,c.spotShadowMap.value=da.spotShadowMap,c.spotShadowMatrix.value=da.spotShadowMatrix,c.pointShadowMap.value=da.pointShadowMap,c.pointShadowMatrix.value=da.pointShadowMatrix);a=d.program.getUniforms();a=eb.seqWithValue(a.seq,c);d.uniformsList=a}function p(a,
13705 b,c,d){X=0;var e=ha.get(c);id&&(Wd||a!==S)&&Ha.setState(c.clippingPlanes,c.clipIntersection,c.clipShadows,a,e,a===S&&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!==da.hash?c.needsUpdate=!0:void 0===e.numClippingPlanes||e.numClippingPlanes===Ha.numPlanes&&e.numIntersection===Ha.numIntersection||(c.needsUpdate=!0));c.needsUpdate&&(v(c,b,d),c.needsUpdate=!1);var f=!1,g=!1,h=!1,k=e.program,m=k.getUniforms(),q=e.shader.uniforms;
13706 k.id!==G&&(A.useProgram(k.program),G=k.id,h=g=f=!0);c.id!==V&&(V=c.id,g=!0);if(f||a!==S){m.setValue(A,"projectionMatrix",a.projectionMatrix);ia.logarithmicDepthBuffer&&m.setValue(A,"logDepthBufFC",2/(Math.log(a.far+1)/Math.LN2));S!==(N||a)&&(S=N||a,h=g=!0);if(c.isShaderMaterial||c.isMeshPhongMaterial||c.isMeshStandardMaterial||c.envMap)f=m.map.cameraPosition,void 0!==f&&f.setValue(A,Oa.setFromMatrixPosition(a.matrixWorld));(c.isMeshPhongMaterial||c.isMeshLambertMaterial||c.isMeshBasicMaterial||c.isMeshStandardMaterial||
13707 c.isShaderMaterial||c.skinning)&&m.setValue(A,"viewMatrix",a.matrixWorldInverse)}if(c.skinning&&(m.setOptional(A,d,"bindMatrix"),m.setOptional(A,d,"bindMatrixInverse"),a=d.skeleton))if(f=a.bones,ia.floatVertexTextures){if(void 0===a.boneTexture){var f=Math.sqrt(4*f.length),f=Y.nextPowerOfTwo(Math.ceil(f)),f=Math.max(f,4),p=new Float32Array(f*f*4);p.set(a.boneMatrices);var t=new db(p,f,f,1023,1015);a.boneMatrices=p;a.boneTexture=t;a.boneTextureSize=f}m.setValue(A,"boneTexture",a.boneTexture);m.setValue(A,
13708 "boneTextureSize",a.boneTextureSize)}else m.setOptional(A,a,"boneMatrices");if(g){m.setValue(A,"toneMappingExposure",B.toneMappingExposure);m.setValue(A,"toneMappingWhitePoint",B.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&&
13709 (q.fogDensity.value=b.density));if(c.isMeshBasicMaterial||c.isMeshLambertMaterial||c.isMeshPhongMaterial||c.isMeshStandardMaterial||c.isMeshNormalMaterial||c.isMeshDepthMaterial){q.opacity.value=c.opacity;q.diffuse.value=c.color;c.emissive&&q.emissive.value.copy(c.emissive).multiplyScalar(c.emissiveIntensity);q.map.value=c.map;q.specularMap.value=c.specularMap;q.alphaMap.value=c.alphaMap;c.lightMap&&(q.lightMap.value=c.lightMap,q.lightMapIntensity.value=c.lightMapIntensity);c.aoMap&&(q.aoMap.value=
13710 c.aoMap,q.aoMapIntensity.value=c.aoMapIntensity);var n;c.map?n=c.map:c.specularMap?n=c.specularMap:c.displacementMap?n=c.displacementMap:c.normalMap?n=c.normalMap:c.bumpMap?n=c.bumpMap:c.roughnessMap?n=c.roughnessMap:c.metalnessMap?n=c.metalnessMap:c.alphaMap?n=c.alphaMap:c.emissiveMap&&(n=c.emissiveMap);void 0!==n&&(n.isWebGLRenderTarget&&(n=n.texture),b=n.offset,n=n.repeat,q.offsetRepeat.value.set(b.x,b.y,n.x,n.y));q.envMap.value=c.envMap;q.flipEnvMap.value=c.envMap&&c.envMap.isCubeTexture?-1:1;
13711 q.reflectivity.value=c.reflectivity;q.refractionRatio.value=c.refractionRatio}c.isLineBasicMaterial?(q.diffuse.value=c.color,q.opacity.value=c.opacity):c.isLineDashedMaterial?(q.diffuse.value=c.color,q.opacity.value=c.opacity,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*Q,q.scale.value=.5*L,q.map.value=c.map,null!==c.map&&(n=c.map.offset,c=c.map.repeat,q.offsetRepeat.value.set(n.x,
13712 n.y,c.x,c.y))):c.isMeshLambertMaterial?c.emissiveMap&&(q.emissiveMap.value=c.emissiveMap):c.isMeshToonMaterial?(r(q,c),c.gradientMap&&(q.gradientMap.value=c.gradientMap)):c.isMeshPhongMaterial?r(q,c):c.isMeshPhysicalMaterial?(q.clearCoat.value=c.clearCoat,q.clearCoatRoughness.value=c.clearCoatRoughness,l(q,c)):c.isMeshStandardMaterial?l(q,c):c.isMeshDepthMaterial?c.displacementMap&&(q.displacementMap.value=c.displacementMap,q.displacementScale.value=c.displacementScale,q.displacementBias.value=c.displacementBias):
13713 c.isMeshNormalMaterial&&(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));void 0!==q.ltcMat&&(q.ltcMat.value=R.LTC_MAT_TEXTURE);void 0!==q.ltcMag&&(q.ltcMag.value=R.LTC_MAG_TEXTURE);eb.upload(A,e.uniformsList,q,B)}m.setValue(A,"modelViewMatrix",
13714 d.modelViewMatrix);m.setValue(A,"normalMatrix",d.normalMatrix);m.setValue(A,"modelMatrix",d.matrixWorld);return k}function r(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=b.displacementScale,
13715 a.displacementBias.value=b.displacementBias)}function l(a,b){a.roughness.value=b.roughness;a.metalness.value=b.metalness;b.roughnessMap&&(a.roughnessMap.value=b.roughnessMap);b.metalnessMap&&(a.metalnessMap.value=b.metalnessMap);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=
13716 b.displacementScale,a.displacementBias.value=b.displacementBias);b.envMap&&(a.envMapIntensity.value=b.envMapIntensity)}function t(a,b){var c,d,e,f,g=0,h=0,k=0,m,q,p,v=b.matrixWorldInverse,r=0,l=0,n=0,t=0,ca=0;c=0;for(d=a.length;c<d;c++)if(e=a[c],f=e.color,m=e.intensity,q=e.distance,p=e.shadow&&e.shadow.map?e.shadow.map.texture:null,e.isAmbientLight)g+=f.r*m,h+=f.g*m,k+=f.b*m;else if(e.isDirectionalLight){var u=wa.get(e);u.color.copy(e.color).multiplyScalar(e.intensity);u.direction.setFromMatrixPosition(e.matrixWorld);
13717 Oa.setFromMatrixPosition(e.target.matrixWorld);u.direction.sub(Oa);u.direction.transformDirection(v);if(u.shadow=e.castShadow)f=e.shadow,u.shadowBias=f.bias,u.shadowRadius=f.radius,u.shadowMapSize=f.mapSize;da.directionalShadowMap[r]=p;da.directionalShadowMatrix[r]=e.shadow.matrix;da.directional[r]=u;r++}else if(e.isSpotLight){u=wa.get(e);u.position.setFromMatrixPosition(e.matrixWorld);u.position.applyMatrix4(v);u.color.copy(f).multiplyScalar(m);u.distance=q;u.direction.setFromMatrixPosition(e.matrixWorld);
13718 Oa.setFromMatrixPosition(e.target.matrixWorld);u.direction.sub(Oa);u.direction.transformDirection(v);u.coneCos=Math.cos(e.angle);u.penumbraCos=Math.cos(e.angle*(1-e.penumbra));u.decay=0===e.distance?0:e.decay;if(u.shadow=e.castShadow)f=e.shadow,u.shadowBias=f.bias,u.shadowRadius=f.radius,u.shadowMapSize=f.mapSize;da.spotShadowMap[n]=p;da.spotShadowMatrix[n]=e.shadow.matrix;da.spot[n]=u;n++}else if(e.isRectAreaLight)u=wa.get(e),u.color.copy(f).multiplyScalar(m/(e.width*e.height)),u.position.setFromMatrixPosition(e.matrixWorld),
13719 u.position.applyMatrix4(v),oa.identity(),qa.copy(e.matrixWorld),qa.premultiply(v),oa.extractRotation(qa),u.halfWidth.set(.5*e.width,0,0),u.halfHeight.set(0,.5*e.height,0),u.halfWidth.applyMatrix4(oa),u.halfHeight.applyMatrix4(oa),da.rectArea[t]=u,t++;else if(e.isPointLight){u=wa.get(e);u.position.setFromMatrixPosition(e.matrixWorld);u.position.applyMatrix4(v);u.color.copy(e.color).multiplyScalar(e.intensity);u.distance=e.distance;u.decay=0===e.distance?0:e.decay;if(u.shadow=e.castShadow)f=e.shadow,
13720 u.shadowBias=f.bias,u.shadowRadius=f.radius,u.shadowMapSize=f.mapSize;da.pointShadowMap[l]=p;da.pointShadowMatrix[l]=e.shadow.matrix;da.point[l]=u;l++}else e.isHemisphereLight&&(u=wa.get(e),u.direction.setFromMatrixPosition(e.matrixWorld),u.direction.transformDirection(v),u.direction.normalize(),u.skyColor.copy(e.color).multiplyScalar(m),u.groundColor.copy(e.groundColor).multiplyScalar(m),da.hemi[ca]=u,ca++);da.ambient[0]=g;da.ambient[1]=h;da.ambient[2]=k;da.directional.length=r;da.spot.length=n;
13721 da.rectArea.length=t;da.point.length=l;da.hemi.length=ca;da.hash=r+","+l+","+n+","+t+","+ca+","+da.shadows.length}function y(a){var b;if(1E3===a)return A.REPEAT;if(1001===a)return A.CLAMP_TO_EDGE;if(1002===a)return A.MIRRORED_REPEAT;if(1003===a)return A.NEAREST;if(1004===a)return A.NEAREST_MIPMAP_NEAREST;if(1005===a)return A.NEAREST_MIPMAP_LINEAR;if(1006===a)return A.LINEAR;if(1007===a)return A.LINEAR_MIPMAP_NEAREST;if(1008===a)return A.LINEAR_MIPMAP_LINEAR;if(1009===a)return A.UNSIGNED_BYTE;if(1017===
13722 a)return A.UNSIGNED_SHORT_4_4_4_4;if(1018===a)return A.UNSIGNED_SHORT_5_5_5_1;if(1019===a)return A.UNSIGNED_SHORT_5_6_5;if(1010===a)return A.BYTE;if(1011===a)return A.SHORT;if(1012===a)return A.UNSIGNED_SHORT;if(1013===a)return A.INT;if(1014===a)return A.UNSIGNED_INT;if(1015===a)return A.FLOAT;if(1016===a&&(b=ma.get("OES_texture_half_float"),null!==b))return b.HALF_FLOAT_OES;if(1021===a)return A.ALPHA;if(1022===a)return A.RGB;if(1023===a)return A.RGBA;if(1024===a)return A.LUMINANCE;if(1025===a)return A.LUMINANCE_ALPHA;
13723 if(1026===a)return A.DEPTH_COMPONENT;if(1027===a)return A.DEPTH_STENCIL;if(100===a)return A.FUNC_ADD;if(101===a)return A.FUNC_SUBTRACT;if(102===a)return A.FUNC_REVERSE_SUBTRACT;if(200===a)return A.ZERO;if(201===a)return A.ONE;if(202===a)return A.SRC_COLOR;if(203===a)return A.ONE_MINUS_SRC_COLOR;if(204===a)return A.SRC_ALPHA;if(205===a)return A.ONE_MINUS_SRC_ALPHA;if(206===a)return A.DST_ALPHA;if(207===a)return A.ONE_MINUS_DST_ALPHA;if(208===a)return A.DST_COLOR;if(209===a)return A.ONE_MINUS_DST_COLOR;
13724 if(210===a)return A.SRC_ALPHA_SATURATE;if(2001===a||2002===a||2003===a||2004===a)if(b=ma.get("WEBGL_compressed_texture_s3tc"),null!==b){if(2001===a)return b.COMPRESSED_RGB_S3TC_DXT1_EXT;if(2002===a)return b.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(2003===a)return b.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(2004===a)return b.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(2100===a||2101===a||2102===a||2103===a)if(b=ma.get("WEBGL_compressed_texture_pvrtc"),null!==b){if(2100===a)return b.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(2101===a)return b.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
13725 if(2102===a)return b.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(2103===a)return b.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(2151===a&&(b=ma.get("WEBGL_compressed_texture_etc1"),null!==b))return b.COMPRESSED_RGB_ETC1_WEBGL;if(103===a||104===a)if(b=ma.get("EXT_blend_minmax"),null!==b){if(103===a)return b.MIN_EXT;if(104===a)return b.MAX_EXT}return 1020===a&&(b=ma.get("WEBGL_depth_texture"),null!==b)?b.UNSIGNED_INT_24_8_WEBGL:0}console.log("THREE.WebGLRenderer","86");a=a||{};var x=void 0!==a.canvas?a.canvas:document.createElementNS("http://www.w3.org/1999/xhtml",
13726 "canvas"),u=void 0!==a.context?a.context:null,H=void 0!==a.alpha?a.alpha:!1,w=void 0!==a.depth?a.depth:!0,I=void 0!==a.stencil?a.stencil:!0,W=void 0!==a.antialias?a.antialias:!1,D=void 0!==a.premultipliedAlpha?a.premultipliedAlpha:!0,O=void 0!==a.preserveDrawingBuffer?a.preserveDrawingBuffer:!1,aa=[],F=null,ja=new Float32Array(8),C=[],z=[];this.domElement=x;this.context=null;this.sortObjects=this.autoClearStencil=this.autoClearDepth=this.autoClearColor=this.autoClear=!0;this.clippingPlanes=[];this.localClippingEnabled=
13727 !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 B=this,G=null,P=null,M=null,V=-1,pa="",S=null,N=null,J=new fa,Z=null,U=new fa,X=0,ba=x.width,L=x.height,Q=1,ea=new fa(0,0,ba,L),na=!1,hd=new fa(0,0,ba,L),Vd=new gd,Ha=new jg,id=!1,Wd=!1,jd=new K,Oa=new n,qa=new K,oa=new K,da={hash:"",ambient:[0,0,0],directional:[],directionalShadowMap:[],directionalShadowMatrix:[],
13728 spot:[],spotShadowMap:[],spotShadowMatrix:[],rectArea:[],point:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],shadows:[]},ta={geometries:0,textures:0},la={frame:0,calls:0,vertices:0,faces:0,points:0};this.info={render:la,memory:ta,programs:null};var A;try{H={alpha:H,depth:w,stencil:I,antialias:W,premultipliedAlpha:D,preserveDrawingBuffer:O};A=u||x.getContext("webgl",H)||x.getContext("experimental-webgl",H);if(null===A){if(null!==x.getContext("webgl"))throw"Error creating WebGL context with your selected attributes.";
13729 throw"Error creating WebGL context.";}void 0===A.getShaderPrecisionFormat&&(A.getShaderPrecisionFormat=function(){return{rangeMin:1,rangeMax:1,precision:1}});x.addEventListener("webglcontextlost",d,!1)}catch(kg){console.error("THREE.WebGLRenderer: "+kg)}var ma=new ig(A);ma.get("WEBGL_depth_texture");ma.get("OES_texture_float");ma.get("OES_texture_float_linear");ma.get("OES_texture_half_float");ma.get("OES_texture_half_float_linear");ma.get("OES_standard_derivatives");ma.get("ANGLE_instanced_arrays");
13730 ma.get("OES_element_index_uint")&&(E.MaxIndex=4294967296);var ia=new gg(A,ma,a),ga=new fg(A,ma,y),ha=new eg,ra=new dg(A,ma,ga,ha,ia,y,ta),ua=new Kf(A),za=new Tf(A,ua,ta),xa=new Vf(A,za,la),va=new cg(this,ia),wa=new Uf,Aa=new Qf,ya=new Mf(this,ga,xa,D),sa=new hg(this);this.info.programs=va.programs;var Da=new Sf(A,ma,la),Ea=new Rf(A,ma,la);b();this.context=A;this.capabilities=ia;this.extensions=ma;this.properties=ha;this.renderLists=Aa;this.state=ga;this.vr=sa;var Ba=new Ie(this,da,xa,ia);this.shadowMap=
13731 Ba;var Fa=new If(this,C),Ga=new Hf(this,z);this.getContext=function(){return A};this.getContextAttributes=function(){return A.getContextAttributes()};this.forceContextLoss=function(){var a=ma.get("WEBGL_lose_context");a&&a.loseContext()};this.getMaxAnisotropy=function(){return ia.getMaxAnisotropy()};this.getPrecision=function(){return ia.precision};this.getPixelRatio=function(){return Q};this.setPixelRatio=function(a){void 0!==a&&(Q=a,this.setSize(ba,L,!1))};this.getSize=function(){return{width:ba,
13732 height:L}};this.setSize=function(a,b,c){var d=sa.getDevice();d&&d.isPresenting?console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting."):(ba=a,L=b,x.width=a*Q,x.height=b*Q,!1!==c&&(x.style.width=a+"px",x.style.height=b+"px"),this.setViewport(0,0,a,b))};this.getDrawingBufferSize=function(){return{width:ba*Q,height:L*Q}};this.setDrawingBufferSize=function(a,b,c){ba=a;L=b;Q=c;x.width=a*c;x.height=b*c;this.setViewport(0,0,a,b)};this.setViewport=function(a,b,c,d){hd.set(a,L-
13733 b-d,c,d);ga.viewport(U.copy(hd).multiplyScalar(Q))};this.setScissor=function(a,b,c,d){ea.set(a,L-b-d,c,d);ga.scissor(J.copy(ea).multiplyScalar(Q))};this.setScissorTest=function(a){ga.setScissorTest(na=a)};this.getClearColor=ya.getClearColor;this.setClearColor=ya.setClearColor;this.getClearAlpha=ya.getClearAlpha;this.setClearAlpha=ya.setClearAlpha;this.clear=function(a,b,c){var d=0;if(void 0===a||a)d|=A.COLOR_BUFFER_BIT;if(void 0===b||b)d|=A.DEPTH_BUFFER_BIT;if(void 0===c||c)d|=A.STENCIL_BUFFER_BIT;
13734 A.clear(d)};this.clearColor=function(){this.clear(!0,!1,!1)};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.resetGLState=c;this.dispose=function(){x.removeEventListener("webglcontextlost",d,!1);Aa.dispose()};this.renderBufferImmediate=function(a,b,c){ga.initAttributes();var d=ha.get(a);a.hasPositions&&!d.position&&(d.position=A.createBuffer());a.hasNormals&&!d.normal&&
13735 (d.normal=A.createBuffer());a.hasUvs&&!d.uv&&(d.uv=A.createBuffer());a.hasColors&&!d.color&&(d.color=A.createBuffer());b=b.getAttributes();a.hasPositions&&(A.bindBuffer(A.ARRAY_BUFFER,d.position),A.bufferData(A.ARRAY_BUFFER,a.positionArray,A.DYNAMIC_DRAW),ga.enableAttribute(b.position),A.vertexAttribPointer(b.position,3,A.FLOAT,!1,0,0));if(a.hasNormals){A.bindBuffer(A.ARRAY_BUFFER,d.normal);if(!c.isMeshPhongMaterial&&!c.isMeshStandardMaterial&&!c.isMeshNormalMaterial&&1===c.shading)for(var e=0,f=
13736 3*a.count;e<f;e+=9){var g=a.normalArray,h=(g[e+0]+g[e+3]+g[e+6])/3,k=(g[e+1]+g[e+4]+g[e+7])/3,m=(g[e+2]+g[e+5]+g[e+8])/3;g[e+0]=h;g[e+1]=k;g[e+2]=m;g[e+3]=h;g[e+4]=k;g[e+5]=m;g[e+6]=h;g[e+7]=k;g[e+8]=m}A.bufferData(A.ARRAY_BUFFER,a.normalArray,A.DYNAMIC_DRAW);ga.enableAttribute(b.normal);A.vertexAttribPointer(b.normal,3,A.FLOAT,!1,0,0)}a.hasUvs&&c.map&&(A.bindBuffer(A.ARRAY_BUFFER,d.uv),A.bufferData(A.ARRAY_BUFFER,a.uvArray,A.DYNAMIC_DRAW),ga.enableAttribute(b.uv),A.vertexAttribPointer(ua.uv,2,A.FLOAT,
13737 !1,0,0));a.hasColors&&0!==c.vertexColors&&(A.bindBuffer(A.ARRAY_BUFFER,d.color),A.bufferData(A.ARRAY_BUFFER,a.colorArray,A.DYNAMIC_DRAW),ga.enableAttribute(b.color),A.vertexAttribPointer(b.color,3,A.FLOAT,!1,0,0));ga.disableUnusedAttributes();A.drawArrays(A.TRIANGLES,0,a.count);a.count=0};this.renderBufferDirect=function(a,b,c,d,e,f){ga.setMaterial(d);var g=p(a,b,d,e);a=c.id+"_"+g.id+"_"+(!0===d.wireframe);var k=!1;a!==pa&&(pa=a,k=!0);b=e.morphTargetInfluences;if(void 0!==b){var m=[];a=0;for(var q=
13738 b.length;a<q;a++)k=b[a],m.push([k,a]);m.sort(h);8<m.length&&(m.length=8);var v=c.morphAttributes;a=0;for(q=m.length;a<q;a++)k=m[a],ja[a]=k[0],0!==k[0]?(b=k[1],!0===d.morphTargets&&v.position&&c.addAttribute("morphTarget"+a,v.position[b]),!0===d.morphNormals&&v.normal&&c.addAttribute("morphNormal"+a,v.normal[b])):(!0===d.morphTargets&&c.removeAttribute("morphTarget"+a),!0===d.morphNormals&&c.removeAttribute("morphNormal"+a));a=m.length;for(b=ja.length;a<b;a++)ja[a]=0;g.getUniforms().setValue(A,"morphTargetInfluences",
13739 ja);k=!0}b=c.index;q=c.attributes.position;m=1;!0===d.wireframe&&(b=za.getWireframeAttribute(c),m=2);var r;a=Da;null!==b&&(r=ua.get(b),a=Ea,a.setIndex(r));if(k){k=void 0;if(c&&c.isInstancedBufferGeometry&&null===ma.get("ANGLE_instanced_arrays"))console.error("THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");else{void 0===k&&(k=0);ga.initAttributes();var v=c.attributes,g=g.getAttributes(),l=d.defaultAttributeValues,
13740 n;for(n in g){var t=g[n];if(0<=t){var u=v[n];if(void 0!==u){var ca=u.normalized,w=u.itemSize,x=ua.get(u),y=x.buffer,H=x.type,x=x.bytesPerElement;if(u.isInterleavedBufferAttribute){var I=u.data,D=I.stride,u=u.offset;I&&I.isInstancedInterleavedBuffer?(ga.enableAttributeAndDivisor(t,I.meshPerAttribute),void 0===c.maxInstancedCount&&(c.maxInstancedCount=I.meshPerAttribute*I.count)):ga.enableAttribute(t);A.bindBuffer(A.ARRAY_BUFFER,y);A.vertexAttribPointer(t,w,H,ca,D*x,(k*D+u)*x)}else u.isInstancedBufferAttribute?
13741 (ga.enableAttributeAndDivisor(t,u.meshPerAttribute),void 0===c.maxInstancedCount&&(c.maxInstancedCount=u.meshPerAttribute*u.count)):ga.enableAttribute(t),A.bindBuffer(A.ARRAY_BUFFER,y),A.vertexAttribPointer(t,w,H,ca,0,k*w*x)}else if(void 0!==l&&(ca=l[n],void 0!==ca))switch(ca.length){case 2:A.vertexAttrib2fv(t,ca);break;case 3:A.vertexAttrib3fv(t,ca);break;case 4:A.vertexAttrib4fv(t,ca);break;default:A.vertexAttrib1fv(t,ca)}}}ga.disableUnusedAttributes()}null!==b&&A.bindBuffer(A.ELEMENT_ARRAY_BUFFER,
13742 r.buffer)}r=0;null!==b?r=b.count:void 0!==q&&(r=q.count);b=c.drawRange.start*m;q=null!==f?f.start*m:0;n=Math.max(b,q);f=Math.max(0,Math.min(r,b+c.drawRange.count*m,q+(null!==f?f.count*m:Infinity))-1-n+1);if(0!==f){if(e.isMesh)if(!0===d.wireframe)ga.setLineWidth(d.wireframeLinewidth*(null===P?Q:1)),a.setMode(A.LINES);else switch(e.drawMode){case 0:a.setMode(A.TRIANGLES);break;case 1:a.setMode(A.TRIANGLE_STRIP);break;case 2:a.setMode(A.TRIANGLE_FAN)}else e.isLine?(d=d.linewidth,void 0===d&&(d=1),ga.setLineWidth(d*
13743 (null===P?Q:1)),e.isLineSegments?a.setMode(A.LINES):e.isLineLoop?a.setMode(A.LINE_LOOP):a.setMode(A.LINE_STRIP)):e.isPoints&&a.setMode(A.POINTS);c&&c.isInstancedBufferGeometry?0<c.maxInstancedCount&&a.renderInstances(c,n,f):a.render(n,f)}};this.compile=function(a,b){aa=[];a.traverse(function(a){a.isLight&&aa.push(a)});t(aa,b);a.traverse(function(b){if(b.material)if(Array.isArray(b.material))for(var c=0;c<b.material.length;c++)v(b.material[c],a.fog,b);else v(b.material,a.fog,b)})};this.animate=function(a){function b(){a();
13744 (sa.getDevice()||window).requestAnimationFrame(b)}(sa.getDevice()||window).requestAnimationFrame(b)};this.render=function(a,b,c,d){if(b&&b.isCamera){pa="";V=-1;S=null;!0===a.autoUpdate&&a.updateMatrixWorld();null===b.parent&&b.updateMatrixWorld();sa.enabled&&(b=sa.getCamera(b));jd.multiplyMatrices(b.projectionMatrix,b.matrixWorldInverse);Vd.setFromMatrix(jd);aa.length=0;C.length=0;z.length=0;Wd=this.localClippingEnabled;id=Ha.init(this.clippingPlanes,Wd,b);F=Aa.get(a,b);F.init();k(a,b,B.sortObjects);
13745 F.finish();!0===B.sortObjects&&F.sort();id&&Ha.beginShadows();for(var e=aa,f=0,g=0,h=e.length;g<h;g++){var q=e[g];q.castShadow&&(da.shadows[f]=q,f++)}da.shadows.length=f;Ba.render(a,b);t(aa,b);id&&Ha.endShadows();la.frame++;la.calls=0;la.vertices=0;la.faces=0;la.points=0;void 0===c&&(c=null);this.setRenderTarget(c);ya.render(a,b,d);d=F.opaque;e=F.transparent;a.overrideMaterial?(f=a.overrideMaterial,d.length&&m(d,a,b,f),e.length&&m(e,a,b,f)):(d.length&&m(d,a,b),e.length&&m(e,a,b));Fa.render(a,b);Ga.render(a,
13746 b,U);c&&ra.updateRenderTargetMipmap(c);ga.buffers.depth.setTest(!0);ga.buffers.depth.setMask(!0);ga.buffers.color.setMask(!0);b.isArrayCamera&&B.setScissorTest(!1);sa.enabled&&sa.submitFrame()}else console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.")};this.setFaceCulling=function(a,b){ga.setCullFace(a);ga.setFlipSided(0===b)};this.allocTextureUnit=function(){var a=X;a>=ia.maxTextures&&console.warn("THREE.WebGLRenderer: Trying to use "+a+" texture units while this GPU supports only "+
13747 ia.maxTextures);X+=1;return a};this.setTexture2D=function(){var a=!1;return function(b,c){b&&b.isWebGLRenderTarget&&(a||(console.warn("THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead."),a=!0),b=b.texture);ra.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);ra.setTexture2D(b,c)}}();this.setTextureCube=function(){var a=
13748 !1;return function(b,c){b&&b.isWebGLRenderTargetCube&&(a||(console.warn("THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead."),a=!0),b=b.texture);b&&b.isCubeTexture||Array.isArray(b.image)&&6===b.image.length?ra.setTextureCube(b,c):ra.setTextureCubeDynamic(b,c)}}();this.getRenderTarget=function(){return P};this.setRenderTarget=function(a){(P=a)&&void 0===ha.get(a).__webglFramebuffer&&ra.setupRenderTarget(a);var b=a&&a.isWebGLRenderTargetCube,
13749 c;a?(c=ha.get(a),c=b?c.__webglFramebuffer[a.activeCubeFace]:c.__webglFramebuffer,J.copy(a.scissor),Z=a.scissorTest,U.copy(a.viewport)):(c=null,J.copy(ea).multiplyScalar(Q),Z=na,U.copy(hd).multiplyScalar(Q));M!==c&&(A.bindFramebuffer(A.FRAMEBUFFER,c),M=c);ga.scissor(J);ga.setScissorTest(Z);ga.viewport(U);b&&(b=ha.get(a.texture),A.framebufferTexture2D(A.FRAMEBUFFER,A.COLOR_ATTACHMENT0,A.TEXTURE_CUBE_MAP_POSITIVE_X+a.activeCubeFace,b.__webglTexture,a.activeMipMapLevel))};this.readRenderTargetPixels=
13750 function(a,b,c,d,e,f){if(a&&a.isWebGLRenderTarget){var g=ha.get(a).__webglFramebuffer;if(g){var h=!1;g!==M&&(A.bindFramebuffer(A.FRAMEBUFFER,g),h=!0);try{var k=a.texture,m=k.format,q=k.type;1023!==m&&y(m)!==A.getParameter(A.IMPLEMENTATION_COLOR_READ_FORMAT)?console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format."):1009===q||y(q)===A.getParameter(A.IMPLEMENTATION_COLOR_READ_TYPE)||1015===q&&(ma.get("OES_texture_float")||ma.get("WEBGL_color_buffer_float"))||
13751 1016===q&&ma.get("EXT_color_buffer_half_float")?A.checkFramebufferStatus(A.FRAMEBUFFER)===A.FRAMEBUFFER_COMPLETE?0<=b&&b<=a.width-d&&0<=c&&c<=a.height-e&&A.readPixels(b,c,d,e,y(m),y(q),f):console.error("THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete."):console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.")}finally{h&&A.bindFramebuffer(A.FRAMEBUFFER,M)}}}else console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.")}}
13752 function Ib(a,b){this.name="";this.color=new G(a);this.density=void 0!==b?b:2.5E-4}function Jb(a,b,c){this.name="";this.color=new G(a);this.near=void 0!==b?b:1;this.far=void 0!==c?c:1E3}function ld(){z.call(this);this.type="Scene";this.overrideMaterial=this.fog=this.background=null;this.autoUpdate=!0}function Yd(a,b,c,d,e){z.call(this);this.lensFlares=[];this.positionScreen=new n;this.customUpdateCallback=void 0;void 0!==a&&this.add(a,b,c,d,e)}function bb(a){U.call(this);this.type="SpriteMaterial";
13753 this.color=new G(16777215);this.map=null;this.rotation=0;this.lights=this.fog=!1;this.setValues(a)}function xc(a){z.call(this);this.type="Sprite";this.material=void 0!==a?a:new bb}function yc(){z.call(this);this.type="LOD";Object.defineProperties(this,{levels:{enumerable:!0,value:[]}})}function zc(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{console.warn("THREE.Skeleton boneInverses is the wrong length.");
13754 this.boneInverses=[];for(var c=0,d=this.bones.length;c<d;c++)this.boneInverses.push(new K)}}function md(){z.call(this);this.type="Bone"}function nd(a,b){la.call(this,a,b);this.type="SkinnedMesh";this.bindMode="attached";this.bindMatrix=new K;this.bindMatrixInverse=new K;var c=this.initBones(),c=new zc(c);this.bind(c,this.matrixWorld);this.normalizeSkinWeights()}function ea(a){U.call(this);this.type="LineBasicMaterial";this.color=new G(16777215);this.linewidth=1;this.linejoin=this.linecap="round";
13755 this.lights=!1;this.setValues(a)}function sa(a,b,c){if(1===c)return console.warn("THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead."),new Q(a,b);z.call(this);this.type="Line";this.geometry=void 0!==a?a:new E;this.material=void 0!==b?b:new ea({color:16777215*Math.random()})}function Q(a,b){sa.call(this,a,b);this.type="LineSegments"}function od(a,b){sa.call(this,a,b);this.type="LineLoop"}function Fa(a){U.call(this);this.type="PointsMaterial";this.color=
13756 new G(16777215);this.map=null;this.size=1;this.sizeAttenuation=!0;this.lights=!1;this.setValues(a)}function Kb(a,b){z.call(this);this.type="Points";this.geometry=void 0!==a?a:new E;this.material=void 0!==b?b:new Fa({color:16777215*Math.random()})}function Ac(){z.call(this);this.type="Group"}function pd(a,b,c,d,e,f,g,h,k){function m(){requestAnimationFrame(m);a.readyState>=a.HAVE_CURRENT_DATA&&(q.needsUpdate=!0)}ba.call(this,a,b,c,d,e,f,g,h,k);this.generateMipmaps=!1;var q=this;m()}function Lb(a,b,
13757 c,d,e,f,g,h,k,m,q,v){ba.call(this,null,f,g,h,k,m,d,e,q,v);this.image={width:b,height:c};this.mipmaps=a;this.generateMipmaps=this.flipY=!1}function qd(a,b,c,d,e,f,g,h,k){ba.call(this,a,b,c,d,e,f,g,h,k);this.needsUpdate=!0}function Bc(a,b,c,d,e,f,g,h,k,m){m=void 0!==m?m:1026;if(1026!==m&&1027!==m)throw Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");void 0===c&&1026===m&&(c=1012);void 0===c&&1027===m&&(c=1020);ba.call(this,null,d,e,f,g,h,m,c,k);this.image={width:a,
13758 height:b};this.magFilter=void 0!==g?g:1003;this.minFilter=void 0!==h?h:1003;this.generateMipmaps=this.flipY=!1}function Mb(a){E.call(this);this.type="WireframeGeometry";var b=[],c,d,e,f,g=[0,0],h={},k,m,q=["a","b","c"];if(a&&a.isGeometry){var v=a.faces;c=0;for(e=v.length;c<e;c++){var p=v[c];for(d=0;3>d;d++)k=p[q[d]],m=p[q[(d+1)%3]],g[0]=Math.min(k,m),g[1]=Math.max(k,m),k=g[0]+","+g[1],void 0===h[k]&&(h[k]={index1:g[0],index2:g[1]})}for(k in h)c=h[k],q=a.vertices[c.index1],b.push(q.x,q.y,q.z),q=a.vertices[c.index2],
13759 b.push(q.x,q.y,q.z)}else if(a&&a.isBufferGeometry){var r,q=new n;if(null!==a.index){v=a.attributes.position;p=a.index;r=a.groups;0===r.length&&(r=[{start:0,count:p.count,materialIndex:0}]);a=0;for(f=r.length;a<f;++a)for(c=r[a],d=c.start,e=c.count,c=d,e=d+e;c<e;c+=3)for(d=0;3>d;d++)k=p.getX(c+d),m=p.getX(c+(d+1)%3),g[0]=Math.min(k,m),g[1]=Math.max(k,m),k=g[0]+","+g[1],void 0===h[k]&&(h[k]={index1:g[0],index2:g[1]});for(k in h)c=h[k],q.fromBufferAttribute(v,c.index1),b.push(q.x,q.y,q.z),q.fromBufferAttribute(v,
13760 c.index2),b.push(q.x,q.y,q.z)}else for(v=a.attributes.position,c=0,e=v.count/3;c<e;c++)for(d=0;3>d;d++)h=3*c+d,q.fromBufferAttribute(v,h),b.push(q.x,q.y,q.z),h=3*c+(d+1)%3,q.fromBufferAttribute(v,h),b.push(q.x,q.y,q.z)}this.addAttribute("position",new B(b,3))}function Cc(a,b,c){J.call(this);this.type="ParametricGeometry";this.parameters={func:a,slices:b,stacks:c};this.fromBufferGeometry(new Nb(a,b,c));this.mergeVertices()}function Nb(a,b,c){E.call(this);this.type="ParametricBufferGeometry";this.parameters=
13761 {func:a,slices:b,stacks:c};var d=[],e=[],f=[],g=[],h=new n,k=new n,m=new n,q=new n,v=new n,p,r,l=b+1;for(p=0;p<=c;p++){var t=p/c;for(r=0;r<=b;r++){var y=r/b,k=a(y,t,k);e.push(k.x,k.y,k.z);0<=y-1E-5?(m=a(y-1E-5,t,m),q.subVectors(k,m)):(m=a(y+1E-5,t,m),q.subVectors(m,k));0<=t-1E-5?(m=a(y,t-1E-5,m),v.subVectors(k,m)):(m=a(y,t+1E-5,m),v.subVectors(m,k));h.crossVectors(q,v).normalize();f.push(h.x,h.y,h.z);g.push(y,t)}}for(p=0;p<c;p++)for(r=0;r<b;r++)a=p*l+r+1,h=(p+1)*l+r+1,k=(p+1)*l+r,d.push(p*l+r,a,k),
13762 d.push(a,h,k);this.setIndex(d);this.addAttribute("position",new B(e,3));this.addAttribute("normal",new B(f,3));this.addAttribute("uv",new B(g,2))}function Dc(a,b,c,d){J.call(this);this.type="PolyhedronGeometry";this.parameters={vertices:a,indices:b,radius:c,detail:d};this.fromBufferGeometry(new za(a,b,c,d));this.mergeVertices()}function za(a,b,c,d){function e(a){h.push(a.x,a.y,a.z)}function f(b,c){var d=3*b;c.x=a[d+0];c.y=a[d+1];c.z=a[d+2]}function g(a,b,c,d){0>d&&1===a.x&&(k[b]=a.x-1);0===c.x&&0===
13763 c.z&&(k[b]=d/2/Math.PI+.5)}E.call(this);this.type="PolyhedronBufferGeometry";this.parameters={vertices:a,indices:b,radius:c,detail:d};c=c||1;d=d||0;var h=[],k=[];(function(a){for(var c=new n,d=new n,g=new n,h=0;h<b.length;h+=3){f(b[h+0],c);f(b[h+1],d);f(b[h+2],g);var k=c,l=d,y=g,x=Math.pow(2,a),u=[],H,w;for(H=0;H<=x;H++){u[H]=[];var I=k.clone().lerp(y,H/x),W=l.clone().lerp(y,H/x),D=x-H;for(w=0;w<=D;w++)u[H][w]=0===w&&H===x?I:I.clone().lerp(W,w/D)}for(H=0;H<x;H++)for(w=0;w<2*(x-H)-1;w++)k=Math.floor(w/
13764 2),0===w%2?(e(u[H][k+1]),e(u[H+1][k]),e(u[H][k])):(e(u[H][k+1]),e(u[H+1][k+1]),e(u[H+1][k]))}})(d);(function(a){for(var b=new n,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 n,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 n,b=new n,c=new n,d=new n,e=new C,f=new C,l=new C,y=0,
13765 x=0;y<h.length;y+=9,x+=6){a.set(h[y+0],h[y+1],h[y+2]);b.set(h[y+3],h[y+4],h[y+5]);c.set(h[y+6],h[y+7],h[y+8]);e.set(k[x+0],k[x+1]);f.set(k[x+2],k[x+3]);l.set(k[x+4],k[x+5]);d.copy(a).add(b).add(c).divideScalar(3);var u=Math.atan2(d.z,-d.x);g(e,x+0,a,u);g(f,x+2,b,u);g(l,x+4,c,u)}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 B(h,3));this.addAttribute("normal",
13766 new B(h.slice(),3));this.addAttribute("uv",new B(k,2));0===d?this.computeVertexNormals():this.normalizeNormals()}function Ec(a,b){J.call(this);this.type="TetrahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Ob(a,b));this.mergeVertices()}function Ob(a,b){za.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 Fc(a,b){J.call(this);this.type="OctahedronGeometry";this.parameters=
13767 {radius:a,detail:b};this.fromBufferGeometry(new lb(a,b));this.mergeVertices()}function lb(a,b){za.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 Gc(a,b){J.call(this);this.type="IcosahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Pb(a,b));this.mergeVertices()}function Pb(a,b){var c=(1+Math.sqrt(5))/2;za.call(this,[-1,c,0,1,c,0,
13768 -1,-c,0,1,-c,0,0,-1,c,0,1,c,0,-1,-c,0,1,-c,c,0,-1,c,0,1,-c,0,-1,-c,0,1],[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1],a,b);this.type="IcosahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Hc(a,b){J.call(this);this.type="DodecahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Qb(a,b));this.mergeVertices()}function Qb(a,b){var c=(1+Math.sqrt(5))/2,d=1/c;za.call(this,
13769 [-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-d,-c,0,-d,c,0,d,-c,0,d,c,-d,-c,0,-d,c,0,d,-c,0,d,c,0,-c,0,-d,c,0,-d,-c,0,d,c,0,d],[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9],a,b);this.type="DodecahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Ic(a,
13770 b,c,d,e,f){J.call(this);this.type="TubeGeometry";this.parameters={path:a,tubularSegments:b,radius:c,radialSegments:d,closed:e};void 0!==f&&console.warn("THREE.TubeGeometry: taper has been removed.");a=new Rb(a,b,c,d,e);this.tangents=a.tangents;this.normals=a.normals;this.binormals=a.binormals;this.fromBufferGeometry(a);this.mergeVertices()}function Rb(a,b,c,d,e){function f(e){var f=a.getPointAt(e/b),m=g.normals[e];e=g.binormals[e];for(v=0;v<=d;v++){var q=v/d*Math.PI*2,l=Math.sin(q),q=-Math.cos(q);
13771 k.x=q*m.x+l*e.x;k.y=q*m.y+l*e.y;k.z=q*m.z+l*e.z;k.normalize();r.push(k.x,k.y,k.z);h.x=f.x+c*k.x;h.y=f.y+c*k.y;h.z=f.z+c*k.z;p.push(h.x,h.y,h.z)}}E.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 n,k=new n,m=new C,q,v,p=[],r=[],l=[],t=[];for(q=0;q<b;q++)f(q);f(!1===e?b:0);for(q=0;q<=
13772 b;q++)for(v=0;v<=d;v++)m.x=q/b,m.y=v/d,l.push(m.x,m.y);(function(){for(v=1;v<=b;v++)for(q=1;q<=d;q++){var a=(d+1)*v+(q-1),c=(d+1)*v+q,e=(d+1)*(v-1)+q;t.push((d+1)*(v-1)+(q-1),a,e);t.push(a,c,e)}})();this.setIndex(t);this.addAttribute("position",new B(p,3));this.addAttribute("normal",new B(r,3));this.addAttribute("uv",new B(l,2))}function Jc(a,b,c,d,e,f,g){J.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.");
13773 this.fromBufferGeometry(new Sb(a,b,c,d,e,f));this.mergeVertices()}function Sb(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}E.call(this);this.type="TorusKnotBufferGeometry";this.parameters={radius:a,tube:b,tubularSegments:c,radialSegments:d,p:e,q:f};a=a||100;b=b||40;c=Math.floor(c)||64;d=Math.floor(d)||8;e=e||2;f=f||3;var h=[],k=[],m=[],q=[],v,p,r=new n,l=new n,t=new n,y=new n,x=new n,u=new n,H=new n;for(v=
13774 0;v<=c;++v)for(p=v/c*e*Math.PI*2,g(p,e,f,a,t),g(p+.01,e,f,a,y),u.subVectors(y,t),H.addVectors(y,t),x.crossVectors(u,H),H.crossVectors(x,u),x.normalize(),H.normalize(),p=0;p<=d;++p){var w=p/d*Math.PI*2,I=-b*Math.cos(w),w=b*Math.sin(w);r.x=t.x+(I*H.x+w*x.x);r.y=t.y+(I*H.y+w*x.y);r.z=t.z+(I*H.z+w*x.z);k.push(r.x,r.y,r.z);l.subVectors(r,t).normalize();m.push(l.x,l.y,l.z);q.push(v/c);q.push(p/d)}for(p=1;p<=c;p++)for(v=1;v<=d;v++)a=(d+1)*p+(v-1),b=(d+1)*p+v,e=(d+1)*(p-1)+v,h.push((d+1)*(p-1)+(v-1),a,e),
13775 h.push(a,b,e);this.setIndex(h);this.addAttribute("position",new B(k,3));this.addAttribute("normal",new B(m,3));this.addAttribute("uv",new B(q,2))}function Kc(a,b,c,d,e){J.call(this);this.type="TorusGeometry";this.parameters={radius:a,tube:b,radialSegments:c,tubularSegments:d,arc:e};this.fromBufferGeometry(new Tb(a,b,c,d,e));this.mergeVertices()}function Tb(a,b,c,d,e){E.call(this);this.type="TorusBufferGeometry";this.parameters={radius:a,tube:b,radialSegments:c,tubularSegments:d,arc:e};a=a||100;b=
13776 b||40;c=Math.floor(c)||8;d=Math.floor(d)||6;e=e||2*Math.PI;var f=[],g=[],h=[],k=[],m=new n,q=new n,v=new n,p,r;for(p=0;p<=c;p++)for(r=0;r<=d;r++){var l=r/d*e,t=p/c*Math.PI*2;q.x=(a+b*Math.cos(t))*Math.cos(l);q.y=(a+b*Math.cos(t))*Math.sin(l);q.z=b*Math.sin(t);g.push(q.x,q.y,q.z);m.x=a*Math.cos(l);m.y=a*Math.sin(l);v.subVectors(q,m).normalize();h.push(v.x,v.y,v.z);k.push(r/d);k.push(p/c)}for(p=1;p<=c;p++)for(r=1;r<=d;r++)a=(d+1)*(p-1)+r-1,b=(d+1)*(p-1)+r,e=(d+1)*p+r,f.push((d+1)*p+r-1,a,e),f.push(a,
13777 b,e);this.setIndex(f);this.addAttribute("position",new B(g,3));this.addAttribute("normal",new B(h,3));this.addAttribute("uv",new B(k,2))}function cb(a,b){J.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&&(E.call(this),this.type="ExtrudeBufferGeometry",a=Array.isArray(a)?a:[a],this.addShapeList(a,b),this.computeVertexNormals())}function Lc(a,b){J.call(this);this.type="TextGeometry";
13778 this.parameters={text:a,parameters:b};this.fromBufferGeometry(new Ub(a,b));this.mergeVertices()}function Ub(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 J;c=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,c,b);this.type="TextBufferGeometry"}
13779 function Mc(a,b,c,d,e,f,g){J.call(this);this.type="SphereGeometry";this.parameters={radius:a,widthSegments:b,heightSegments:c,phiStart:d,phiLength:e,thetaStart:f,thetaLength:g};this.fromBufferGeometry(new mb(a,b,c,d,e,f,g));this.mergeVertices()}function mb(a,b,c,d,e,f,g){E.call(this);this.type="SphereBufferGeometry";this.parameters={radius:a,widthSegments:b,heightSegments:c,phiStart:d,phiLength:e,thetaStart:f,thetaLength:g};a=a||50;b=Math.max(3,Math.floor(b)||8);c=Math.max(2,Math.floor(c)||6);d=void 0!==
13780 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,m,q=0,v=[],p=new n,r=new n,l=[],t=[],y=[],x=[];for(m=0;m<=c;m++){var u=[],H=m/c;for(k=0;k<=b;k++){var w=k/b;p.x=-a*Math.cos(d+w*e)*Math.sin(f+H*g);p.y=a*Math.cos(f+H*g);p.z=a*Math.sin(d+w*e)*Math.sin(f+H*g);t.push(p.x,p.y,p.z);r.set(p.x,p.y,p.z).normalize();y.push(r.x,r.y,r.z);x.push(w,1-H);u.push(q++)}v.push(u)}for(m=0;m<c;m++)for(k=0;k<b;k++)a=v[m][k+1],d=v[m][k],e=v[m+1][k],g=v[m+1][k+1],(0!==m||0<f)&&l.push(a,d,
13781 g),(m!==c-1||h<Math.PI)&&l.push(d,e,g);this.setIndex(l);this.addAttribute("position",new B(t,3));this.addAttribute("normal",new B(y,3));this.addAttribute("uv",new B(x,2))}function Nc(a,b,c,d,e,f){J.call(this);this.type="RingGeometry";this.parameters={innerRadius:a,outerRadius:b,thetaSegments:c,phiSegments:d,thetaStart:e,thetaLength:f};this.fromBufferGeometry(new Vb(a,b,c,d,e,f));this.mergeVertices()}function Vb(a,b,c,d,e,f){E.call(this);this.type="RingBufferGeometry";this.parameters={innerRadius:a,
13782 outerRadius:b,thetaSegments:c,phiSegments:d,thetaStart:e,thetaLength:f};a=a||20;b=b||50;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=[],m=[],q=a,v=(b-a)/d,p=new n,r=new C,l,t;for(l=0;l<=d;l++){for(t=0;t<=c;t++)a=e+t/c*f,p.x=q*Math.cos(a),p.y=q*Math.sin(a),h.push(p.x,p.y,p.z),k.push(0,0,1),r.x=(p.x/b+1)/2,r.y=(p.y/b+1)/2,m.push(r.x,r.y);q+=v}for(l=0;l<d;l++)for(b=l*(c+1),t=0;t<c;t++)a=t+b,e=a+c+1,f=a+c+2,q=a+1,g.push(a,e,q),g.push(e,
13783 f,q);this.setIndex(g);this.addAttribute("position",new B(h,3));this.addAttribute("normal",new B(k,3));this.addAttribute("uv",new B(m,2))}function Oc(a,b,c,d){J.call(this);this.type="LatheGeometry";this.parameters={points:a,segments:b,phiStart:c,phiLength:d};this.fromBufferGeometry(new Wb(a,b,c,d));this.mergeVertices()}function Wb(a,b,c,d){E.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=Y.clamp(d,
13784 0,2*Math.PI);var e=[],f=[],g=[],h=1/b,k=new n,m=new C,q,v;for(q=0;q<=b;q++){v=c+q*h*d;var p=Math.sin(v),r=Math.cos(v);for(v=0;v<=a.length-1;v++)k.x=a[v].x*p,k.y=a[v].y,k.z=a[v].x*r,f.push(k.x,k.y,k.z),m.x=q/b,m.y=v/(a.length-1),g.push(m.x,m.y)}for(q=0;q<b;q++)for(v=0;v<a.length-1;v++)c=v+q*a.length,h=c+a.length,k=c+a.length+1,m=c+1,e.push(c,h,m),e.push(h,k,m);this.setIndex(e);this.addAttribute("position",new B(f,3));this.addAttribute("uv",new B(g,2));this.computeVertexNormals();if(d===2*Math.PI)for(d=
13785 this.attributes.normal.array,e=new n,f=new n,g=new n,c=b*a.length*3,v=q=0;q<a.length;q++,v+=3)e.x=d[v+0],e.y=d[v+1],e.z=d[v+2],f.x=d[c+v+0],f.y=d[c+v+1],f.z=d[c+v+2],g.addVectors(e,f).normalize(),d[v+0]=d[c+v+0]=g.x,d[v+1]=d[c+v+1]=g.y,d[v+2]=d[c+v+2]=g.z}function Xb(a,b){J.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 Yb(a,
13786 b));this.mergeVertices()}function Yb(a,b){function c(a){var c,h,m=e.length/3;a=a.extractPoints(b);var l=a.shape,n=a.holes;if(!1===Ia.isClockWise(l))for(l=l.reverse(),a=0,c=n.length;a<c;a++)h=n[a],!0===Ia.isClockWise(h)&&(n[a]=h.reverse());var y=Ia.triangulateShape(l,n);a=0;for(c=n.length;a<c;a++)h=n[a],l=l.concat(h);a=0;for(c=l.length;a<c;a++)h=l[a],e.push(h.x,h.y,0),f.push(0,0,1),g.push(h.x,h.y);a=0;for(c=y.length;a<c;a++)l=y[a],d.push(l[0]+m,l[1]+m,l[2]+m),k+=3}E.call(this);this.type="ShapeBufferGeometry";
13787 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 m=0;m<a.length;m++)c(a[m]),this.addGroup(h,k,m),h+=k,k=0;this.setIndex(d);this.addAttribute("position",new B(e,3));this.addAttribute("normal",new B(f,3));this.addAttribute("uv",new B(g,2))}function Zb(a,b){E.call(this);this.type="EdgesGeometry";this.parameters={thresholdAngle:b};var c=[],d=Math.cos(Y.DEG2RAD*(void 0!==b?b:1)),e=[0,0],f={},g,h,k=["a","b","c"],m;a.isBufferGeometry?
13788 (m=new J,m.fromBufferGeometry(a)):m=a.clone();m.mergeVertices();m.computeFaceNormals();var q=m.vertices;m=m.faces;for(var v=0,p=m.length;v<p;v++)for(var l=m[v],n=0;3>n;n++)g=l[k[n]],h=l[k[(n+1)%3]],e[0]=Math.min(g,h),e[1]=Math.max(g,h),g=e[0]+","+e[1],void 0===f[g]?f[g]={index1:e[0],index2:e[1],face1:v,face2:void 0}:f[g].face2=v;for(g in f)if(e=f[g],void 0===e.face2||m[e.face1].normal.dot(m[e.face2].normal)<=d)k=q[e.index1],c.push(k.x,k.y,k.z),k=q[e.index2],c.push(k.x,k.y,k.z);this.addAttribute("position",
13789 new B(c,3))}function nb(a,b,c,d,e,f,g,h){J.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 Ua(a,b,c,d,e,f,g,h));this.mergeVertices()}function Ua(a,b,c,d,e,f,g,h){function k(c){var e,f,k,t=new C,D=new n,O=0,aa=!0===c?a:b,F=!0===c?1:-1;f=ca;for(e=1;e<=d;e++)v.push(0,y*F,0),p.push(0,F,0),l.push(.5,.5),ca++;k=ca;for(e=0;e<=d;e++){var B=e/d*h+g,z=Math.cos(B),
13790 B=Math.sin(B);D.x=aa*B;D.y=y*F;D.z=aa*z;v.push(D.x,D.y,D.z);p.push(0,F,0);t.x=.5*z+.5;t.y=.5*B*F+.5;l.push(t.x,t.y);ca++}for(e=0;e<d;e++)t=f+e,D=k+e,!0===c?q.push(D,D+1,t):q.push(D+1,D,t),O+=3;m.addGroup(x,O,!0===c?1:2);x+=O}E.call(this);this.type="CylinderBufferGeometry";this.parameters={radiusTop:a,radiusBottom:b,height:c,radialSegments:d,heightSegments:e,openEnded:f,thetaStart:g,thetaLength:h};var m=this;a=void 0!==a?a:20;b=void 0!==b?b:20;c=void 0!==c?c:100;d=Math.floor(d)||8;e=Math.floor(e)||
13791 1;f=void 0!==f?f:!1;g=void 0!==g?g:0;h=void 0!==h?h:2*Math.PI;var q=[],v=[],p=[],l=[],ca=0,t=[],y=c/2,x=0;(function(){var f,k,w=new n,I=new n,W=0,D=(b-a)/c;for(k=0;k<=e;k++){var O=[],aa=k/e,F=aa*(b-a)+a;for(f=0;f<=d;f++){var B=f/d,C=B*h+g,z=Math.sin(C),C=Math.cos(C);I.x=F*z;I.y=-aa*c+y;I.z=F*C;v.push(I.x,I.y,I.z);w.set(z,D,C).normalize();p.push(w.x,w.y,w.z);l.push(B,1-aa);O.push(ca++)}t.push(O)}for(f=0;f<d;f++)for(k=0;k<e;k++)w=t[k+1][f],I=t[k+1][f+1],D=t[k][f+1],q.push(t[k][f],w,D),q.push(w,I,D),
13792 W+=6;m.addGroup(x,W,0);x+=W})();!1===f&&(0<a&&k(!0),0<b&&k(!1));this.setIndex(q);this.addAttribute("position",new B(v,3));this.addAttribute("normal",new B(p,3));this.addAttribute("uv",new B(l,2))}function Pc(a,b,c,d,e,f,g){nb.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 Qc(a,b,c,d,e,f,g){Ua.call(this,0,a,b,c,d,e,f,g);this.type="ConeBufferGeometry";this.parameters={radius:a,
13793 height:b,radialSegments:c,heightSegments:d,openEnded:e,thetaStart:f,thetaLength:g}}function Rc(a,b,c,d){J.call(this);this.type="CircleGeometry";this.parameters={radius:a,segments:b,thetaStart:c,thetaLength:d};this.fromBufferGeometry(new $b(a,b,c,d));this.mergeVertices()}function $b(a,b,c,d){E.call(this);this.type="CircleBufferGeometry";this.parameters={radius:a,segments:b,thetaStart:c,thetaLength:d};a=a||50;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=[],
13794 h=[],k,m,q=new n,v=new C;f.push(0,0,0);g.push(0,0,1);h.push(.5,.5);m=0;for(k=3;m<=b;m++,k+=3){var p=c+m/b*d;q.x=a*Math.cos(p);q.y=a*Math.sin(p);f.push(q.x,q.y,q.z);g.push(0,0,1);v.x=(f[k]/a+1)/2;v.y=(f[k+1]/a+1)/2;h.push(v.x,v.y)}for(k=1;k<=b;k++)e.push(k,k+1,0);this.setIndex(e);this.addAttribute("position",new B(f,3));this.addAttribute("normal",new B(g,3));this.addAttribute("uv",new B(h,2))}function ac(a){ra.call(this,{uniforms:Ca.merge([R.lights,{opacity:{value:1}}]),vertexShader:X.shadow_vert,
13795 fragmentShader:X.shadow_frag});this.transparent=this.lights=!0;Object.defineProperties(this,{opacity:{enumerable:!0,get:function(){return this.uniforms.opacity.value},set:function(a){this.uniforms.opacity.value=a}}});this.setValues(a)}function bc(a){ra.call(this,a);this.type="RawShaderMaterial"}function Pa(a){U.call(this);this.defines={STANDARD:""};this.type="MeshStandardMaterial";this.color=new G(16777215);this.metalness=this.roughness=.5;this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=
13796 null;this.aoMapIntensity=1;this.emissive=new G(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.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=
13797 !1;this.setValues(a)}function ob(a){Pa.call(this);this.defines={PHYSICAL:""};this.type="MeshPhysicalMaterial";this.reflectivity=.5;this.clearCoatRoughness=this.clearCoat=0;this.setValues(a)}function Ja(a){U.call(this);this.type="MeshPhongMaterial";this.color=new G(16777215);this.specular=new G(1118481);this.shininess=30;this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new G(0);this.emissiveIntensity=1;this.bumpMap=this.emissiveMap=null;this.bumpScale=
13798 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=!1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.morphNormals=this.morphTargets=this.skinning=!1;this.setValues(a)}function pb(a){Ja.call(this);this.defines={TOON:""};this.type="MeshToonMaterial";this.gradientMap=null;
13799 this.setValues(a)}function qb(a){U.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=!1;this.wireframeLinewidth=1;this.morphNormals=this.morphTargets=this.skinning=this.lights=this.fog=!1;this.setValues(a)}function rb(a){U.call(this);this.type="MeshLambertMaterial";this.color=new G(16777215);this.lightMap=this.map=null;this.lightMapIntensity=
13800 1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new G(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=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.morphNormals=this.morphTargets=this.skinning=!1;this.setValues(a)}function sb(a){U.call(this);this.type="LineDashedMaterial";this.color=new G(16777215);this.scale=this.linewidth=1;this.dashSize=
13801 3;this.gapSize=1;this.lights=!1;this.setValues(a)}function Zd(a,b,c){var d=this,e=!1,f=0,g=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,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)}}function Ka(a){this.manager=void 0!==a?a:va}function Oe(a){this.manager=void 0!==
13802 a?a:va;this._parser=null}function $d(a){this.manager=void 0!==a?a:va;this._parser=null}function Sc(a){this.manager=void 0!==a?a:va}function ae(a){this.manager=void 0!==a?a:va}function rd(a){this.manager=void 0!==a?a:va}function na(a,b){z.call(this);this.type="Light";this.color=new G(a);this.intensity=void 0!==b?b:1;this.receiveShadow=void 0}function sd(a,b,c){na.call(this,a,c);this.type="HemisphereLight";this.castShadow=void 0;this.position.copy(z.DefaultUp);this.updateMatrix();this.groundColor=new G(b)}
13803 function tb(a){this.camera=a;this.bias=0;this.radius=1;this.mapSize=new C(512,512);this.map=null;this.matrix=new K}function td(){tb.call(this,new qa(50,1,.5,500))}function ud(a,b,c,d,e,f){na.call(this,a,b);this.type="SpotLight";this.position.copy(z.DefaultUp);this.updateMatrix();this.target=new z;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=
13804 void 0!==e?e:0;this.decay=void 0!==f?f:1;this.shadow=new td}function vd(a,b,c,d){na.call(this,a,b);this.type="PointLight";Object.defineProperty(this,"power",{get:function(){return 4*this.intensity*Math.PI},set:function(a){this.intensity=a/(4*Math.PI)}});this.distance=void 0!==c?c:0;this.decay=void 0!==d?d:1;this.shadow=new tb(new qa(90,1,.5,500))}function wd(){tb.call(this,new Fb(-5,5,5,-5,.5,500))}function xd(a,b){na.call(this,a,b);this.type="DirectionalLight";this.position.copy(z.DefaultUp);this.updateMatrix();
13805 this.target=new z;this.shadow=new wd}function yd(a,b){na.call(this,a,b);this.type="AmbientLight";this.castShadow=void 0}function zd(a,b,c,d){na.call(this,a,b);this.type="RectAreaLight";this.position.set(0,1,0);this.updateMatrix();this.width=void 0!==c?c:10;this.height=void 0!==d?d:10}function wa(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 Ad(a,b,c,d){wa.call(this,a,b,c,d);this._offsetNext=
13806 this._weightNext=this._offsetPrev=this._weightPrev=-0}function Tc(a,b,c,d){wa.call(this,a,b,c,d)}function Bd(a,b,c,d){wa.call(this,a,b,c,d)}function ub(a,b,c,d){if(void 0===a)throw Error("track name is undefined");if(void 0===b||0===b.length)throw Error("no keyframes in track named "+a);this.name=a;this.times=ia.convertArray(b,this.TimeBufferType);this.values=ia.convertArray(c,this.ValueBufferType);this.setInterpolation(d||this.DefaultInterpolation);this.validate();this.optimize()}function cc(a,b,
13807 c,d){ub.call(this,a,b,c,d)}function Cd(a,b,c,d){wa.call(this,a,b,c,d)}function Uc(a,b,c,d){ub.call(this,a,b,c,d)}function dc(a,b,c,d){ub.call(this,a,b,c,d)}function Dd(a,b,c,d){ub.call(this,a,b,c,d)}function Ed(a,b,c){ub.call(this,a,b,c)}function Fd(a,b,c,d){ub.call(this,a,b,c,d)}function vb(a,b,c,d){ub.apply(this,arguments)}function Da(a,b,c){this.name=a;this.tracks=c;this.duration=void 0!==b?b:-1;this.uuid=Y.generateUUID();0>this.duration&&this.resetDuration();this.optimize()}function Gd(a){this.manager=
13808 void 0!==a?a:va;this.textures={}}function be(a){this.manager=void 0!==a?a:va}function ec(){this.onLoadStart=function(){};this.onLoadProgress=function(){};this.onLoadComplete=function(){}}function ce(a){"boolean"===typeof a&&(console.warn("THREE.JSONLoader: showStatus parameter has been removed from constructor."),a=void 0);this.manager=void 0!==a?a:va;this.withCredentials=!1}function Pe(a){this.manager=void 0!==a?a:va;this.texturePath=""}function Qe(a,b,c,d,e){b=.5*(d-b);e=.5*(e-c);var f=a*a;return(2*
13809 c-2*d+b+e)*a*f+(-3*c+3*d-2*b-e)*f+b*a+c}function wb(a,b,c,d){var e=1-a;return e*e*b+2*(1-a)*a*c+a*a*d}function xb(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 ua(){this.arcLengthDivisions=200}function Qa(a,b){this.arcLengthDivisions=200;this.v1=a;this.v2=b}function Vc(){this.arcLengthDivisions=200;this.curves=[];this.autoClose=!1}function Va(a,b,c,d,e,f,g,h){this.arcLengthDivisions=200;this.aX=a;this.aY=b;this.xRadius=c;this.yRadius=d;this.aStartAngle=e;this.aEndAngle=
13810 f;this.aClockwise=g;this.aRotation=h||0}function yb(a){this.arcLengthDivisions=200;this.points=void 0===a?[]:a}function fc(a,b,c,d){this.arcLengthDivisions=200;this.v0=a;this.v1=b;this.v2=c;this.v3=d}function gc(a,b,c){this.arcLengthDivisions=200;this.v0=a;this.v1=b;this.v2=c}function Wc(a){Vc.call(this);this.currentPoint=new C;a&&this.fromPoints(a)}function zb(){Wc.apply(this,arguments);this.holes=[]}function de(){this.subPaths=[];this.currentPath=null}function ee(a){this.data=a}function Re(a){this.manager=
13811 void 0!==a?a:va}function fe(a){this.manager=void 0!==a?a:va}function Se(){this.type="StereoCamera";this.aspect=1;this.eyeSep=.064;this.cameraL=new qa;this.cameraL.layers.enable(1);this.cameraL.matrixAutoUpdate=!1;this.cameraR=new qa;this.cameraR.layers.enable(2);this.cameraR.matrixAutoUpdate=!1}function Hd(a,b,c){z.call(this);this.type="CubeCamera";var d=new qa(90,1,a,b);d.up.set(0,-1,0);d.lookAt(new n(1,0,0));this.add(d);var e=new qa(90,1,a,b);e.up.set(0,-1,0);e.lookAt(new n(-1,0,0));this.add(e);
13812 var f=new qa(90,1,a,b);f.up.set(0,0,1);f.lookAt(new n(0,1,0));this.add(f);var g=new qa(90,1,a,b);g.up.set(0,0,-1);g.lookAt(new n(0,-1,0));this.add(g);var h=new qa(90,1,a,b);h.up.set(0,-1,0);h.lookAt(new n(0,0,1));this.add(h);var k=new qa(90,1,a,b);k.up.set(0,-1,0);k.lookAt(new n(0,0,-1));this.add(k);this.renderTarget=new Db(c,c,{format:1022,magFilter:1006,minFilter:1006});this.renderTarget.texture.name="CubeCamera";this.updateCubeMap=function(a,b){null===this.parent&&this.updateMatrixWorld();var c=
13813 this.renderTarget,p=c.texture.generateMipmaps;c.texture.generateMipmaps=!1;c.activeCubeFace=0;a.render(b,d,c);c.activeCubeFace=1;a.render(b,e,c);c.activeCubeFace=2;a.render(b,f,c);c.activeCubeFace=3;a.render(b,g,c);c.activeCubeFace=4;a.render(b,h,c);c.texture.generateMipmaps=p;c.activeCubeFace=5;a.render(b,k,c);a.setRenderTarget(null)}}function ge(){z.call(this);this.type="AudioListener";this.context=he.getContext();this.gain=this.context.createGain();this.gain.connect(this.context.destination);this.filter=
13814 null}function hc(a){z.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.startTime=0;this.playbackRate=1;this.isPlaying=!1;this.hasPlaybackControl=!0;this.sourceType="empty";this.filters=[]}function ie(a){hc.call(this,a);this.panner=this.context.createPanner();this.panner.connect(this.gain)}function je(a,b){this.analyser=a.context.createAnalyser();this.analyser.fftSize=void 0!==
13815 b?b:2048;this.data=new Uint8Array(this.analyser.frequencyBinCount);a.getOutput().connect(this.analyser)}function ke(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 Te(a,b,c){c=c||ha.parseTrackName(b);this._targetGroup=a;this._bindings=a.subscribe_(b,c)}function ha(a,
13816 b,c){this.path=b;this.parsedPath=c||ha.parseTrackName(b);this.node=ha.findNode(a,this.parsedPath.nodeName)||a;this.rootNode=a}function Ue(a){this.uuid=Y.generateUUID();this._objects=Array.prototype.slice.call(arguments);this.nCachedObjects_=0;var b={};this._indicesByUUID=b;for(var c=0,d=arguments.length;c!==d;++c)b[arguments[c].uuid]=c;this._paths=[];this._parsedPaths=[];this._bindings=[];this._bindingsIndicesByPath={};var e=this;this.stats={objects:{get total(){return e._objects.length},get inUse(){return this.total-
13817 e.nCachedObjects_}},get bindingsPerObject(){return e._bindings.length}}}function Ve(a,b,c){this._mixer=a;this._clip=b;this._localRoot=c||null;a=b.tracks;b=a.length;c=Array(b);for(var d={endingStart:2400,endingEnd:2400},e=0;e!==b;++e){var f=a[e].createInterpolant(null);c[e]=f;f.settings=d}this._interpolantSettings=d;this._interpolants=c;this._propertyBindings=Array(b);this._weightInterpolant=this._timeScaleInterpolant=this._byClipCacheIndex=this._cacheIndex=null;this.loop=2201;this._loopCount=-1;this._startTime=
13818 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 We(a){this._root=a;this._initMemoryManager();this.time=this._accuIndex=0;this.timeScale=1}function Id(a,b){"string"===typeof a&&(console.warn("THREE.Uniform: Type parameter is no longer needed."),a=b);this.value=a}function le(){E.call(this);this.type="InstancedBufferGeometry";
13819 this.maxInstancedCount=void 0}function me(a,b,c,d){this.uuid=Y.generateUUID();this.data=a;this.itemSize=b;this.offset=c;this.normalized=!0===d}function ic(a,b){this.uuid=Y.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 ne(a,b,c){ic.call(this,a,b);this.meshPerAttribute=c||1}function oe(a,b,c){Z.call(this,a,b);this.meshPerAttribute=c||1}function Xe(a,b,c,d){this.ray=
13820 new kb(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 Ye(a,b){return a.distance-b.distance}function pe(a,b,c,d){if(!1!==a.visible&&(a.raycast(b,c),!0===d)){a=a.children;d=0;for(var e=a.length;d<e;d++)pe(a[d],b,c,!0)}}function Ze(a){this.autoStart=void 0!==a?
13821 a:!0;this.elapsedTime=this.oldTime=this.startTime=0;this.running=!1}function $e(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 af(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 ta(a,b){la.call(this,a,b);this.animationsMap={};this.animationsList=[];var c=this.geometry.morphTargets.length;this.createAnimation("__default",0,c-1,c/1);this.setAnimationWeight("__default",1)}function Xc(a){z.call(this);
13822 this.material=a;this.render=function(a){}}function Yc(a,b,c,d){this.object=a;this.size=void 0!==b?b:1;a=void 0!==c?c: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 E;b=new B(6*b,3);c.addAttribute("position",b);Q.call(this,c,new ea({color:a,linewidth:d}));this.matrixAutoUpdate=!1;this.update()}function jc(a){z.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=
13823 !1;a=new E;for(var 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],c=0,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 B(b,3));b=new ea({fog:!1});this.cone=new Q(a,b);this.add(this.cone);this.update()}function bf(a){var b=[];a&&a.isBone&&b.push(a);for(var c=0;c<a.children.length;c++)b.push.apply(b,bf(a.children[c]));return b}function kc(a){for(var b=bf(a),c=new E,d=[],e=[],f=new G(0,
13824 0,1),g=new G(0,1,0),h=0;h<b.length;h++){var k=b[h];k.parent&&k.parent.isBone&&(d.push(0,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 B(d,3));c.addAttribute("color",new B(e,3));d=new ea({vertexColors:2,depthTest:!1,depthWrite:!1,transparent:!0});Q.call(this,c,d);this.root=a;this.bones=b;this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.onBeforeRender()}function lc(a,b){this.light=a;this.light.updateMatrixWorld();var c=new mb(b,4,2),d=new ya({wireframe:!0,
13825 fog:!1});d.color.copy(this.light.color);la.call(this,c,d);this.matrix=this.light.matrixWorld;this.matrixAutoUpdate=!1}function mc(a){z.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;a=new ea({color:a.color});var b=new E;b.addAttribute("position",new Z(new Float32Array(15),3));this.add(new sa(b,a));this.update()}function nc(a,b){z.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;var c=
13826 new lb(b);c.rotateY(.5*Math.PI);var d=new ya({vertexColors:2,wireframe:!0}),e=c.getAttribute("position"),e=new Float32Array(3*e.count);c.addAttribute("color",new Z(e,3));this.add(new la(c,d));this.update()}function Zc(a,b,c,d){a=a||10;b=b||10;c=new G(void 0!==c?c:4473924);d=new G(void 0!==d?d:8947848);var e=b/2,f=a/b,g=a/2;a=[];for(var h=[],k=0,m=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 l=k===e?c:d;l.toArray(h,m);m+=3;l.toArray(h,m);m+=3;l.toArray(h,m);m+=3;l.toArray(h,
13827 m);m+=3}b=new E;b.addAttribute("position",new B(a,3));b.addAttribute("color",new B(h,3));c=new ea({vertexColors:2});Q.call(this,b,c)}function Jd(a,b,c,d,e,f){a=a||10;b=b||16;c=c||8;d=d||64;e=new G(void 0!==e?e:4473924);f=new G(void 0!==f?f:8947848);var g=[],h=[],k,m,q,l,p;for(q=0;q<=b;q++)m=q/b*2*Math.PI,k=Math.sin(m)*a,m=Math.cos(m)*a,g.push(0,0,0),g.push(k,0,m),p=q&1?e:f,h.push(p.r,p.g,p.b),h.push(p.r,p.g,p.b);for(q=0;q<=c;q++)for(p=q&1?e:f,l=a-a/c*q,b=0;b<d;b++)m=b/d*2*Math.PI,k=Math.sin(m)*l,
13828 m=Math.cos(m)*l,g.push(k,0,m),h.push(p.r,p.g,p.b),m=(b+1)/d*2*Math.PI,k=Math.sin(m)*l,m=Math.cos(m)*l,g.push(k,0,m),h.push(p.r,p.g,p.b);a=new E;a.addAttribute("position",new B(g,3));a.addAttribute("color",new B(h,3));g=new ea({vertexColors:2});Q.call(this,a,g)}function $c(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.");
13829 c=new E;b=new B(6*b,3);c.addAttribute("position",b);Q.call(this,c,new ea({color:a,linewidth:d}));this.matrixAutoUpdate=!1;this.update()}function oc(a,b){z.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;void 0===b&&(b=1);var c=new E;c.addAttribute("position",new B([-b,b,0,b,b,0,b,-b,0,-b,-b,0,-b,b,0],3));var d=new ea({fog:!1});this.add(new sa(c,d));c=new E;c.addAttribute("position",new B([0,0,0,0,0,1],3));this.add(new sa(c,d));this.update()}
13830 function ad(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 E,e=new ea({color:16777215,vertexColors:1}),f=[],g=[],h={},k=new G(16755200),m=new G(16711680),q=new G(43775),l=new G(16777215),p=new G(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);b("n3","f3",k);b("n4","f4",k);b("p","n1",m);b("p",
13831 "n2",m);b("p","n3",m);b("p","n4",m);b("u1","u2",q);b("u2","u3",q);b("u3","u1",q);b("c","t",l);b("p","c",p);b("cn1","cn2",p);b("cn3","cn4",p);b("cf1","cf2",p);b("cf3","cf4",p);d.addAttribute("position",new B(f,3));d.addAttribute("color",new B(g,3));Q.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 Ab(a,b){this.object=a;void 0===b&&(b=16776960);var c=new Uint16Array([0,
13832 1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]),d=new Float32Array(24),e=new E;e.setIndex(new Z(c,1));e.addAttribute("position",new Z(d,3));Q.call(this,e,new ea({color:b}));this.matrixAutoUpdate=!1;this.update()}function Bb(a,b,c,d,e,f){z.call(this);void 0===d&&(d=16776960);void 0===c&&(c=1);void 0===e&&(e=.2*c);void 0===f&&(f=.2*e);void 0===Kd&&(Kd=new E,Kd.addAttribute("position",new B([0,0,0,0,1,0],3)),qe=new Ua(0,.5,1,5,1),qe.translate(0,-.5,0));this.position.copy(b);this.line=new sa(Kd,new ea({color:d}));
13833 this.line.matrixAutoUpdate=!1;this.add(this.line);this.cone=new la(qe,new ya({color:d}));this.cone.matrixAutoUpdate=!1;this.add(this.cone);this.setDirection(a);this.setLength(c,e,f)}function Ld(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 E;a.addAttribute("position",new B(b,3));a.addAttribute("color",new B([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],3));b=new ea({vertexColors:2});Q.call(this,a,b)}function re(){var a=0,b=0,c=0,d=0;return{initCatmullRom:function(e,f,g,h,k){e=k*(g-e);h=k*
13834 (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,m,q){e=((f-e)/k-(g-e)/(k+m)+(g-f)/m)*m;h=((g-f)/m-(h-f)/(m+q)+(h-g)/q)*m;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 La(a){this.arcLengthDivisions=200;2>a.length&&console.warn("THREE.CatmullRomCurve3: Points array needs at least two entries.");this.points=a||[];this.closed=!1}function bd(a,b,c,d){this.arcLengthDivisions=200;this.v0=a;this.v1=b;this.v2=
13835 c;this.v3=d}function cd(a,b,c){this.arcLengthDivisions=200;this.v0=a;this.v1=b;this.v2=c}function dd(a,b){this.arcLengthDivisions=200;this.v1=a;this.v2=b}function Md(a,b,c,d,e,f){Va.call(this,a,b,c,c,d,e,f)}function cf(a){console.warn("THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.");La.call(this,a);this.type="catmullrom";this.closed=!0}function df(a){console.warn("THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.");La.call(this,a);this.type=
13836 "catmullrom"}function se(a){console.warn("THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.");La.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});void 0===Function.prototype.name&&Object.defineProperty(Function.prototype,"name",{get:function(){return this.toString().match(/^\s*function\s*([^\(\s]*)/)[1]}});
13837 void 0===Object.assign&&function(){Object.assign=function(a){if(void 0===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(xa.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)},
13838 hasEventListener:function(a,b){if(void 0===this._listeners)return!1;var c=this._listeners;return void 0!==c[a]&&-1!==c[a].indexOf(b)},removeEventListener:function(a,b){if(void 0!==this._listeners){var c=this._listeners[a];if(void 0!==c){var d=c.indexOf(b);-1!==d&&c.splice(d,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 Y={DEG2RAD:Math.PI/180,RAD2DEG:180/
13839 Math.PI,generateUUID:function(){var a="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),b=Array(36),c=0,d;return function(){for(var e=0;36>e;e++)8===e||13===e||18===e||23===e?b[e]="-":14===e?b[e]="4":(2>=c&&(c=33554432+16777216*Math.random()|0),d=c&15,c>>=4,b[e]=a[19===e?d&3|8:d]);return b.join("")}}(),clamp:function(a,b,c){return Math.max(b,Math.min(c,a))},euclideanModulo:function(a,b){return(a%b+b)%b},mapLinear:function(a,b,c,d,e){return d+(a-b)*(e-d)/(c-b)},lerp:function(a,
13840 b,c){return(1-c)*a+c*b},smoothstep:function(a,b,c){if(a<=b)return 0;if(a>=c)return 1;a=(a-b)/(c-b);return a*a*(3-2*a)},smootherstep:function(a,b,c){if(a<=b)return 0;if(a>=c)return 1;a=(a-b)/(c-b);return a*a*a*(a*(6*a-15)+10)},randInt:function(a,b){return a+Math.floor(Math.random()*(b-a+1))},randFloat:function(a,b){return a+Math.random()*(b-a)},randFloatSpread:function(a){return a*(.5-Math.random())},degToRad:function(a){return a*Y.DEG2RAD},radToDeg:function(a){return a*Y.RAD2DEG},isPowerOfTwo:function(a){return 0===
13841 (a&a-1)&&0!==a},nearestPowerOfTwo:function(a){return Math.pow(2,Math.round(Math.log(a)/Math.LN2))},nextPowerOfTwo:function(a){a--;a|=a>>1;a|=a>>2;a|=a>>4;a|=a>>8;a|=a>>16;a++;return a}};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=
13842 a;return this},setY:function(a){this.y=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y)},copy:function(a){this.x=a.x;this.y=a.y;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),
13843 this.addVectors(a,b);this.x+=a.x;this.y+=a.y;return this},addScalar:function(a){this.x+=a;this.y+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;return this},subScalar:function(a){this.x-=a;this.y-=a;return this},
13844 subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;return this},multiply:function(a){this.x*=a.x;this.y*=a.y;return this},multiplyScalar:function(a){this.x*=a;this.y*=a;return this},divide:function(a){this.x/=a.x;this.y/=a.y;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);return this},clamp:function(a,b){this.x=Math.max(a.x,
13845 Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));return this},clampScalar:function(){var a=new C,b=new C;return function(c,d){a.set(c,c);b.set(d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.divideScalar(c||1).multiplyScalar(Math.max(a,Math.min(b,c)))},floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);return this},round:function(){this.x=Math.round(this.x);
13846 this.y=Math.round(this.y);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);return this},negate:function(){this.x=-this.x;this.y=-this.y;return this},dot:function(a){return this.x*a.x+this.y*a.y},lengthSq:function(){return this.x*this.x+this.y*this.y},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)},normalize:function(){return this.divideScalar(this.length()||
13847 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},distanceToManhattan:function(a){return Math.abs(this.x-a.x)+Math.abs(this.y-a.y)},setLength:function(a){return this.normalize().multiplyScalar(a)},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+=(a.y-this.y)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,
13848 a).multiplyScalar(c).add(a)},equals:function(a){return a.x===this.x&&a.y===this.y},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;return a},fromBufferAttribute:function(a,b,c){void 0!==c&&console.warn("THREE.Vector2: offset has been removed from .fromBufferAttribute().");this.x=a.getX(b);this.y=a.getY(b);return this},rotateAround:function(a,b){var c=Math.cos(b),d=Math.sin(b),e=this.x-
13849 a.x,f=this.y-a.y;this.x=e*c-f*d+a.x;this.y=e*d+f*c+a.y;return this}});var hf=0;ba.DEFAULT_IMAGE=void 0;ba.DEFAULT_MAPPING=300;Object.defineProperty(ba.prototype,"needsUpdate",{set:function(a){!0===a&&this.version++}});Object.assign(ba.prototype,xa.prototype,{constructor:ba,isTexture:!0,clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.name=a.name;this.image=a.image;this.mipmaps=a.mipmaps.slice(0);this.mapping=a.mapping;this.wrapS=a.wrapS;this.wrapT=a.wrapT;this.magFilter=
13850 a.magFilter;this.minFilter=a.minFilter;this.anisotropy=a.anisotropy;this.format=a.format;this.type=a.type;this.offset.copy(a.offset);this.repeat.copy(a.repeat);this.generateMipmaps=a.generateMipmaps;this.premultiplyAlpha=a.premultiplyAlpha;this.flipY=a.flipY;this.unpackAlignment=a.unpackAlignment;this.encoding=a.encoding;return this},toJSON:function(a){if(void 0!==a.textures[this.uuid])return a.textures[this.uuid];var b={metadata:{version:4.5,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,
13851 name:this.name,mapping:this.mapping,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],wrap:[this.wrapS,this.wrapT],minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY};if(void 0!==this.image){var c=this.image;void 0===c.uuid&&(c.uuid=Y.generateUUID());if(void 0===a.images[c.uuid]){var d=a.images,e=c.uuid,f=c.uuid,g;void 0!==c.toDataURL?g=c:(g=document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),g.width=c.width,g.height=
13852 c.height,g.getContext("2d").drawImage(c,0,0,c.width,c.height));g=2048<g.width||2048<g.height?g.toDataURL("image/jpeg",.6):g.toDataURL("image/png");d[e]={uuid:f,url:g}}b.image=c.uuid}return a.textures[this.uuid]=b},dispose:function(){this.dispatchEvent({type:"dispose"})},transformUv:function(a){if(300===this.mapping){a.multiply(this.repeat);a.add(this.offset);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)%
13853 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)%2)?Math.ceil(a.y)-a.y:a.y-Math.floor(a.y)}this.flipY&&(a.y=1-a.y)}}});Object.assign(fa.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},
13854 setZ:function(a){this.z=a;return this},setW:function(a){this.w=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;case 2:this.z=b;break;case 3:this.w=b;break;default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y,this.z,
13855 this.w)},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;this.w=void 0!==a.w?a.w:1;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b);this.x+=a.x;this.y+=a.y;this.z+=a.z;this.w+=a.w;return this},addScalar:function(a){this.x+=a;this.y+=a;this.z+=a;this.w+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;this.w=a.w+b.w;return this},addScaledVector:function(a,
13856 b){this.x+=a.x*b;this.y+=a.y*b;this.z+=a.z*b;this.w+=a.w*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;this.z-=a.z;this.w-=a.w;return this},subScalar:function(a){this.x-=a;this.y-=a;this.z-=a;this.w-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;this.w=a.w-b.w;return this},multiplyScalar:function(a){this.x*=
13857 a;this.y*=a;this.z*=a;this.w*=a;return this},applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z,e=this.w;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d+a[12]*e;this.y=a[1]*b+a[5]*c+a[9]*d+a[13]*e;this.z=a[2]*b+a[6]*c+a[10]*d+a[14]*e;this.w=a[3]*b+a[7]*c+a[11]*d+a[15]*e;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},setAxisAngleFromQuaternion:function(a){this.w=2*Math.acos(a.w);var b=Math.sqrt(1-a.w*a.w);1E-4>b?(this.x=1,this.z=this.y=0):(this.x=a.x/b,this.y=a.y/b,this.z=a.z/
13858 b);return this},setAxisAngleFromRotationMatrix:function(a){var b,c,d;a=a.elements;var e=a[0];d=a[4];var f=a[8],g=a[1],h=a[5],k=a[9];c=a[2];b=a[6];var m=a[10];if(.01>Math.abs(d-g)&&.01>Math.abs(f-c)&&.01>Math.abs(k-b)){if(.1>Math.abs(d+g)&&.1>Math.abs(f+c)&&.1>Math.abs(k+b)&&.1>Math.abs(e+h+m-3))return this.set(1,0,0,0),this;a=Math.PI;e=(e+1)/2;h=(h+1)/2;m=(m+1)/2;d=(d+g)/4;f=(f+c)/4;k=(k+b)/4;e>h&&e>m?.01>e?(b=0,d=c=.707106781):(b=Math.sqrt(e),c=d/b,d=f/b):h>m?.01>h?(b=.707106781,c=0,d=.707106781):
13859 (c=Math.sqrt(h),b=d/c,d=k/c):.01>m?(c=b=.707106781,d=0):(d=Math.sqrt(m),b=f/d,c=k/d);this.set(b,c,d,a);return this}a=Math.sqrt((b-k)*(b-k)+(f-c)*(f-c)+(g-d)*(g-d));.001>Math.abs(a)&&(a=1);this.x=(b-k)/a;this.y=(f-c)/a;this.z=(g-d)/a;this.w=Math.acos((e+h+m-1)/2);return this},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);this.z=Math.min(this.z,a.z);this.w=Math.min(this.w,a.w);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);this.z=Math.max(this.z,
13860 a.z);this.w=Math.max(this.w,a.w);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));this.z=Math.max(a.z,Math.min(b.z,this.z));this.w=Math.max(a.w,Math.min(b.w,this.w));return this},clampScalar:function(){var a,b;return function(c,d){void 0===a&&(a=new fa,b=new fa);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,
13861 c)))},floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);this.z=Math.floor(this.z);this.w=Math.floor(this.w);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);this.w=Math.ceil(this.w);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);this.z=Math.round(this.z);this.w=Math.round(this.w);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):
13862 Math.floor(this.y);this.z=0>this.z?Math.ceil(this.z):Math.floor(this.z);this.w=0>this.w?Math.ceil(this.w):Math.floor(this.w);return this},negate:function(){this.x=-this.x;this.y=-this.y;this.z=-this.z;this.w=-this.w;return this},dot:function(a){return this.x*a.x+this.y*a.y+this.z*a.z+this.w*a.w},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},lengthManhattan:function(){return Math.abs(this.x)+
13863 Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)},normalize:function(){return this.divideScalar(this.length()||1)},setLength:function(a){return this.normalize().multiplyScalar(a)},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+=(a.y-this.y)*b;this.z+=(a.z-this.z)*b;this.w+=(a.w-this.w)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},equals:function(a){return a.x===this.x&&a.y===this.y&&a.z===this.z&&a.w===this.w},fromArray:function(a,b){void 0===
13864 b&&(b=0);this.x=a[b];this.y=a[b+1];this.z=a[b+2];this.w=a[b+3];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;a[b+2]=this.z;a[b+3]=this.w;return a},fromBufferAttribute:function(a,b,c){void 0!==c&&console.warn("THREE.Vector4: offset has been removed from .fromBufferAttribute().");this.x=a.getX(b);this.y=a.getY(b);this.z=a.getZ(b);this.w=a.getW(b);return this}});Object.assign(Cb.prototype,xa.prototype,{isWebGLRenderTarget:!0,setSize:function(a,b){if(this.width!==
13865 a||this.height!==b)this.width=a,this.height=b,this.dispose();this.viewport.set(0,0,a,b);this.scissor.set(0,0,a,b)},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.width=a.width;this.height=a.height;this.viewport.copy(a.viewport);this.texture=a.texture.clone();this.depthBuffer=a.depthBuffer;this.stencilBuffer=a.stencilBuffer;this.depthTexture=a.depthTexture;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Db.prototype=Object.create(Cb.prototype);
13866 Db.prototype.constructor=Db;Db.prototype.isWebGLRenderTargetCube=!0;Object.assign(oa,{slerp:function(a,b,c,d){return c.copy(a).slerp(b,d)},slerpFlat:function(a,b,c,d,e,f,g){var h=c[d+0],k=c[d+1],m=c[d+2];c=c[d+3];d=e[f+0];var q=e[f+1],l=e[f+2];e=e[f+3];if(c!==e||h!==d||k!==q||m!==l){f=1-g;var p=h*d+k*q+m*l+c*e,r=0<=p?1:-1,n=1-p*p;n>Number.EPSILON&&(n=Math.sqrt(n),p=Math.atan2(n,p*r),f=Math.sin(f*p)/n,g=Math.sin(g*p)/n);r*=g;h=h*f+d*r;k=k*f+q*r;m=m*f+l*r;c=c*f+e*r;f===1-g&&(g=1/Math.sqrt(h*h+k*k+m*
13867 m+c*c),h*=g,k*=g,m*=g,c*=g)}a[b]=h;a[b+1]=k;a[b+2]=m;a[b+3]=c}});Object.defineProperties(oa.prototype,{x:{get:function(){return this._x},set:function(a){this._x=a;this.onChangeCallback()}},y:{get:function(){return this._y},set:function(a){this._y=a;this.onChangeCallback()}},z:{get:function(){return this._z},set:function(a){this._z=a;this.onChangeCallback()}},w:{get:function(){return this._w},set:function(a){this._w=a;this.onChangeCallback()}}});Object.assign(oa.prototype,{set:function(a,b,c,d){this._x=
13868 a;this._y=b;this._z=c;this._w=d;this.onChangeCallback();return this},clone:function(){return new this.constructor(this._x,this._y,this._z,this._w)},copy:function(a){this._x=a.x;this._y=a.y;this._z=a.z;this._w=a.w;this.onChangeCallback();return this},setFromEuler:function(a,b){if(!a||!a.isEuler)throw Error("THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.");var c=a._x,d=a._y,e=a._z,f=a.order,g=Math.cos,h=Math.sin,k=g(c/2),m=g(d/2),g=g(e/2),c=h(c/2),d=
13869 h(d/2),e=h(e/2);"XYZ"===f?(this._x=c*m*g+k*d*e,this._y=k*d*g-c*m*e,this._z=k*m*e+c*d*g,this._w=k*m*g-c*d*e):"YXZ"===f?(this._x=c*m*g+k*d*e,this._y=k*d*g-c*m*e,this._z=k*m*e-c*d*g,this._w=k*m*g+c*d*e):"ZXY"===f?(this._x=c*m*g-k*d*e,this._y=k*d*g+c*m*e,this._z=k*m*e+c*d*g,this._w=k*m*g-c*d*e):"ZYX"===f?(this._x=c*m*g-k*d*e,this._y=k*d*g+c*m*e,this._z=k*m*e-c*d*g,this._w=k*m*g+c*d*e):"YZX"===f?(this._x=c*m*g+k*d*e,this._y=k*d*g+c*m*e,this._z=k*m*e-c*d*g,this._w=k*m*g-c*d*e):"XZY"===f&&(this._x=c*m*g-
13870 k*d*e,this._y=k*d*g-c*m*e,this._z=k*m*e+c*d*g,this._w=k*m*g+c*d*e);if(!1!==b)this.onChangeCallback();return this},setFromAxisAngle:function(a,b){var c=b/2,d=Math.sin(c);this._x=a.x*d;this._y=a.y*d;this._z=a.z*d;this._w=Math.cos(c);this.onChangeCallback();return this},setFromRotationMatrix:function(a){var b=a.elements,c=b[0];a=b[4];var d=b[8],e=b[1],f=b[5],g=b[9],h=b[2],k=b[6],b=b[10],m=c+f+b;0<m?(c=.5/Math.sqrt(m+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+
13871 c-f-b),this._w=(k-g)/c,this._x=.25*c,this._y=(a+e)/c,this._z=(d+h)/c):f>b?(c=2*Math.sqrt(1+f-c-b),this._w=(d-h)/c,this._x=(a+e)/c,this._y=.25*c,this._z=(g+k)/c):(c=2*Math.sqrt(1+b-c-f),this._w=(e-a)/c,this._x=(d+h)/c,this._y=(g+k)/c,this._z=.25*c);this.onChangeCallback();return this},setFromUnitVectors:function(){var a=new n,b;return function(c,d){void 0===a&&(a=new n);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=
13872 a.y;this._z=a.z;this._w=b;return this.normalize()}}(),inverse:function(){return this.conjugate().normalize()},conjugate:function(){this._x*=-1;this._y*=-1;this._z*=-1;this.onChangeCallback();return this},dot:function(a){return this._x*a._x+this._y*a._y+this._z*a._z+this._w*a._w},lengthSq:function(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w},length:function(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)},normalize:function(){var a=this.length();
13873 0===a?(this._z=this._y=this._x=0,this._w=1):(a=1/a,this._x*=a,this._y*=a,this._z*=a,this._w*=a);this.onChangeCallback();return this},multiply:function(a,b){return void 0!==b?(console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),this.multiplyQuaternions(a,b)):this.multiplyQuaternions(this,a)},premultiply:function(a){return this.multiplyQuaternions(a,this)},multiplyQuaternions:function(a,b){var c=a._x,d=a._y,e=a._z,f=a._w,g=b._x,h=b._y,
13874 k=b._z,m=b._w;this._x=c*m+f*g+d*k-e*h;this._y=d*m+f*h+e*g-c*k;this._z=e*m+f*k+c*h-d*g;this._w=f*m-c*g-d*h-e*k;this.onChangeCallback();return this},slerp:function(a,b){if(0===b)return this;if(1===b)return this.copy(a);var c=this._x,d=this._y,e=this._z,f=this._w,g=f*a._w+c*a._x+d*a._y+e*a._z;0>g?(this._w=-a._w,this._x=-a._x,this._y=-a._y,this._z=-a._z,g=-g):this.copy(a);if(1<=g)return this._w=f,this._x=c,this._y=d,this._z=e,this;var h=Math.sqrt(1-g*g);if(.001>Math.abs(h))return this._w=.5*(f+this._w),
13875 this._x=.5*(c+this._x),this._y=.5*(d+this._y),this._z=.5*(e+this._z),this;var k=Math.atan2(h,g),g=Math.sin((1-b)*k)/h,h=Math.sin(b*k)/h;this._w=f*g+this._w*h;this._x=c*g+this._x*h;this._y=d*g+this._y*h;this._z=e*g+this._z*h;this.onChangeCallback();return this},equals:function(a){return a._x===this._x&&a._y===this._y&&a._z===this._z&&a._w===this._w},fromArray:function(a,b){void 0===b&&(b=0);this._x=a[b];this._y=a[b+1];this._z=a[b+2];this._w=a[b+3];this.onChangeCallback();return this},toArray:function(a,
13876 b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this._x;a[b+1]=this._y;a[b+2]=this._z;a[b+3]=this._w;return a},onChange:function(a){this.onChangeCallback=a;return this},onChangeCallback:function(){}});Object.assign(n.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=
13877 b;break;case 1:this.y=b;break;case 2:this.z=b;break;default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y,this.z)},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),
13878 this.addVectors(a,b);this.x+=a.x;this.y+=a.y;this.z+=a.z;return this},addScalar:function(a){this.x+=a;this.y+=a;this.z+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;this.z+=a.z*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;this.z-=a.z;
13879 return this},subScalar:function(a){this.x-=a;this.y-=a;this.z-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;return this},multiply:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."),this.multiplyVectors(a,b);this.x*=a.x;this.y*=a.y;this.z*=a.z;return this},multiplyScalar:function(a){this.x*=a;this.y*=a;this.z*=a;return this},multiplyVectors:function(a,b){this.x=a.x*
13880 b.x;this.y=a.y*b.y;this.z=a.z*b.z;return this},applyEuler:function(){var a=new oa;return function(b){b&&b.isEuler||console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.");return this.applyQuaternion(a.setFromEuler(b))}}(),applyAxisAngle:function(){var a=new oa;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]*
13881 b+a[4]*c+a[7]*d;this.z=a[2]*b+a[5]*c+a[8]*d;return this},applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;var e=1/(a[3]*b+a[7]*c+a[11]*d+a[15]);this.x=(a[0]*b+a[4]*c+a[8]*d+a[12])*e;this.y=(a[1]*b+a[5]*c+a[9]*d+a[13])*e;this.z=(a[2]*b+a[6]*c+a[10]*d+a[14])*e;return this},applyQuaternion:function(a){var b=this.x,c=this.y,d=this.z,e=a.x,f=a.y,g=a.z;a=a.w;var h=a*b+f*d-g*c,k=a*c+g*b-e*d,m=a*d+e*c-f*b,b=-e*b-f*c-g*d;this.x=h*a+b*-e+k*-g-m*-f;this.y=k*a+b*-f+m*-e-h*-g;this.z=m*a+b*
13882 -g+h*-f-k*-e;return this},project:function(){var a=new K;return function(b){a.multiplyMatrices(b.projectionMatrix,a.getInverse(b.matrixWorld));return this.applyMatrix4(a)}}(),unproject:function(){var a=new K;return function(b){a.multiplyMatrices(b.matrixWorld,a.getInverse(b.projectionMatrix));return this.applyMatrix4(a)}}(),transformDirection:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d;this.y=a[1]*b+a[5]*c+a[9]*d;this.z=a[2]*b+a[6]*c+a[10]*d;return this.normalize()},
13883 divide:function(a){this.x/=a.x;this.y/=a.y;this.z/=a.z;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);this.z=Math.min(this.z,a.z);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);this.z=Math.max(this.z,a.z);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));this.z=Math.max(a.z,Math.min(b.z,this.z));return this},
13884 clampScalar:function(){var a=new n,b=new n;return function(c,d){a.set(c,c,c);b.set(d,d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.divideScalar(c||1).multiplyScalar(Math.max(a,Math.min(b,c)))},floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);this.z=Math.floor(this.z);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);
13885 this.z=Math.round(this.z);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);this.z=0>this.z?Math.ceil(this.z):Math.floor(this.z);return this},negate:function(){this.x=-this.x;this.y=-this.y;this.z=-this.z;return this},dot:function(a){return this.x*a.x+this.y*a.y+this.z*a.z},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*
13886 this.z)},lengthManhattan:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)},normalize:function(){return this.divideScalar(this.length()||1)},setLength:function(a){return this.normalize().multiplyScalar(a)},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+=(a.y-this.y)*b;this.z+=(a.z-this.z)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},cross:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),
13887 this.crossVectors(a,b);var c=this.x,d=this.y,e=this.z;this.x=d*a.z-e*a.y;this.y=e*a.x-c*a.z;this.z=c*a.y-d*a.x;return this},crossVectors:function(a,b){var c=a.x,d=a.y,e=a.z,f=b.x,g=b.y,h=b.z;this.x=d*h-e*g;this.y=e*f-c*h;this.z=c*g-d*f;return this},projectOnVector:function(a){var b=a.dot(this)/a.lengthSq();return this.copy(a).multiplyScalar(b)},projectOnPlane:function(){var a=new n;return function(b){a.copy(this).projectOnVector(b);return this.sub(a)}}(),reflect:function(){var a=new n;return function(b){return this.sub(a.copy(b).multiplyScalar(2*
13888 this.dot(b)))}}(),angleTo:function(a){a=this.dot(a)/Math.sqrt(this.lengthSq()*a.lengthSq());return Math.acos(Y.clamp(a,-1,1))},distanceTo:function(a){return Math.sqrt(this.distanceToSquared(a))},distanceToSquared:function(a){var b=this.x-a.x,c=this.y-a.y;a=this.z-a.z;return b*b+c*c+a*a},distanceToManhattan:function(a){return Math.abs(this.x-a.x)+Math.abs(this.y-a.y)+Math.abs(this.z-a.z)},setFromSpherical:function(a){var b=Math.sin(a.phi)*a.radius;this.x=b*Math.sin(a.theta);this.y=Math.cos(a.phi)*
13889 a.radius;this.z=b*Math.cos(a.theta);return this},setFromCylindrical:function(a){this.x=a.radius*Math.sin(a.theta);this.y=a.y;this.z=a.radius*Math.cos(a.theta);return this},setFromMatrixPosition:function(a){a=a.elements;this.x=a[12];this.y=a[13];this.z=a[14];return this},setFromMatrixScale:function(a){var b=this.setFromMatrixColumn(a,0).length(),c=this.setFromMatrixColumn(a,1).length();a=this.setFromMatrixColumn(a,2).length();this.x=b;this.y=c;this.z=a;return this},setFromMatrixColumn:function(a,b){return this.fromArray(a.elements,
13890 4*b)},equals:function(a){return a.x===this.x&&a.y===this.y&&a.z===this.z},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];this.z=a[b+2];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;a[b+2]=this.z;return a},fromBufferAttribute:function(a,b,c){void 0!==c&&console.warn("THREE.Vector3: offset has been removed from .fromBufferAttribute().");this.x=a.getX(b);this.y=a.getY(b);this.z=a.getZ(b);return this}});Object.assign(K.prototype,
13891 {isMatrix4:!0,set:function(a,b,c,d,e,f,g,h,k,m,q,l,p,r,n,t){var y=this.elements;y[0]=a;y[4]=b;y[8]=c;y[12]=d;y[1]=e;y[5]=f;y[9]=g;y[13]=h;y[2]=k;y[6]=m;y[10]=q;y[14]=l;y[3]=p;y[7]=r;y[11]=n;y[15]=t;return this},identity:function(){this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return this},clone:function(){return(new K).fromArray(this.elements)},copy:function(a){var b=this.elements;a=a.elements;b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];b[5]=a[5];b[6]=a[6];b[7]=a[7];b[8]=a[8];b[9]=a[9];b[10]=a[10];
13892 b[11]=a[11];b[12]=a[12];b[13]=a[13];b[14]=a[14];b[15]=a[15];return this},copyPosition:function(a){var b=this.elements;a=a.elements;b[12]=a[12];b[13]=a[13];b[14]=a[14];return this},extractBasis:function(a,b,c){a.setFromMatrixColumn(this,0);b.setFromMatrixColumn(this,1);c.setFromMatrixColumn(this,2);return this},makeBasis:function(a,b,c){this.set(a.x,b.x,c.x,0,a.y,b.y,c.y,0,a.z,b.z,c.z,0,0,0,0,1);return this},extractRotation:function(){var a=new n;return function(b){var c=this.elements,d=b.elements,
13893 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.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");var b=this.elements,c=a.x,d=a.y,e=a.z,f=Math.cos(c),c=Math.sin(c),g=Math.cos(d),d=Math.sin(d),
13894 h=Math.cos(e),e=Math.sin(e);if("XYZ"===a.order){a=f*h;var k=f*e,m=c*h,q=c*e;b[0]=g*h;b[4]=-g*e;b[8]=d;b[1]=k+m*d;b[5]=a-q*d;b[9]=-c*g;b[2]=q-a*d;b[6]=m+k*d;b[10]=f*g}else"YXZ"===a.order?(a=g*h,k=g*e,m=d*h,q=d*e,b[0]=a+q*c,b[4]=m*c-k,b[8]=f*d,b[1]=f*e,b[5]=f*h,b[9]=-c,b[2]=k*c-m,b[6]=q+a*c,b[10]=f*g):"ZXY"===a.order?(a=g*h,k=g*e,m=d*h,q=d*e,b[0]=a-q*c,b[4]=-f*e,b[8]=m+k*c,b[1]=k+m*c,b[5]=f*h,b[9]=q-a*c,b[2]=-f*d,b[6]=c,b[10]=f*g):"ZYX"===a.order?(a=f*h,k=f*e,m=c*h,q=c*e,b[0]=g*h,b[4]=m*d-k,b[8]=a*
13895 d+q,b[1]=g*e,b[5]=q*d+a,b[9]=k*d-m,b[2]=-d,b[6]=c*g,b[10]=f*g):"YZX"===a.order?(a=f*g,k=f*d,m=c*g,q=c*d,b[0]=g*h,b[4]=q-a*e,b[8]=m*e+k,b[1]=e,b[5]=f*h,b[9]=-c*h,b[2]=-d*h,b[6]=k*e+m,b[10]=a-q*e):"XZY"===a.order&&(a=f*g,k=f*d,m=c*g,q=c*d,b[0]=g*h,b[4]=-e,b[8]=d*h,b[1]=a*e+q,b[5]=f*h,b[9]=k*e-m,b[2]=m*e-k,b[6]=c*h,b[10]=q*e+a);b[3]=0;b[7]=0;b[11]=0;b[12]=0;b[13]=0;b[14]=0;b[15]=1;return this},makeRotationFromQuaternion:function(a){var b=this.elements,c=a._x,d=a._y,e=a._z,f=a._w,g=c+c,h=d+d,k=e+e;a=
13896 c*g;var m=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]=m-f;b[8]=c+h;b[1]=m+f;b[5]=1-(a+e);b[9]=d-g;b[2]=c-h;b[6]=d+g;b[10]=1-(a+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 n,b=new n,c=new n;return function(d,e,f){var g=this.elements;c.subVectors(d,e);0===c.lengthSq()&&(c.z=1);c.normalize();a.crossVectors(f,c);0===a.lengthSq()&&(1===Math.abs(f.z)?c.x+=1E-4:c.z+=1E-4,c.normalize(),a.crossVectors(f,c));a.normalize();b.crossVectors(c,
13897 a);g[0]=a.x;g[4]=b.x;g[8]=c.x;g[1]=a.y;g[5]=b.y;g[9]=c.y;g[2]=a.z;g[6]=b.z;g[10]=c.z;return this}}(),multiply:function(a,b){return void 0!==b?(console.warn("THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead."),this.multiplyMatrices(a,b)):this.multiplyMatrices(this,a)},premultiply:function(a){return this.multiplyMatrices(a,this)},multiplyMatrices:function(a,b){var c=a.elements,d=b.elements,e=this.elements,f=c[0],g=c[4],h=c[8],k=c[12],m=c[1],q=c[5],l=c[9],
13898 p=c[13],r=c[2],n=c[6],t=c[10],y=c[14],x=c[3],u=c[7],H=c[11],c=c[15],w=d[0],I=d[4],W=d[8],D=d[12],O=d[1],B=d[5],F=d[9],C=d[13],z=d[2],E=d[6],G=d[10],K=d[14],P=d[3],M=d[7],V=d[11],d=d[15];e[0]=f*w+g*O+h*z+k*P;e[4]=f*I+g*B+h*E+k*M;e[8]=f*W+g*F+h*G+k*V;e[12]=f*D+g*C+h*K+k*d;e[1]=m*w+q*O+l*z+p*P;e[5]=m*I+q*B+l*E+p*M;e[9]=m*W+q*F+l*G+p*V;e[13]=m*D+q*C+l*K+p*d;e[2]=r*w+n*O+t*z+y*P;e[6]=r*I+n*B+t*E+y*M;e[10]=r*W+n*F+t*G+y*V;e[14]=r*D+n*C+t*K+y*d;e[3]=x*w+u*O+H*z+c*P;e[7]=x*I+u*B+H*E+c*M;e[11]=x*W+u*F+H*G+
13899 c*V;e[15]=x*D+u*C+H*K+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 n;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=this.elements,b=a[0],c=a[4],d=a[8],e=a[12],f=
13900 a[1],g=a[5],h=a[9],k=a[13],m=a[2],q=a[6],l=a[10],p=a[14];return a[3]*(+e*h*q-d*k*q-e*g*l+c*k*l+d*g*p-c*h*p)+a[7]*(+b*h*p-b*k*l+e*f*l-d*f*p+d*k*m-e*h*m)+a[11]*(+b*k*q-b*g*p-e*f*q+c*f*p+e*g*m-c*k*m)+a[15]*(-d*g*m-b*h*q+b*g*l+d*f*q-c*f*l+c*h*m)},transpose:function(){var a=this.elements,b;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=this.elements;b[12]=
13901 a.x;b[13]=a.y;b[14]=a.z;return this},getInverse:function(a,b){var c=this.elements,d=a.elements,e=d[0],f=d[1],g=d[2],h=d[3],k=d[4],m=d[5],q=d[6],l=d[7],p=d[8],r=d[9],n=d[10],t=d[11],y=d[12],x=d[13],u=d[14],d=d[15],H=r*u*l-x*n*l+x*q*t-m*u*t-r*q*d+m*n*d,w=y*n*l-p*u*l-y*q*t+k*u*t+p*q*d-k*n*d,I=p*x*l-y*r*l+y*m*t-k*x*t-p*m*d+k*r*d,W=y*r*q-p*x*q-y*m*n+k*x*n+p*m*u-k*r*u,D=e*H+f*w+g*I+h*W;if(0===D){if(!0===b)throw Error("THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0");console.warn("THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0");
13902 return this.identity()}D=1/D;c[0]=H*D;c[1]=(x*n*h-r*u*h-x*g*t+f*u*t+r*g*d-f*n*d)*D;c[2]=(m*u*h-x*q*h+x*g*l-f*u*l-m*g*d+f*q*d)*D;c[3]=(r*q*h-m*n*h-r*g*l+f*n*l+m*g*t-f*q*t)*D;c[4]=w*D;c[5]=(p*u*h-y*n*h+y*g*t-e*u*t-p*g*d+e*n*d)*D;c[6]=(y*q*h-k*u*h-y*g*l+e*u*l+k*g*d-e*q*d)*D;c[7]=(k*n*h-p*q*h+p*g*l-e*n*l-k*g*t+e*q*t)*D;c[8]=I*D;c[9]=(y*r*h-p*x*h-y*f*t+e*x*t+p*f*d-e*r*d)*D;c[10]=(k*x*h-y*m*h+y*f*l-e*x*l-k*f*d+e*m*d)*D;c[11]=(p*m*h-k*r*h-p*f*l+e*r*l+k*f*t-e*m*t)*D;c[12]=W*D;c[13]=(p*x*g-y*r*g+y*f*n-e*x*
13903 n-p*f*u+e*r*u)*D;c[14]=(y*m*g-k*x*g-y*f*q+e*x*q+k*f*u-e*m*u)*D;c[15]=(k*r*g-p*m*g+p*f*q-e*r*q-k*f*n+e*m*n)*D;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],a[8]*a[8]+a[9]*a[9]+a[10]*a[10]))},makeTranslation:function(a,b,c){this.set(1,
13904 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=Math.cos(b),d=Math.sin(b),e=1-c,f=a.x,g=a.y,h=a.z,k=e*f,m=e*g;this.set(k*f+c,k*
13905 g-d*h,k*h+d*g,0,k*g+d*h,m*g+c,m*h-d*f,0,k*h-d*g,m*h+d*f,e*h*h+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 n,b=new K;return function(c,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(),
13906 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,m=1/k;b.elements[0]*=c;b.elements[1]*=c;b.elements[2]*=c;b.elements[4]*=f;b.elements[5]*=f;b.elements[6]*=f;b.elements[8]*=m;b.elements[9]*=m;b.elements[10]*=m;d.setFromRotationMatrix(b);e.x=g;e.y=h;e.z=k;return this}}(),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.");
13907 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),m=1/(f-e);g[0]=2*h;g[4]=0;g[8]=0;g[12]=-((b+a)*h);g[1]=0;g[5]=2*k;g[9]=0;g[13]=-((c+d)*k);g[2]=0;g[6]=0;g[10]=-2*m;g[14]=-((f+e)*m);g[3]=0;g[7]=0;g[11]=0;g[15]=1;return this},equals:function(a){var b=this.elements;
13908 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}});db.prototype=Object.create(ba.prototype);
13909 db.prototype.constructor=db;db.prototype.isDataTexture=!0;Xa.prototype=Object.create(ba.prototype);Xa.prototype.constructor=Xa;Xa.prototype.isCubeTexture=!0;Object.defineProperty(Xa.prototype,"images",{get:function(){return this.image},set:function(a){this.image=a}});var Ce=new ba,De=new Xa,xe=[],ze=[],Be=new Float32Array(16),Ae=new Float32Array(9);He.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 Pd=/([\w\d_]+)(\])?(\[|\.)?/g;
13910 eb.prototype.setValue=function(a,b,c){b=this.map[b];void 0!==b&&b.setValue(a,c,this.renderer)};eb.prototype.setOptional=function(a,b,c){b=b[c];void 0!==b&&this.setValue(a,c,b)};eb.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)}};eb.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 lg={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,
13911 beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,
13912 darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,
13913 khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,
13914 mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,
13915 peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,
13916 yellow:16776960,yellowgreen:10145074};Object.assign(G.prototype,{isColor:!0,r:1,g:1,b:1,set:function(a){a&&a.isColor?this.copy(a):"number"===typeof a?this.setHex(a):"string"===typeof a&&this.setStyle(a);return this},setScalar:function(a){this.b=this.g=this.r=a;return this},setHex:function(a){a=Math.floor(a);this.r=(a>>16&255)/255;this.g=(a>>8&255)/255;this.b=(a&255)/255;return this},setRGB:function(a,b,c){this.r=a;this.g=b;this.b=c;return this},setHSL:function(){function a(a,c,d){0>d&&(d+=1);1<d&&
13917 --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=Y.euclideanModulo(b,1);c=Y.clamp(c,0,1);d=Y.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=
13918 /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d))return this.r=Math.min(255,parseInt(c[1],10))/255,this.g=Math.min(255,parseInt(c[2],10))/255,this.b=Math.min(255,parseInt(c[3],10))/255,b(c[5]),this;if(c=/^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d))return this.r=Math.min(100,parseInt(c[1],10))/100,this.g=Math.min(100,parseInt(c[2],10))/100,this.b=Math.min(100,parseInt(c[3],10))/100,b(c[5]),this;break;case "hsl":case "hsla":if(c=/^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d)){var d=
13919 parseFloat(c[1])/360,e=parseInt(c[2],10)/100,f=parseInt(c[3],10)/100;b(c[5]);return this.setHSL(d,e,f)}}}else if(c=/^\#([A-Fa-f0-9]+)$/.exec(a)){c=c[1];d=c.length;if(3===d)return this.r=parseInt(c.charAt(0)+c.charAt(0),16)/255,this.g=parseInt(c.charAt(1)+c.charAt(1),16)/255,this.b=parseInt(c.charAt(2)+c.charAt(2),16)/255,this;if(6===d)return this.r=parseInt(c.charAt(0)+c.charAt(1),16)/255,this.g=parseInt(c.charAt(2)+c.charAt(3),16)/255,this.b=parseInt(c.charAt(4)+c.charAt(5),16)/255,this}a&&0<a.length&&
13920 (c=lg[a],void 0!==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);var c=0<b?1/b:1;this.r=Math.pow(a.r,c);this.g=Math.pow(a.g,c);this.b=Math.pow(a.b,c);return this},
13921 convertGammaToLinear:function(){var a=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===
13922 e)f=g=0;else{var k=e-f,f=.5>=h?k/(e+f):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},
13923 addScalar:function(a){this.r+=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,
13924 b){void 0===b&&(b=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 R={common:{diffuse:{value:new G(15658734)},opacity:{value:1},map:{value:null},offsetRepeat:{value:new fa(0,0,1,1)},specularMap:{value:null},alphaMap:{value:null},envMap:{value:null},flipEnvMap:{value:-1},reflectivity:{value:1},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},
13925 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},
13926 fogFar:{value:2E3},fogColor:{value:new G(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:[]},
13927 pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}}},points:{diffuse:{value:new G(15658734)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},offsetRepeat:{value:new fa(0,0,1,1)}}},Ca={merge:function(a){for(var b=
13928 {},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}},X={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",
13929 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",
13930 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 * transpose( 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",
13931 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",
13932 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",
13933 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",
13934 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 transpose( const in mat3 v ) {\n\tmat3 tmp;\n\ttmp[0] = vec3(v[0].x, v[1].x, v[2].x);\n\ttmp[1] = vec3(v[0].y, v[1].y, v[2].y);\n\ttmp[2] = vec3(v[0].z, v[1].z, v[2].z);\n\treturn tmp;\n}\n",
13935 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",
13936 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",
13937 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",
13938 envmap_fragment:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\tsampleUV.y = asin( flipNormal * reflectVec.y ) * RECIPROCAL_PI + 0.5;\n\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\tvec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\tenvColor = envMapTexelToLinear( envColor );\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif\n",
13939 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",
13940 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",
13941 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",
13942 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",
13943 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",
13944 lights_pars:"uniform vec3 ambientLightColor;\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\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 = saturate( reflectVec.y * 0.5 + 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",
13945 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",
13946 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",
13947 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",
13948 lights_template:"\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( 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",
13949 logdepthbuf_fragment:"#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#ifdef USE_LOGDEPTHBUF\n\tuniform float logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n#endif\n",logdepthbuf_pars_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n\tuniform float logDepthBufFC;\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGDEPTHBUF\n\tgl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t#else\n\t\tgl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n\t#endif\n#endif\n",
13950 map_fragment:"#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n",map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n",map_particle_fragment:"#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n",map_particle_pars_fragment:"#ifdef USE_MAP\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n#endif\n",
13951 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",
13952 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",
13953 normal_flip:"#ifdef DOUBLE_SIDED\n\tfloat flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n#else\n\tfloat flipNormal = 1.0;\n#endif\n",normal_fragment:"#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal ) * flipNormal;\n#endif\n#ifdef USE_NORMALMAP\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n",
13954 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",
13955 packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 1.0 - 2.0 * rgb.xyz;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\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",
13956 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",
13957 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 ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tfloat dp = ( length( lightToPosition ) - shadowBias ) / 1000.0;\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif\n",
13958 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",
13959 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",
13960 shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}\n",
13961 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",
13962 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",
13963 specularmap_fragment:"float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif",specularmap_pars_fragment:"#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",tonemapping_fragment:"#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n",tonemapping_pars_fragment:"#define saturate(a) clamp( a, 0.0, 1.0 )\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n\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",
13964 uv_pars_fragment:"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n#endif",uv_pars_vertex:"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n\tuniform vec4 offsetRepeat;\n#endif\n",
13965 uv_vertex:"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n#endif",uv2_pars_fragment:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif",uv2_pars_vertex:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif",
13966 uv2_vertex:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n#endif\n",cube_frag:"uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n}\n",
13967 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}\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",
13968 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",
13969 distanceRGBA_frag:"uniform vec3 lightPos;\nvarying vec4 vWorldPosition;\n#include <common>\n#include <packing>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tgl_FragColor = packDepthToRGBA( length( vWorldPosition.xyz - lightPos.xyz ) / 1000.0 );\n}\n",distanceRGBA_vert:"varying vec4 vWorldPosition;\n#include <common>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <skinbase_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition;\n}\n",
13970 equirect_frag:"uniform sampler2D tEquirect;\nuniform float tFlip;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n}\n",equirect_vert:"varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}\n",
13971 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",
13972 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",
13973 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 <normal_flip>\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",
13974 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",
13975 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 <normal_flip>\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",
13976 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",
13977 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_flip>\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",
13978 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",
13979 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_flip>\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",
13980 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",
13981 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_flip>\n\t#include <normal_fragment>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}\n",
13982 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",
13983 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",
13984 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",
13985 shadow_frag:"uniform float opacity;\n#include <common>\n#include <packing>\n#include <bsdfs>\n#include <lights_pars>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( 0.0, 0.0, 0.0, opacity * ( 1.0 - getShadowMask() ) );\n}\n",shadow_vert:"#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}\n"},$a={basic:{uniforms:Ca.merge([R.common,
13986 R.aomap,R.lightmap,R.fog]),vertexShader:X.meshbasic_vert,fragmentShader:X.meshbasic_frag},lambert:{uniforms:Ca.merge([R.common,R.aomap,R.lightmap,R.emissivemap,R.fog,R.lights,{emissive:{value:new G(0)}}]),vertexShader:X.meshlambert_vert,fragmentShader:X.meshlambert_frag},phong:{uniforms:Ca.merge([R.common,R.aomap,R.lightmap,R.emissivemap,R.bumpmap,R.normalmap,R.displacementmap,R.gradientmap,R.fog,R.lights,{emissive:{value:new G(0)},specular:{value:new G(1118481)},shininess:{value:30}}]),vertexShader:X.meshphong_vert,
13987 fragmentShader:X.meshphong_frag},standard:{uniforms:Ca.merge([R.common,R.aomap,R.lightmap,R.emissivemap,R.bumpmap,R.normalmap,R.displacementmap,R.roughnessmap,R.metalnessmap,R.fog,R.lights,{emissive:{value:new G(0)},roughness:{value:.5},metalness:{value:.5},envMapIntensity:{value:1}}]),vertexShader:X.meshphysical_vert,fragmentShader:X.meshphysical_frag},points:{uniforms:Ca.merge([R.points,R.fog]),vertexShader:X.points_vert,fragmentShader:X.points_frag},dashed:{uniforms:Ca.merge([R.common,R.fog,{scale:{value:1},
13988 dashSize:{value:1},totalSize:{value:2}}]),vertexShader:X.linedashed_vert,fragmentShader:X.linedashed_frag},depth:{uniforms:Ca.merge([R.common,R.displacementmap]),vertexShader:X.depth_vert,fragmentShader:X.depth_frag},normal:{uniforms:Ca.merge([R.common,R.bumpmap,R.normalmap,R.displacementmap,{opacity:{value:1}}]),vertexShader:X.normal_vert,fragmentShader:X.normal_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:X.cube_vert,fragmentShader:X.cube_frag},equirect:{uniforms:{tEquirect:{value:null},
13989 tFlip:{value:-1}},vertexShader:X.equirect_vert,fragmentShader:X.equirect_frag},distanceRGBA:{uniforms:{lightPos:{value:new n}},vertexShader:X.distanceRGBA_vert,fragmentShader:X.distanceRGBA_frag}};$a.physical={uniforms:Ca.merge([$a.standard.uniforms,{clearCoat:{value:0},clearCoatRoughness:{value:0}}]),vertexShader:X.meshphysical_vert,fragmentShader:X.meshphysical_frag};Object.assign(fd.prototype,{set:function(a,b){this.min.copy(a);this.max.copy(b);return this},setFromPoints:function(a){this.makeEmpty();
13990 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){var d=a.copy(c).multiplyScalar(.5);this.min.copy(b).sub(d);this.max.copy(b).add(d);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||
13991 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=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<
13992 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<=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)},
13993 distanceToPoint:function(){var a=new C;return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),intersect:function(a){this.min.max(a.min);this.max.min(a.max);return this},union:function(a){this.min.min(a.min);this.max.max(a.max);return this},translate:function(a){this.min.add(a);this.max.add(a);return this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)}});var Jf=0;Object.assign(U.prototype,xa.prototype,{isMaterial:!0,onBeforeCompile:function(){},
13994 setValues:function(a){if(void 0!==a)for(var b in a){var c=a[b];if(void 0===c)console.warn("THREE.Material: '"+b+"' parameter is undefined.");else{var d=this[b];void 0===d?console.warn("THREE."+this.type+": '"+b+"' is not a property of this material."):d&&d.isColor?d.set(c):d&&d.isVector3&&c&&c.isVector3?d.copy(c):this[b]="overdraw"===b?Number(c):c}}},toJSON:function(a){function b(a){var b=[],c;for(c in a){var d=a[c];delete d.metadata;b.push(d)}return b}var c=void 0===a;c&&(a={textures:{},images:{}});
13995 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());this.specular&&this.specular.isColor&&(d.specular=this.specular.getHex());void 0!==this.shininess&&(d.shininess=this.shininess);
13996 void 0!==this.clearCoat&&(d.clearCoat=this.clearCoat);void 0!==this.clearCoatRoughness&&(d.clearCoatRoughness=this.clearCoatRoughness);this.map&&this.map.isTexture&&(d.map=this.map.toJSON(a).uuid);this.alphaMap&&this.alphaMap.isTexture&&(d.alphaMap=this.alphaMap.toJSON(a).uuid);this.lightMap&&this.lightMap.isTexture&&(d.lightMap=this.lightMap.toJSON(a).uuid);this.bumpMap&&this.bumpMap.isTexture&&(d.bumpMap=this.bumpMap.toJSON(a).uuid,d.bumpScale=this.bumpScale);this.normalMap&&this.normalMap.isTexture&&
13997 (d.normalMap=this.normalMap.toJSON(a).uuid,d.normalScale=this.normalScale.toArray());this.displacementMap&&this.displacementMap.isTexture&&(d.displacementMap=this.displacementMap.toJSON(a).uuid,d.displacementScale=this.displacementScale,d.displacementBias=this.displacementBias);this.roughnessMap&&this.roughnessMap.isTexture&&(d.roughnessMap=this.roughnessMap.toJSON(a).uuid);this.metalnessMap&&this.metalnessMap.isTexture&&(d.metalnessMap=this.metalnessMap.toJSON(a).uuid);this.emissiveMap&&this.emissiveMap.isTexture&&
13998 (d.emissiveMap=this.emissiveMap.toJSON(a).uuid);this.specularMap&&this.specularMap.isTexture&&(d.specularMap=this.specularMap.toJSON(a).uuid);this.envMap&&this.envMap.isTexture&&(d.envMap=this.envMap.toJSON(a).uuid,d.reflectivity=this.reflectivity);this.gradientMap&&this.gradientMap.isTexture&&(d.gradientMap=this.gradientMap.toJSON(a).uuid);void 0!==this.size&&(d.size=this.size);void 0!==this.sizeAttenuation&&(d.sizeAttenuation=this.sizeAttenuation);1!==this.blending&&(d.blending=this.blending);2!==
13999 this.shading&&(d.shading=this.shading);0!==this.side&&(d.side=this.side);0!==this.vertexColors&&(d.vertexColors=this.vertexColors);1>this.opacity&&(d.opacity=this.opacity);!0===this.transparent&&(d.transparent=this.transparent);d.depthFunc=this.depthFunc;d.depthTest=this.depthTest;d.depthWrite=this.depthWrite;0<this.alphaTest&&(d.alphaTest=this.alphaTest);!0===this.premultipliedAlpha&&(d.premultipliedAlpha=this.premultipliedAlpha);!0===this.wireframe&&(d.wireframe=this.wireframe);1<this.wireframeLinewidth&&
14000 (d.wireframeLinewidth=this.wireframeLinewidth);"round"!==this.wireframeLinecap&&(d.wireframeLinecap=this.wireframeLinecap);"round"!==this.wireframeLinejoin&&(d.wireframeLinejoin=this.wireframeLinejoin);d.skinning=this.skinning;d.morphTargets=this.morphTargets;d.dithering=this.dithering;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;this.lights=
14001 a.lights;this.blending=a.blending;this.side=a.side;this.shading=a.shading;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=a.precision;this.polygonOffset=
14002 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.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]=a[d].clone();this.clippingPlanes=b;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});
14003 ra.prototype=Object.create(U.prototype);ra.prototype.constructor=ra;ra.prototype.isShaderMaterial=!0;ra.prototype.copy=function(a){U.prototype.copy.call(this,a);this.fragmentShader=a.fragmentShader;this.vertexShader=a.vertexShader;this.uniforms=Ca.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=
14004 a.extensions;return this};ra.prototype.toJSON=function(a){a=U.prototype.toJSON.call(this,a);a.uniforms=this.uniforms;a.vertexShader=this.vertexShader;a.fragmentShader=this.fragmentShader;return a};Za.prototype=Object.create(U.prototype);Za.prototype.constructor=Za;Za.prototype.isMeshDepthMaterial=!0;Za.prototype.copy=function(a){U.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=
14005 a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;return this};Object.assign(Ra.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 m=a[h],q=a[h+1],l=a[h+2];m<b&&(b=m);q<c&&(c=q);l<d&&(d=l);m>e&&(e=m);q>f&&(f=q);
14006 l>g&&(g=l)}this.min.set(b,c,d);this.max.set(e,f,g);return this},setFromBufferAttribute:function(a){for(var b=Infinity,c=Infinity,d=Infinity,e=-Infinity,f=-Infinity,g=-Infinity,h=0,k=a.count;h<k;h++){var m=a.getX(h),q=a.getY(h),l=a.getZ(h);m<b&&(b=m);q<c&&(c=q);l<d&&(d=l);m>e&&(e=m);q>f&&(f=q);l>g&&(g=l)}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=
14007 new n;return function(b,c){var d=a.copy(c).multiplyScalar(.5);this.min.copy(b).sub(d);this.max.copy(b).add(d);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<
14008 this.min.y||this.max.z<this.min.z},getCenter:function(a){a=a||new n;return this.isEmpty()?a.set(0,0,0):a.addVectors(this.min,this.max).multiplyScalar(.5)},getSize:function(a){a=a||new n;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(){var a=
14009 new n;return function(b){var c=this;b.updateMatrixWorld(!0);b.traverse(function(b){var e,f;e=b.geometry;if(void 0!==e)if(e.isGeometry){var g=e.vertices;e=0;for(f=g.length;e<f;e++)a.copy(g[e]),a.applyMatrix4(b.matrixWorld),c.expandByPoint(a)}else if(e.isBufferGeometry&&(g=e.attributes.position,void 0!==g))for(e=0,f=g.count;e<f;e++)a.fromBufferAttribute(g,e).applyMatrix4(b.matrixWorld),c.expandByPoint(a)});return this}}(),containsPoint:function(a){return a.x<this.min.x||a.x>this.max.x||a.y<this.min.y||
14010 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<=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 n).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<
14011 this.min.z||a.min.z>this.max.z?!1:!0},intersectsSphere:function(){var a=new n;return function(b){this.clampPoint(b.center,a);return a.distanceToSquared(b.center)<=b.radius*b.radius}}(),intersectsPlane:function(a){var b,c;0<a.normal.x?(b=a.normal.x*this.min.x,c=a.normal.x*this.max.x):(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*
14012 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,b){return(b||new n).copy(a).clamp(this.min,this.max)},distanceToPoint:function(){var a=new n;return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),getBoundingSphere:function(){var a=new n;return function(b){b=b||new Ea;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);
14013 this.isEmpty()&&this.makeEmpty();return this},union:function(a){this.min.min(a.min);this.max.max(a.max);return this},applyMatrix4:function(){var a=[new n,new n,new n,new n,new n,new n,new n,new n];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,
14014 this.min.y,this.min.z).applyMatrix4(b);a[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(b);a[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(b);a[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(b);this.setFromPoints(a);return this}}(),translate:function(a){this.min.add(a);this.max.add(a);return this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)}});Object.assign(Ea.prototype,{set:function(a,b){this.center.copy(a);this.radius=b;return this},setFromPoints:function(){var a=
14015 new Ra;return function(b,c){var d=this.center;void 0!==c?d.copy(c):a.setFromPoints(b).getCenter(d);for(var e=0,f=0,g=b.length;f<g;f++)e=Math.max(e,d.distanceToSquared(b[f]));this.radius=Math.sqrt(e);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)-
14016 this.radius},intersectsSphere:function(a){var b=this.radius+a.radius;return a.center.distanceToSquared(this.center)<=b*b},intersectsBox:function(a){return a.intersectsSphere(this)},intersectsPlane:function(a){return Math.abs(this.center.dot(a.normal)-a.constant)<=this.radius},clampPoint:function(a,b){var c=this.center.distanceToSquared(a),d=b||new n;d.copy(a);c>this.radius*this.radius&&(d.sub(this.center).normalize(),d.multiplyScalar(this.radius).add(this.center));return d},getBoundingBox:function(a){a=
14017 a||new Ra;a.set(this.center,this.center);a.expandByScalar(this.radius);return a},applyMatrix4:function(a){this.center.applyMatrix4(a);this.radius*=a.getMaxScaleOnAxis();return this},translate:function(a){this.center.add(a);return this},equals:function(a){return a.center.equals(this.center)&&a.radius===this.radius}});Object.assign(Ba.prototype,{isMatrix3:!0,set:function(a,b,c,d,e,f,g,h,k){var m=this.elements;m[0]=a;m[1]=d;m[2]=g;m[3]=b;m[4]=e;m[5]=h;m[6]=c;m[7]=f;m[8]=k;return this},identity:function(){this.set(1,
14018 0,0,0,1,0,0,0,1);return this},clone:function(){return(new this.constructor).fromArray(this.elements)},copy:function(a){var b=this.elements;a=a.elements;b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];b[5]=a[5];b[6]=a[6];b[7]=a[7];b[8]=a[8];return this},setFromMatrix4:function(a){a=a.elements;this.set(a[0],a[4],a[8],a[1],a[5],a[9],a[2],a[6],a[10]);return this},applyToBufferAttribute:function(){var a=new n;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),
14019 a.applyMatrix3(this),b.setXYZ(c,a.x,a.y,a.z);return b}}(),multiply:function(a){return this.multiplyMatrices(this,a)},premultiply:function(a){return this.multiplyMatrices(a,this)},multiplyMatrices:function(a,b){var c=a.elements,d=b.elements,e=this.elements,f=c[0],g=c[3],h=c[6],k=c[1],m=c[4],q=c[7],l=c[2],p=c[5],c=c[8],r=d[0],n=d[3],t=d[6],y=d[1],x=d[4],u=d[7],H=d[2],w=d[5],d=d[8];e[0]=f*r+g*y+h*H;e[3]=f*n+g*x+h*w;e[6]=f*t+g*u+h*d;e[1]=k*r+m*y+q*H;e[4]=k*n+m*x+q*w;e[7]=k*t+m*u+q*d;e[2]=l*r+p*y+c*H;
14020 e[5]=l*n+p*x+c*w;e[8]=l*t+p*u+c*d;return this},multiplyScalar:function(a){var b=this.elements;b[0]*=a;b[3]*=a;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,d=this.elements,e=c[0],f=c[1],g=c[2],
14021 h=c[3],k=c[4],m=c[5],q=c[6],l=c[7],c=c[8],p=c*k-m*l,r=m*q-c*h,n=l*h-k*q,t=e*p+f*r+g*n;if(0===t){if(!0===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()}t=1/t;d[0]=p*t;d[1]=(g*l-c*f)*t;d[2]=(m*f-g*k)*t;d[3]=r*t;d[4]=(c*e-g*q)*t;d[5]=(g*h-m*e)*t;d[6]=n*t;d[7]=(f*q-l*e)*t;d[8]=(k*e-f*h)*t;return this},transpose:function(){var a,b=this.elements;a=b[1];b[1]=b[3];b[3]=
14022 a;a=b[2];b[2]=b[6];b[6]=a;a=b[5];b[5]=b[7];b[7]=a;return this},getNormalMatrix:function(a){return this.setFromMatrix4(a).getInverse(this).transpose()},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},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},
14023 toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);var c=this.elements;a[b]=c[0];a[b+1]=c[1];a[b+2]=c[2];a[b+3]=c[3];a[b+4]=c[4];a[b+5]=c[5];a[b+6]=c[6];a[b+7]=c[7];a[b+8]=c[8];return a}});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=
14024 new n,b=new n;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)+
14025 this.constant},distanceToSphere:function(a){return this.distanceToPoint(a.center)-a.radius},projectPoint:function(a,b){return this.orthoPoint(a,b).sub(a).negate()},orthoPoint:function(a,b){var c=this.distanceToPoint(a);return(b||new n).copy(this.normal).multiplyScalar(c)},intersectLine:function(){var a=new n;return function(b,c){var d=c||new n,e=b.delta(a),f=this.normal.dot(e);if(0===f){if(0===this.distanceToPoint(b.start))return d.copy(b.start)}else return f=-(b.start.dot(this.normal)+this.constant)/
14026 f,0>f||1<f?void 0:d.copy(e).multiplyScalar(f).add(b.start)}}(),intersectsLine:function(a){var b=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 n).copy(this.normal).multiplyScalar(-this.constant)},applyMatrix4:function(){var a=new n,b=new Ba;return function(c,d){var e=this.coplanarPoint(a).applyMatrix4(c),
14027 f=d||b.getNormalMatrix(c),f=this.normal.applyMatrix3(f).normalize();this.constant=-e.dot(f);return this}}(),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(gd.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=
14028 this.planes,c=0;6>c;c++)b[c].copy(a.planes[c]);return this},setFromMatrix:function(a){var b=this.planes,c=a.elements;a=c[0];var d=c[1],e=c[2],f=c[3],g=c[4],h=c[5],k=c[6],m=c[7],q=c[8],l=c[9],p=c[10],r=c[11],n=c[12],t=c[13],y=c[14],c=c[15];b[0].setComponents(f-a,m-g,r-q,c-n).normalize();b[1].setComponents(f+a,m+g,r+q,c+n).normalize();b[2].setComponents(f+d,m+h,r+l,c+t).normalize();b[3].setComponents(f-d,m-h,r-l,c-t).normalize();b[4].setComponents(f-e,m-k,r-p,c-y).normalize();b[5].setComponents(f+e,
14029 m+k,r+p,c+y).normalize();return this},intersectsObject:function(){var a=new Ea;return function(b){var c=b.geometry;null===c.boundingSphere&&c.computeBoundingSphere();a.copy(c.boundingSphere).applyMatrix4(b.matrixWorld);return this.intersectsSphere(a)}}(),intersectsSprite:function(){var a=new Ea;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=
14030 0;6>d;d++)if(b[d].distanceToPoint(c)<a)return!1;return!0},intersectsBox:function(){var a=new n,b=new n;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>
14031 c;c++)if(0>b[c].distanceToPoint(a))return!1;return!0}});ab.RotationOrders="XYZ YZX ZXY XZY YXZ ZYX".split(" ");ab.DefaultOrder="XYZ";Object.defineProperties(ab.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;
14032 this.onChangeCallback()}}});Object.assign(ab.prototype,{isEuler:!0,set:function(a,b,c,d){this._x=a;this._y=b;this._z=c;this._order=d||this._order;this.onChangeCallback();return this},clone:function(){return new this.constructor(this._x,this._y,this._z,this._order)},copy:function(a){this._x=a._x;this._y=a._y;this._z=a._z;this._order=a._order;this.onChangeCallback();return this},setFromRotationMatrix:function(a,b,c){var d=Y.clamp,e=a.elements;a=e[0];var f=e[4],g=e[8],h=e[1],k=e[5],m=e[9],q=e[2],l=e[6],
14033 e=e[10];b=b||this._order;"XYZ"===b?(this._y=Math.asin(d(g,-1,1)),.99999>Math.abs(g)?(this._x=Math.atan2(-m,e),this._z=Math.atan2(-f,a)):(this._x=Math.atan2(l,k),this._z=0)):"YXZ"===b?(this._x=Math.asin(-d(m,-1,1)),.99999>Math.abs(m)?(this._y=Math.atan2(g,e),this._z=Math.atan2(h,k)):(this._y=Math.atan2(-q,a),this._z=0)):"ZXY"===b?(this._x=Math.asin(d(l,-1,1)),.99999>Math.abs(l)?(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,
14034 -1,1)),.99999>Math.abs(q)?(this._x=Math.atan2(l,e),this._z=Math.atan2(h,a)):(this._x=0,this._z=Math.atan2(-f,k))):"YZX"===b?(this._z=Math.asin(d(h,-1,1)),.99999>Math.abs(h)?(this._x=Math.atan2(-m,k),this._y=Math.atan2(-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(l,k),this._y=Math.atan2(g,a)):(this._x=Math.atan2(-m,e),this._y=0)):console.warn("THREE.Euler: .setFromRotationMatrix() given unsupported order: "+b);this._order=
14035 b;if(!1!==c)this.onChangeCallback();return this},setFromQuaternion:function(){var a=new K;return function(b,c,d){a.makeRotationFromQuaternion(b);return this.setFromRotationMatrix(a,c,d)}}(),setFromVector3:function(a,b){return this.set(a.x,a.y,a.z,b||this._order)},reorder:function(){var a=new oa;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=
14036 a[0];this._y=a[1];this._z=a[2];void 0!==a[3]&&(this._order=a[3]);this.onChangeCallback();return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this._x;a[b+1]=this._y;a[b+2]=this._z;a[b+3]=this._order;return a},toVector3:function(a){return a?a.set(this._x,this._y,this._z):new n(this._x,this._y,this._z)},onChange:function(a){this.onChangeCallback=a;return this},onChangeCallback:function(){}});Object.assign(Qd.prototype,{set:function(a){this.mask=1<<a|0},enable:function(a){this.mask=
14037 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)}});var Lf=0;z.DefaultUp=new n(0,1,0);z.DefaultMatrixAutoUpdate=!0;Object.assign(z.prototype,xa.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);
14038 return this},setRotationFromAxisAngle:function(a,b){this.quaternion.setFromAxisAngle(a,b)},setRotationFromEuler:function(a){this.quaternion.setFromEuler(a,!0)},setRotationFromMatrix:function(a){this.quaternion.setFromRotationMatrix(a)},setRotationFromQuaternion:function(a){this.quaternion.copy(a)},rotateOnAxis:function(){var a=new oa;return function(b,c){a.setFromAxisAngle(b,c);this.quaternion.multiply(a);return this}}(),rotateX:function(){var a=new n(1,0,0);return function(b){return this.rotateOnAxis(a,
14039 b)}}(),rotateY:function(){var a=new n(0,1,0);return function(b){return this.rotateOnAxis(a,b)}}(),rotateZ:function(){var a=new n(0,0,1);return function(b){return this.rotateOnAxis(a,b)}}(),translateOnAxis:function(){var a=new n;return function(b,c){a.copy(b).applyQuaternion(this.quaternion);this.position.add(a.multiplyScalar(c));return this}}(),translateX:function(){var a=new n(1,0,0);return function(b){return this.translateOnAxis(a,b)}}(),translateY:function(){var a=new n(0,1,0);return function(b){return this.translateOnAxis(a,
14040 b)}}(),translateZ:function(){var a=new n(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;return function(b){this.isCamera?a.lookAt(this.position,b,this.up):a.lookAt(b,this.position,this.up);this.quaternion.setFromRotationMatrix(a)}}(),add:function(a){if(1<arguments.length){for(var b=
14041 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]);return this}b=this.children.indexOf(a);
14042 -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 n;this.updateMatrixWorld(!0);return a.setFromMatrixPosition(this.matrixWorld)},
14043 getWorldQuaternion:function(){var a=new n,b=new n;return function(c){c=c||new oa;this.updateMatrixWorld(!0);this.matrixWorld.decompose(a,c,b);return c}}(),getWorldRotation:function(){var a=new oa;return function(b){b=b||new ab;this.getWorldQuaternion(a);return b.setFromQuaternion(a,this.rotation.order,!1)}}(),getWorldScale:function(){var a=new n,b=new oa;return function(c){c=c||new n;this.updateMatrixWorld(!0);this.matrixWorld.decompose(a,b,c);return c}}(),getWorldDirection:function(){var a=new oa;
14044 return function(b){b=b||new n;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,this.quaternion,
14045 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=[],
14046 c;for(c in a){var d=a[c];delete d.metadata;b.push(d)}return b}var d=void 0===a||""===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);"{}"!==JSON.stringify(this.userData)&&(f.userData=this.userData);!0===this.castShadow&&(f.castShadow=!0);!0===this.receiveShadow&&(f.receiveShadow=!0);!1===this.visible&&(f.visible=!1);f.matrix=this.matrix.toArray();
14047 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&&(e.geometries=d),0<g.length&&
14048 (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;this.layers.mask=a.layers.mask;
14049 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(var c=0;c<a.children.length;c++)this.add(a.children[c].clone());return this}});Na.prototype=Object.assign(Object.create(z.prototype),{constructor:Na,isCamera:!0,copy:function(a,b){z.prototype.copy.call(this,a,b);this.matrixWorldInverse.copy(a.matrixWorldInverse);this.projectionMatrix.copy(a.projectionMatrix);
14050 return this},getWorldDirection:function(){var a=new oa;return function(b){b=b||new n;this.getWorldQuaternion(a);return b.set(0,0,-1).applyQuaternion(a)}}(),updateMatrixWorld:function(a){z.prototype.updateMatrixWorld.call(this,a);this.matrixWorldInverse.getInverse(this.matrixWorld)},clone:function(){return(new this.constructor).copy(this)}});Fb.prototype=Object.assign(Object.create(Na.prototype),{constructor:Fb,isOrthographicCamera:!0,copy:function(a,b){Na.prototype.copy.call(this,a,b);this.left=a.left;
14051 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){this.view={fullWidth:a,fullHeight:b,offsetX:c,offsetY:d,width:e,height:f};this.updateProjectionMatrix()},clearViewOffset:function(){this.view=null;this.updateProjectionMatrix()},updateProjectionMatrix:function(){var a=(this.right-this.left)/(2*this.zoom),b=(this.top-this.bottom)/(2*this.zoom),
14052 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)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)/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=z.prototype.toJSON.call(this,
14053 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}});qa.prototype=Object.assign(Object.create(Na.prototype),{constructor:qa,isPerspectiveCamera:!0,copy:function(a,b){Na.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;this.view=
14054 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*Y.RAD2DEG*Math.atan(a);this.updateProjectionMatrix()},getFocalLength:function(){var a=Math.tan(.5*Y.DEG2RAD*this.fov);return.5*this.getFilmHeight()/a},getEffectiveFOV:function(){return 2*Y.RAD2DEG*Math.atan(Math.tan(.5*Y.DEG2RAD*this.fov)/this.zoom)},getFilmWidth:function(){return this.filmGauge*Math.min(this.aspect,1)},
14055 getFilmHeight:function(){return this.filmGauge/Math.max(this.aspect,1)},setViewOffset:function(a,b,c,d,e,f){this.aspect=a/b;this.view={fullWidth:a,fullHeight:b,offsetX:c,offsetY:d,width:e,height:f};this.updateProjectionMatrix()},clearViewOffset:function(){this.view=null;this.updateProjectionMatrix()},updateProjectionMatrix:function(){var a=this.near,b=a*Math.tan(.5*Y.DEG2RAD*this.fov)/this.zoom,c=2*b,d=this.aspect*c,e=-.5*d,f=this.view;if(null!==f)var g=f.fullWidth,h=f.fullHeight,e=e+f.offsetX*d/
14056 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=z.prototype.toJSON.call(this,a);a.object.fov=this.fov;a.object.zoom=this.zoom;a.object.near=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}});
14057 Object.assign(Sa.prototype,{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 Rd=0;Object.assign(J.prototype,xa.prototype,{isGeometry:!0,applyMatrix:function(a){for(var b=
14058 (new Ba).getNormalMatrix(a),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);
14059 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,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 z;return function(b){a.lookAt(b);
14060 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()]:[],r=void 0!==h?[c.colors[a].clone(),c.colors[b].clone(),c.colors[d].clone()]:[];e=new Sa(a,b,d,f,r,e);c.faces.push(e);void 0!==k&&c.faceVertexUvs[0].push([l[a].clone(),l[b].clone(),l[d].clone()]);void 0!==m&&c.faceVertexUvs[1].push([p[a].clone(),p[b].clone(),p[d].clone()])}var c=this,d=null!==a.index?a.index.array:void 0,e=a.attributes,f=e.position.array,
14061 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,m=void 0!==e.uv2?e.uv2.array:void 0;void 0!==m&&(this.faceVertexUvs[1]=[]);for(var q=[],l=[],p=[],r=e=0;e<f.length;e+=3,r+=2)c.vertices.push(new n(f[e],f[e+1],f[e+2])),void 0!==g&&q.push(new n(g[e],g[e+1],g[e+2])),void 0!==h&&c.colors.push(new G(h[e],h[e+1],h[e+2])),void 0!==k&&l.push(new C(k[r],k[r+1])),void 0!==m&&p.push(new C(m[r],m[r+1]));var ca=a.groups;if(0<ca.length)for(e=0;e<
14062 ca.length;e++)for(var f=ca[e],t=f.start,y=f.count,r=t,t=t+y;r<t;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();
14063 this.translate(a.x,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 n,b=new n,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)}},
14064 computeVertexNormals:function(a){void 0===a&&(a=!0);var b,c,d;d=Array(this.vertices.length);b=0;for(c=this.vertices.length;b<c;b++)d[b]=new n;if(a){var e,f,g,h=new n,k=new n;a=0;for(b=this.faces.length;a<b;a++)c=this.faces[a],e=this.vertices[c.a],f=this.vertices[c.b],g=this.vertices[c.c],h.subVectors(g,f),k.subVectors(e,f),h.cross(k),d[c.a].add(h),d[c.b].add(h),d[c.c].add(h)}else for(this.computeFaceNormals(),a=0,b=this.faces.length;a<b;a++)c=this.faces[a],d[c.a].add(c.normal),d[c.b].add(c.normal),
14065 d[c.c].add(c.normal);b=0;for(c=this.vertices.length;b<c;b++)d[b].normalize();a=0;for(b=this.faces.length;a<b;a++)c=this.faces[a],e=c.vertexNormals,3===e.length?(e[0].copy(d[c.a]),e[1].copy(d[c.b]),e[2].copy(d[c.c])):(e[0]=d[c.a].clone(),e[1]=d[c.b].clone(),e[2]=d[c.c].clone());0<this.faces.length&&(this.normalsNeedUpdate=!0)},computeFlatVertexNormals:function(){var a,b,c;this.computeFaceNormals();a=0;for(b=this.faces.length;a<b;a++){c=this.faces[a];var d=c.vertexNormals;3===d.length?(d[0].copy(c.normal),
14066 d[1].copy(c.normal),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,c,d,e;c=0;for(d=this.faces.length;c<d;c++)for(e=this.faces[c],e.__originalFaceNormal?e.__originalFaceNormal.copy(e.normal):e.__originalFaceNormal=e.normal.clone(),e.__originalVertexNormals||(e.__originalVertexNormals=[]),a=0,b=e.vertexNormals.length;a<b;a++)e.__originalVertexNormals[a]?e.__originalVertexNormals[a].copy(e.vertexNormals[a]):
14067 e.__originalVertexNormals[a]=e.vertexNormals[a].clone();var f=new J;f.faces=this.faces;a=0;for(b=this.morphTargets.length;a<b;a++){if(!this.morphNormals[a]){this.morphNormals[a]={};this.morphNormals[a].faceNormals=[];this.morphNormals[a].vertexNormals=[];e=this.morphNormals[a].faceNormals;var g=this.morphNormals[a].vertexNormals,h,k;c=0;for(d=this.faces.length;c<d;c++)h=new n,k={a:new n,b:new n,c:new n},e.push(h),g.push(k)}g=this.morphNormals[a];f.vertices=this.morphTargets[a].vertices;f.computeFaceNormals();
14068 f.computeVertexNormals();c=0;for(d=this.faces.length;c<d;c++)e=this.faces[c],h=g.faceNormals[c],k=g.vertexNormals[c],h.copy(e.normal),k.a.copy(e.vertexNormals[0]),k.b.copy(e.vertexNormals[1]),k.c.copy(e.vertexNormals[2])}c=0;for(d=this.faces.length;c<d;c++)e=this.faces[c],e.normal=e.__originalFaceNormal,e.vertexNormals=e.__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===
14069 this.boundingBox&&(this.boundingBox=new Ra);this.boundingBox.setFromPoints(this.vertices)},computeBoundingSphere:function(){null===this.boundingSphere&&(this.boundingSphere=new Ea);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,m=this.faceVertexUvs[0],q=a.faceVertexUvs[0],l=this.colors,p=a.colors;void 0===c&&(c=0);void 0!==b&&(d=(new Ba).getNormalMatrix(b));a=0;for(var r=g.length;a<
14070 r;a++){var n=g[a].clone();void 0!==b&&n.applyMatrix4(b);f.push(n)}a=0;for(r=p.length;a<r;a++)l.push(p[a].clone());a=0;for(r=k.length;a<r;a++){var g=k[a],t=g.vertexNormals,p=g.vertexColors,l=new Sa(g.a+e,g.b+e,g.c+e);l.normal.copy(g.normal);void 0!==d&&l.normal.applyMatrix3(d).normalize();b=0;for(f=t.length;b<f;b++)n=t[b].clone(),void 0!==d&&n.applyMatrix3(d).normalize(),l.vertexNormals.push(n);l.color.copy(g.color);b=0;for(f=p.length;b<f;b++)n=p[b],l.vertexColors.push(n.clone());l.materialIndex=g.materialIndex+
14071 c;h.push(l)}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());m.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,e=Math.pow(10,4),f,g;f=0;for(g=this.vertices.length;f<
14072 g;f++)d=this.vertices[f],d=Math.round(d.x*e)+"_"+Math.round(d.y*e)+"_"+Math.round(d.z*e),void 0===a[d]?(a[d]=f,b.push(this.vertices[f]),c[f]=b.length-1):c[f]=c[a[d]];a=[];f=0;for(g=this.faces.length;f<g;f++)for(e=this.faces[f],e.a=c[e.a],e.b=c[e.b],e.c=c[e.c],e=[e.a,e.b,e.c],d=0;3>d;d++)if(e[d]===e[(d+1)%3]){a.push(f);break}for(f=a.length-1;0<=f;f--)for(e=a[f],this.faces.splice(e,1),c=0,g=this.faceVertexUvs.length;c<g;c++)this.faceVertexUvs[c].splice(e,1);f=this.vertices.length-b.length;this.vertices=
14073 b;return f},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);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()+
14074 a.z.toString();if(void 0!==m[b])return m[b];m[b]=k.length/3;k.push(a.x,a.y,a.z);return m[b]}function c(a){var b=a.r.toString()+a.g.toString()+a.b.toString();if(void 0!==l[b])return l[b];l[b]=q.length;q.push(a.getHex());return l[b]}function d(a){var b=a.x.toString()+a.y.toString();if(void 0!==r[b])return r[b];r[b]=p.length/2;p.push(a.x,a.y);return r[b]}var e={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!==
14075 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=[],m={},q=[],l={},p=[],r={};for(g=0;g<this.faces.length;g++){var n=this.faces[g],t=void 0!==this.faceVertexUvs[0][g],y=0<n.normal.length(),x=0<n.vertexNormals.length,u=1!==n.color.r||1!==n.color.g||1!==n.color.b,H=0<n.vertexColors.length,w=0,w=a(w,0,0),w=a(w,1,!0),w=a(w,2,!1),w=a(w,3,t),w=a(w,4,y),w=a(w,5,x),w=a(w,6,
14076 u),w=a(w,7,H);h.push(w);h.push(n.a,n.b,n.c);h.push(n.materialIndex);t&&(t=this.faceVertexUvs[0][g],h.push(d(t[0]),d(t[1]),d(t[2])));y&&h.push(b(n.normal));x&&(y=n.vertexNormals,h.push(b(y[0]),b(y[1]),b(y[2])));u&&h.push(c(n.color));H&&(n=n.vertexColors,h.push(c(n[0]),c(n[1]),c(n[2])))}e.data={};e.data.vertices=f;e.data.normals=k;0<q.length&&(e.data.colors=q);0<p.length&&(e.data.uvs=[p]);e.data.faces=h;return e},clone:function(){return(new J).copy(this)},copy:function(a){var b,c,d,e,f,g;this.vertices=
14077 [];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;d=a.vertices;b=0;for(c=d.length;b<c;b++)this.vertices.push(d[b].clone());d=a.colors;b=0;for(c=d.length;b<c;b++)this.colors.push(d[b].clone());d=a.faces;b=0;for(c=d.length;b<c;b++)this.faces.push(d[b].clone());b=0;for(c=a.faceVertexUvs.length;b<c;b++){var h=a.faceVertexUvs[b];void 0===
14078 this.faceVertexUvs[b]&&(this.faceVertexUvs[b]=[]);d=0;for(e=h.length;d<e;d++){var k=h[d],m=[];f=0;for(g=k.length;f<g;f++)m.push(k[f].clone());this.faceVertexUvs[b].push(m)}}f=a.morphTargets;b=0;for(c=f.length;b<c;b++){g={};g.name=f[b].name;if(void 0!==f[b].vertices)for(g.vertices=[],d=0,e=f[b].vertices.length;d<e;d++)g.vertices.push(f[b].vertices[d].clone());if(void 0!==f[b].normals)for(g.normals=[],d=0,e=f[b].normals.length;d<e;d++)g.normals.push(f[b].normals[d].clone());this.morphTargets.push(g)}f=
14079 a.morphNormals;b=0;for(c=f.length;b<c;b++){g={};if(void 0!==f[b].vertexNormals)for(g.vertexNormals=[],d=0,e=f[b].vertexNormals.length;d<e;d++)h=f[b].vertexNormals[d],k={},k.a=h.a.clone(),k.b=h.b.clone(),k.c=h.c.clone(),g.vertexNormals.push(k);if(void 0!==f[b].faceNormals)for(g.faceNormals=[],d=0,e=f[b].faceNormals.length;d<e;d++)g.faceNormals.push(f[b].faceNormals[d].clone());this.morphNormals.push(g)}d=a.skinWeights;b=0;for(c=d.length;b<c;b++)this.skinWeights.push(d[b].clone());d=a.skinIndices;b=
14080 0;for(c=d.length;b<c;b++)this.skinIndices.push(d[b].clone());d=a.lineDistances;b=0;for(c=d.length;b<c;b++)this.lineDistances.push(d[b]);b=a.boundingBox;null!==b&&(this.boundingBox=b.clone());b=a.boundingSphere;null!==b&&(this.boundingSphere=b.clone());this.elementsNeedUpdate=a.elementsNeedUpdate;this.verticesNeedUpdate=a.verticesNeedUpdate;this.uvsNeedUpdate=a.uvsNeedUpdate;this.normalsNeedUpdate=a.normalsNeedUpdate;this.colorsNeedUpdate=a.colorsNeedUpdate;this.lineDistancesNeedUpdate=a.lineDistancesNeedUpdate;
14081 this.groupsNeedUpdate=a.groupsNeedUpdate;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Object.defineProperty(Z.prototype,"needsUpdate",{set:function(a){!0===a&&this.version++}});Object.assign(Z.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!==a?a.length/this.itemSize:0;this.array=a},setDynamic:function(a){this.dynamic=a;return this},copy:function(a){this.array=
14082 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=0,e=a.length;d<e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyColorsArray(): color is undefined",
14083 d),f=new G);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);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=
14084 a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyVector3sArray(): vector is undefined",d),f=new n);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 fa);b[c++]=f.x;b[c++]=f.y;b[c++]=f.z;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*
14085 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]},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+
14086 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,this.itemSize)).copy(this)}});pc.prototype=Object.create(Z.prototype);pc.prototype.constructor=pc;qc.prototype=Object.create(Z.prototype);
14087 qc.prototype.constructor=qc;rc.prototype=Object.create(Z.prototype);rc.prototype.constructor=rc;sc.prototype=Object.create(Z.prototype);sc.prototype.constructor=sc;gb.prototype=Object.create(Z.prototype);gb.prototype.constructor=gb;tc.prototype=Object.create(Z.prototype);tc.prototype.constructor=tc;hb.prototype=Object.create(Z.prototype);hb.prototype.constructor=hb;B.prototype=Object.create(Z.prototype);B.prototype.constructor=B;uc.prototype=Object.create(Z.prototype);uc.prototype.constructor=uc;
14088 Object.assign(Je.prototype,{computeGroups:function(a){var b,c=[],d=void 0;a=a.faces;for(var e=0;e<a.length;e++){var f=a[e];f.materialIndex!==d&&(d=f.materialIndex,void 0!==b&&(b.count=3*e-b.start,c.push(b)),b={start:3*e,materialIndex:d})}void 0!==b&&(b.count=3*e-b.start,c.push(b));this.groups=c},fromGeometry:function(a){var b=a.faces,c=a.vertices,d=a.faceVertexUvs,e=d[0]&&0<d[0].length,f=d[1]&&0<d[1].length,g=a.morphTargets,h=g.length,k;if(0<h){k=[];for(var m=0;m<h;m++)k[m]=[];this.morphTargets.position=
14089 k}var q=a.morphNormals,l=q.length,p;if(0<l){p=[];for(m=0;m<l;m++)p[m]=[];this.morphTargets.normal=p}for(var r=a.skinIndices,n=a.skinWeights,t=r.length===c.length,y=n.length===c.length,m=0;m<b.length;m++){var x=b[m];this.vertices.push(c[x.a],c[x.b],c[x.c]);var u=x.vertexNormals;3===u.length?this.normals.push(u[0],u[1],u[2]):(u=x.normal,this.normals.push(u,u,u));u=x.vertexColors;3===u.length?this.colors.push(u[0],u[1],u[2]):(u=x.color,this.colors.push(u,u,u));!0===e&&(u=d[0][m],void 0!==u?this.uvs.push(u[0],
14090 u[1],u[2]):(console.warn("THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ",m),this.uvs.push(new C,new C,new C)));!0===f&&(u=d[1][m],void 0!==u?this.uvs2.push(u[0],u[1],u[2]):(console.warn("THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ",m),this.uvs2.push(new C,new C,new C)));for(u=0;u<h;u++){var H=g[u].vertices;k[u].push(H[x.a],H[x.b],H[x.c])}for(u=0;u<l;u++)H=q[u].vertexNormals[m],p[u].push(H.a,H.b,H.c);t&&this.skinIndices.push(r[x.a],r[x.b],r[x.c]);y&&this.skinWeights.push(n[x.a],
14091 n[x.b],n[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}});E.MaxIndex=65535;Object.assign(E.prototype,xa.prototype,{isBufferGeometry:!0,getIndex:function(){return this.index},setIndex:function(a){Array.isArray(a)?this.index=new (65535<Sd(a)?hb:gb)(a,1):this.index=a},addAttribute:function(a,b,c){if(b&&b.isBufferAttribute||
14092 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 Z(b,c))},getAttribute:function(a){return this.attributes[a]},removeAttribute:function(a){delete this.attributes[a];return this},addGroup:function(a,b,c){this.groups.push({start:a,count:b,materialIndex:void 0!==
14093 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 Ba).getNormalMatrix(a).applyToBufferAttribute(b),b.needsUpdate=!0);null!==this.boundingBox&&this.computeBoundingBox();null!==this.boundingSphere&&this.computeBoundingSphere();return this},rotateX:function(){var a=new K;return function(b){a.makeRotationX(b);
14094 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,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 z;return function(b){a.lookAt(b);
14095 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 B(3*b.vertices.length,3);var c=new B(3*b.colors.length,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 B(b.lineDistances.length,
14096 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},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=
14097 b.normalsNeedUpdate;c.colorsNeedUpdate=b.colorsNeedUpdate;c.uvsNeedUpdate=b.uvsNeedUpdate;c.groupsNeedUpdate=b.groupsNeedUpdate;b.verticesNeedUpdate=!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=
14098 !1);!0===b.colorsNeedUpdate&&(c=this.attributes.color,void 0!==c&&(c.copyColorsArray(b.colors),c.needsUpdate=!0),b.colorsNeedUpdate=!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},
14099 fromGeometry:function(a){a.__directGeometry=(new Je).fromGeometry(a);return this.fromDirectGeometry(a.__directGeometry)},fromDirectGeometry:function(a){var b=new Float32Array(3*a.vertices.length);this.addAttribute("position",(new Z(b,3)).copyVector3sArray(a.vertices));0<a.normals.length&&(b=new Float32Array(3*a.normals.length),this.addAttribute("normal",(new Z(b,3)).copyVector3sArray(a.normals)));0<a.colors.length&&(b=new Float32Array(3*a.colors.length),this.addAttribute("color",(new Z(b,3)).copyColorsArray(a.colors)));
14100 0<a.uvs.length&&(b=new Float32Array(2*a.uvs.length),this.addAttribute("uv",(new Z(b,2)).copyVector2sArray(a.uvs)));0<a.uvs2.length&&(b=new Float32Array(2*a.uvs2.length),this.addAttribute("uv2",(new Z(b,2)).copyVector2sArray(a.uvs2)));0<a.indices.length&&(b=new (65535<Sd(a.indices)?Uint32Array:Uint16Array)(3*a.indices.length),this.setIndex((new Z(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],
14101 h=new B(3*g.length,3);b.push(h.copyVector3sArray(g))}this.morphAttributes[c]=b}0<a.skinIndices.length&&(c=new B(4*a.skinIndices.length,4),this.addAttribute("skinIndex",c.copyVector4sArray(a.skinIndices)));0<a.skinWeights.length&&(c=new B(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===
14102 this.boundingBox&&(this.boundingBox=new Ra);var a=this.attributes.position;void 0!==a?this.boundingBox.setFromBufferAttribute(a):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 Ra,b=new n;return function(){null===this.boundingSphere&&
14103 (this.boundingSphere=new Ea);var c=this.attributes.position;if(c){var d=this.boundingSphere.center;a.setFromBufferAttribute(c);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(){},
14104 computeVertexNormals:function(){var a=this.index,b=this.attributes,c=this.groups;if(b.position){var d=b.position.array;if(void 0===b.normal)this.addAttribute("normal",new Z(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,k,m,q=new n,l=new n,p=new n,r=new n,ca=new n;if(a){a=a.array;0===c.length&&this.addGroup(0,a.length);for(var t=0,y=c.length;t<y;++t)for(f=c[t],g=f.start,h=f.count,f=g,g+=h;f<g;f+=3)h=3*a[f+0],k=3*a[f+1],m=3*a[f+2],
14105 q.fromArray(d,h),l.fromArray(d,k),p.fromArray(d,m),r.subVectors(p,l),ca.subVectors(q,l),r.cross(ca),e[h]+=r.x,e[h+1]+=r.y,e[h+2]+=r.z,e[k]+=r.x,e[k+1]+=r.y,e[k+2]+=r.z,e[m]+=r.x,e[m+1]+=r.y,e[m+2]+=r.z}else for(f=0,g=d.length;f<g;f+=9)q.fromArray(d,f),l.fromArray(d,f+3),p.fromArray(d,f+6),r.subVectors(p,l),ca.subVectors(q,l),r.cross(ca),e[f]=r.x,e[f+1]=r.y,e[f+2]=r.z,e[f+3]=r.x,e[f+4]=r.y,e[f+5]=r.z,e[f+6]=r.x,e[f+7]=r.y,e[f+8]=r.z;this.normalizeNormals();b.normal.needsUpdate=!0}},merge:function(a,
14106 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=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(){for(var a=this.attributes.normal,b,c,d,e,f=0,g=a.count;f<g;f++)b=a.getX(f),c=a.getY(f),d=a.getZ(f),e=1/Math.sqrt(b*b+c*c+d*d),a.setXYZ(f,b*e,c*e,d*e)},toNonIndexed:function(){if(null===
14107 this.index)return console.warn("THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed."),this;var a=new E,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,m=0,q=b.length;m<q;m++){h=b[m]*e;for(var l=0;l<e;l++)g[k++]=f[h++]}a.addAttribute(d,new Z(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&&
14108 (a.name=this.name);if(void 0!==this.parameters){var b=this.parameters,c;for(c in b)void 0!==b[c]&&(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)));
14109 c=this.boundingSphere;null!==c&&(a.data.boundingSphere={center:c.center.toArray(),radius:c.radius});return a},clone:function(){return(new E).copy(this)},copy:function(a){var b,c,d;this.index=null;this.attributes={};this.morphAttributes={};this.groups=[];this.boundingSphere=this.boundingBox=null;this.name=a.name;c=a.index;null!==c&&this.setIndex(c.clone());c=a.attributes;for(b in c)this.addAttribute(b,c[b].clone());var e=a.morphAttributes;for(b in e){var f=[],g=e[b];c=0;for(d=g.length;c<d;c++)f.push(g[c].clone());
14110 this.morphAttributes[b]=f}b=a.groups;c=0;for(d=b.length;c<d;c++)e=b[c],this.addGroup(e.start,e.count,e.materialIndex);b=a.boundingBox;null!==b&&(this.boundingBox=b.clone());b=a.boundingSphere;null!==b&&(this.boundingSphere=b.clone());this.drawRange.start=a.drawRange.start;this.drawRange.count=a.drawRange.count;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Gb.prototype=Object.create(J.prototype);Gb.prototype.constructor=Gb;ib.prototype=Object.create(E.prototype);ib.prototype.constructor=
14111 ib;vc.prototype=Object.create(J.prototype);vc.prototype.constructor=vc;jb.prototype=Object.create(E.prototype);jb.prototype.constructor=jb;ya.prototype=Object.create(U.prototype);ya.prototype.constructor=ya;ya.prototype.isMeshBasicMaterial=!0;ya.prototype.copy=function(a){U.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=
14112 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;return this};Object.assign(kb.prototype,{set:function(a,b){this.origin.copy(a);this.direction.copy(b);return this},clone:function(){return(new this.constructor).copy(this)},
14113 copy:function(a){this.origin.copy(a.origin);this.direction.copy(a.direction);return this},at:function(a,b){return(b||new n).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 n;return function(b){this.origin.copy(this.at(b,a));return this}}(),closestPointToPoint:function(a,b){var c=b||new n;c.subVectors(a,this.origin);var d=c.dot(this.direction);return 0>d?c.copy(this.origin):c.copy(this.direction).multiplyScalar(d).add(this.origin)},
14114 distanceToPoint:function(a){return Math.sqrt(this.distanceSqToPoint(a))},distanceSqToPoint:function(){var a=new n;return function(b){var c=a.subVectors(b,this.origin).dot(this.direction);if(0>c)return this.origin.distanceToSquared(b);a.copy(this.direction).multiplyScalar(c).add(this.origin);return a.distanceToSquared(b)}}(),distanceSqToSegment:function(){var a=new n,b=new n,c=new n;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);
14115 var h=.5*d.distanceTo(e),k=-this.direction.dot(b),m=c.dot(this.direction),q=-c.dot(b),l=c.lengthSq(),p=Math.abs(1-k*k),r;0<p?(d=k*q-m,e=k*m-q,r=h*p,0<=d?e>=-r?e<=r?(h=1/p,d*=h,e*=h,k=d*(d+k*e+2*m)+e*(k*d+e+2*q)+l):(e=h,d=Math.max(0,-(k*e+m)),k=-d*d+e*(e+2*q)+l):(e=-h,d=Math.max(0,-(k*e+m)),k=-d*d+e*(e+2*q)+l):e<=-r?(d=Math.max(0,-(-k*h+m)),e=0<d?-h:Math.min(Math.max(-h,-q),h),k=-d*d+e*(e+2*q)+l):e<=r?(d=0,e=Math.min(Math.max(-h,-q),h),k=e*(e+2*q)+l):(d=Math.max(0,-(k*h+m)),e=0<d?h:Math.min(Math.max(-h,
14116 -q),h),k=-d*d+e*(e+2*q)+l)):(e=0<k?-h:h,d=Math.max(0,-(k*e+m)),k=-d*d+e*(e+2*q)+l);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 n;return function(b,c){a.subVectors(b.center,this.origin);var d=a.dot(this.direction),e=a.dot(a)-d*d,f=b.radius*b.radius;if(e>f)return null;f=Math.sqrt(f-e);e=d-f;d+=f;return 0>e&&0>d?null:0>e?this.at(d,c):this.at(e,c)}}(),intersectsSphere:function(a){return this.distanceToPoint(a.center)<=
14117 a.radius},distanceToPlane:function(a){var b=a.normal.dot(this.direction);if(0===b)return 0===a.distanceToPoint(this.origin)?0:null;a=-(this.origin.dot(a.normal)+a.constant)/b;return 0<=a?a:null},intersectPlane:function(a,b){var c=this.distanceToPlane(a);return null===c?null:this.at(c,b)},intersectsPlane:function(a){var b=a.distanceToPoint(this.origin);return 0===b||0>a.normal.dot(this.direction)*b?!0:!1},intersectBox:function(a,b){var c,d,e,f,g;d=1/this.direction.x;f=1/this.direction.y;g=1/this.direction.z;
14118 var h=this.origin;0<=d?(c=(a.min.x-h.x)*d,d*=a.max.x-h.x):(c=(a.max.x-h.x)*d,d*=a.min.x-h.x);0<=f?(e=(a.min.y-h.y)*f,f*=a.max.y-h.y):(e=(a.max.y-h.y)*f,f*=a.min.y-h.y);if(c>f||e>d)return null;if(e>c||c!==c)c=e;if(f<d||d!==d)d=f;0<=g?(e=(a.min.z-h.z)*g,g*=a.max.z-h.z):(e=(a.max.z-h.z)*g,g*=a.min.z-h.z);if(c>g||e>d)return null;if(e>c||c!==c)c=e;if(g<d||d!==d)d=g;return 0>d?null:this.at(0<=c?c:d,b)},intersectsBox:function(){var a=new n;return function(b){return null!==this.intersectBox(b,a)}}(),intersectTriangle:function(){var a=
14119 new n,b=new n,c=new n,d=new n;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;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},
14120 equals:function(a){return a.origin.equals(this.origin)&&a.direction.equals(this.direction)}});Object.assign(Hb.prototype,{set:function(a,b){this.start.copy(a);this.end.copy(b);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.start.copy(a.start);this.end.copy(a.end);return this},getCenter:function(a){return(a||new n).addVectors(this.start,this.end).multiplyScalar(.5)},delta:function(a){return(a||new n).subVectors(this.end,this.start)},distanceSq:function(){return this.start.distanceToSquared(this.end)},
14121 distance:function(){return this.start.distanceTo(this.end)},at:function(a,b){var c=b||new n;return this.delta(c).multiplyScalar(a).add(this.start)},closestPointToPointParameter:function(){var a=new n,b=new n;return function(c,d){a.subVectors(c,this.start);b.subVectors(this.end,this.start);var e=b.dot(b),e=b.dot(a)/e;d&&(e=Y.clamp(e,0,1));return e}}(),closestPointToPoint:function(a,b,c){a=this.closestPointToPointParameter(a,b);c=c||new n;return this.delta(c).multiplyScalar(a).add(this.start)},applyMatrix4:function(a){this.start.applyMatrix4(a);
14122 this.end.applyMatrix4(a);return this},equals:function(a){return a.start.equals(this.start)&&a.end.equals(this.end)}});Object.assign(Ta,{normal:function(){var a=new n;return function(b,c,d,e){e=e||new n;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 n,b=new n,c=new n;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=
14123 b.dot(b);g=b.dot(c);var m=d*k-e*e;h=h||new n;if(0===m)return h.set(-2,-1,-1);m=1/m;k=(k*f-e*g)*m;d=(d*g-e*f)*m;return h.set(1-k-d,d,k)}}(),containsPoint:function(){var a=new n;return function(b,c,d,e){b=Ta.barycoordFromPoint(b,c,d,e,a);return 0<=b.x&&0<=b.y&&1>=b.x+b.y}}()});Object.assign(Ta.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)},
14124 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 n,b=new n;return function(){a.subVectors(this.c,this.b);b.subVectors(this.a,this.b);return.5*a.cross(b).length()}}(),midpoint:function(a){return(a||new n).addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)},normal:function(a){return Ta.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 Ta.barycoordFromPoint(a,
14125 this.a,this.b,this.c,b)},containsPoint:function(a){return Ta.containsPoint(a,this.a,this.b,this.c)},closestPointToPoint:function(){var a=new Aa,b=[new Hb,new Hb,new Hb],c=new n,d=new n;return function(e,f){var g=f||new n,h=Infinity;a.setFromCoplanarPoints(this.a,this.b,this.c);a.projectPoint(e,c);if(!0===this.containsPoint(c))g.copy(c);else{b[0].set(this.a,this.b);b[1].set(this.b,this.c);b[2].set(this.c,this.a);for(var k=0;k<b.length;k++){b[k].closestPointToPoint(c,!0,d);var m=c.distanceToSquared(d);
14126 m<h&&(h=m,g.copy(d))}}return g}}(),equals:function(a){return a.a.equals(this.a)&&a.b.equals(this.b)&&a.c.equals(this.c)}});la.prototype=Object.assign(Object.create(z.prototype),{constructor:la,isMesh:!0,setDrawMode:function(a){this.drawMode=a},copy:function(a){z.prototype.copy.call(this,a);this.drawMode=a.drawMode;return this},updateMorphTargets:function(){var a=this.geometry,b,c;if(a.isBufferGeometry){if(a=a.morphAttributes,b=Object.keys(a),0<b.length){var d=a[b[0]];if(void 0!==d)for(this.morphTargetInfluences=
14127 [],this.morphTargetDictionary={},a=0,b=d.length;a<b;a++)c=d[a].name||String(a),this.morphTargetInfluences.push(0),this.morphTargetDictionary[c]=a}}else if(d=a.morphTargets,void 0!==d&&0<d.length)for(this.morphTargetInfluences=[],this.morphTargetDictionary={},a=0,b=d.length;a<b;a++)c=d[a].name||String(a),this.morphTargetInfluences.push(0),this.morphTargetDictionary[c]=a},raycast:function(){function a(a,b,c,d,e,f,g){Ta.barycoordFromPoint(a,b,c,d,t);e.multiplyScalar(t.x);f.multiplyScalar(t.y);g.multiplyScalar(t.z);
14128 e.add(f).add(g);return e.clone()}function b(a,b,c,d,e,f,g){var h=a.material;if(null===(1===h.side?c.intersectTriangle(f,e,d,!0,g):c.intersectTriangle(d,e,f,2!==h.side,g)))return null;x.copy(g);x.applyMatrix4(a.matrixWorld);c=b.ray.origin.distanceTo(x);return c<b.near||c>b.far?null:{distance:c,point:x.clone(),object:a}}function c(c,d,e,f,m,q,l,n){g.fromBufferAttribute(f,q);h.fromBufferAttribute(f,l);k.fromBufferAttribute(f,n);if(c=b(c,d,e,g,h,k,y))m&&(p.fromBufferAttribute(m,q),r.fromBufferAttribute(m,
14129 l),ca.fromBufferAttribute(m,n),c.uv=a(y,g,h,k,p,r,ca)),c.face=new Sa(q,l,n,Ta.normal(g,h,k)),c.faceIndex=q;return c}var d=new K,e=new kb,f=new Ea,g=new n,h=new n,k=new n,m=new n,q=new n,l=new n,p=new C,r=new C,ca=new C,t=new n,y=new n,x=new n;return function(n,t){var w=this.geometry,x=this.material,B=this.matrixWorld;if(void 0!==x&&(null===w.boundingSphere&&w.computeBoundingSphere(),f.copy(w.boundingSphere),f.applyMatrix4(B),!1!==n.ray.intersectsSphere(f)&&(d.getInverse(B),e.copy(n.ray).applyMatrix4(d),
14130 null===w.boundingBox||!1!==e.intersectsBox(w.boundingBox)))){var D;if(w.isBufferGeometry){var O,C,x=w.index,F=w.attributes.position,B=w.attributes.uv,z,T;if(null!==x)for(z=0,T=x.count;z<T;z+=3){if(w=x.getX(z),O=x.getX(z+1),C=x.getX(z+2),D=c(this,n,e,F,B,w,O,C))D.faceIndex=Math.floor(z/3),t.push(D)}else for(z=0,T=F.count;z<T;z+=3)if(w=z,O=z+1,C=z+2,D=c(this,n,e,F,B,w,O,C))D.index=w,t.push(D)}else if(w.isGeometry){var E,B=Array.isArray(x);z=w.vertices;T=w.faces;O=w.faceVertexUvs[0];0<O.length&&(F=O);
14131 for(var G=0,K=T.length;G<K;G++){var P=T[G];D=B?x[P.materialIndex]:x;if(void 0!==D){O=z[P.a];C=z[P.b];E=z[P.c];if(!0===D.morphTargets){D=w.morphTargets;var M=this.morphTargetInfluences;g.set(0,0,0);h.set(0,0,0);k.set(0,0,0);for(var V=0,pa=D.length;V<pa;V++){var S=M[V];if(0!==S){var N=D[V].vertices;g.addScaledVector(m.subVectors(N[P.a],O),S);h.addScaledVector(q.subVectors(N[P.b],C),S);k.addScaledVector(l.subVectors(N[P.c],E),S)}}g.add(O);h.add(C);k.add(E);O=g;C=h;E=k}if(D=b(this,n,e,O,C,E,y))F&&F[G]&&
14132 (M=F[G],p.copy(M[0]),r.copy(M[1]),ca.copy(M[2]),D.uv=a(y,O,C,E,p,r,ca)),D.face=P,D.faceIndex=G,t.push(D)}}}}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});var bg=0;kd.prototype=Object.assign(Object.create(qa.prototype),{constructor:kd,isArrayCamera:!0});Ib.prototype.isFogExp2=!0;Ib.prototype.clone=function(){return new Ib(this.color.getHex(),this.density)};Ib.prototype.toJSON=function(a){return{type:"FogExp2",color:this.color.getHex(),density:this.density}};
14133 Jb.prototype.isFog=!0;Jb.prototype.clone=function(){return new Jb(this.color.getHex(),this.near,this.far)};Jb.prototype.toJSON=function(a){return{type:"Fog",color:this.color.getHex(),near:this.near,far:this.far}};ld.prototype=Object.assign(Object.create(z.prototype),{constructor:ld,copy:function(a,b){z.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=a.overrideMaterial.clone());
14134 this.autoUpdate=a.autoUpdate;this.matrixAutoUpdate=a.matrixAutoUpdate;return this},toJSON:function(a){var b=z.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}});Yd.prototype=Object.assign(Object.create(z.prototype),{constructor:Yd,isLensFlare:!0,copy:function(a){z.prototype.copy.call(this,a);this.positionScreen.copy(a.positionScreen);this.customUpdateCallback=a.customUpdateCallback;for(var b=
14135 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 G(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,d=2*-this.positionScreen.x,e=2*-this.positionScreen.y;for(a=0;a<b;a++)c=this.lensFlares[a],
14136 c.x=this.positionScreen.x+d*c.distance,c.y=this.positionScreen.y+e*c.distance,c.wantedRotation=c.x*Math.PI*.25,c.rotation+=.25*(c.wantedRotation-c.rotation)}});bb.prototype=Object.create(U.prototype);bb.prototype.constructor=bb;bb.prototype.isSpriteMaterial=!0;bb.prototype.copy=function(a){U.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.rotation=a.rotation;return this};xc.prototype=Object.assign(Object.create(z.prototype),{constructor:xc,isSprite:!0,raycast:function(){var a=
14137 new n,b=new n,c=new n;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)}});yc.prototype=Object.assign(Object.create(z.prototype),{constructor:yc,copy:function(a){z.prototype.copy.call(this,a,
14138 !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 n;return function(b,c){a.setFromMatrixPosition(this.matrixWorld);var d=
14139 b.ray.origin.distanceTo(a);this.getObjectForDistance(d).raycast(b,c)}}(),update:function(){var a=new n,b=new n;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=z.prototype.toJSON.call(this,a);a.object.levels=
14140 [];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(zc.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,c;b=0;for(c=this.bones.length;b<c;b++)(a=this.bones[b])&&a.matrixWorld.getInverse(this.boneInverses[b]);b=0;for(c=this.bones.length;b<
14141 c;b++)if(a=this.bones[b])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 zc(this.bones,
14142 this.boneInverses)}});md.prototype=Object.assign(Object.create(z.prototype),{constructor:md,isBone:!0});nd.prototype=Object.assign(Object.create(la.prototype),{constructor:nd,isSkinnedMesh:!0,initBones:function(){var a=[],b,c,d,e;if(this.geometry&&void 0!==this.geometry.bones){d=0;for(e=this.geometry.bones.length;d<e;d++)c=this.geometry.bones[d],b=new md,a.push(b),b.name=c.name,b.position.fromArray(c.pos),b.quaternion.fromArray(c.rotq),void 0!==c.scl&&b.scale.fromArray(c.scl);d=0;for(e=this.geometry.bones.length;d<
14143 e;d++)c=this.geometry.bones[d],-1!==c.parent&&null!==c.parent&&void 0!==a[c.parent]?a[c.parent].add(a[d]):this.add(a[d])}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,b;if(this.geometry&&this.geometry.isGeometry)for(b=0;b<this.geometry.skinWeights.length;b++){var c=
14144 this.geometry.skinWeights[b];a=1/c.lengthManhattan();Infinity!==a?c.multiplyScalar(a):c.set(1,0,0,0)}else if(this.geometry&&this.geometry.isBufferGeometry){var c=new fa,d=this.geometry.attributes.skinWeight;for(b=0;b<d.count;b++)c.x=d.getX(b),c.y=d.getY(b),c.z=d.getZ(b),c.w=d.getW(b),a=1/c.lengthManhattan(),Infinity!==a?c.multiplyScalar(a):c.set(1,0,0,0),d.setXYZW(b,c.x,c.y,c.z,c.w)}},updateMatrixWorld:function(a){la.prototype.updateMatrixWorld.call(this,a);"attached"===this.bindMode?this.bindMatrixInverse.getInverse(this.matrixWorld):
14145 "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)}});ea.prototype=Object.create(U.prototype);ea.prototype.constructor=ea;ea.prototype.isLineBasicMaterial=!0;ea.prototype.copy=function(a){U.prototype.copy.call(this,a);this.color.copy(a.color);this.linewidth=a.linewidth;this.linecap=a.linecap;this.linejoin=a.linejoin;
14146 return this};sa.prototype=Object.assign(Object.create(z.prototype),{constructor:sa,isLine:!0,raycast:function(){var a=new K,b=new kb,c=new Ea;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 n,m=new n,h=new n,q=new n,l=this&&this.isLineSegments?2:1;if(g.isBufferGeometry){var p=g.index,
14147 r=g.attributes.position.array;if(null!==p)for(var p=p.array,g=0,ca=p.length-1;g<ca;g+=l){var t=p[g+1];k.fromArray(r,3*p[g]);m.fromArray(r,3*t);t=b.distanceSqToSegment(k,m,q,h);t>f||(q.applyMatrix4(this.matrixWorld),t=d.ray.origin.distanceTo(q),t<d.near||t>d.far||e.push({distance:t,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}else for(g=0,ca=r.length/3-1;g<ca;g+=l)k.fromArray(r,3*g),m.fromArray(r,3*g+3),t=b.distanceSqToSegment(k,m,q,h),t>f||(q.applyMatrix4(this.matrixWorld),
14148 t=d.ray.origin.distanceTo(q),t<d.near||t>d.far||e.push({distance:t,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}else if(g.isGeometry)for(k=g.vertices,m=k.length,g=0;g<m-1;g+=l)t=b.distanceSqToSegment(k[g],k[g+1],q,h),t>f||(q.applyMatrix4(this.matrixWorld),t=d.ray.origin.distanceTo(q),t<d.near||t>d.far||e.push({distance:t,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}}}(),clone:function(){return(new this.constructor(this.geometry,
14149 this.material)).copy(this)}});Q.prototype=Object.assign(Object.create(sa.prototype),{constructor:Q,isLineSegments:!0});od.prototype=Object.assign(Object.create(sa.prototype),{constructor:od,isLineLoop:!0});Fa.prototype=Object.create(U.prototype);Fa.prototype.constructor=Fa;Fa.prototype.isPointsMaterial=!0;Fa.prototype.copy=function(a){U.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.size=a.size;this.sizeAttenuation=a.sizeAttenuation;return this};Kb.prototype=Object.assign(Object.create(z.prototype),
14150 {constructor:Kb,isPoints:!0,raycast:function(){var a=new K,b=new kb,c=new Ea;return function(d,e){function f(a,c){var f=b.distanceSqToPoint(a);if(f<q){var h=b.closestPointToPoint(a);h.applyMatrix4(k);var m=d.ray.origin.distanceTo(h);m<d.near||m>d.far||e.push({distance:m,distanceToRay:Math.sqrt(f),point:h.clone(),index:c,face:null,object:g})}}var g=this,h=this.geometry,k=this.matrixWorld,m=d.params.Points.threshold;null===h.boundingSphere&&h.computeBoundingSphere();c.copy(h.boundingSphere);c.applyMatrix4(k);
14151 c.radius+=m;if(!1!==d.ray.intersectsSphere(c)){a.getInverse(k);b.copy(d.ray).applyMatrix4(a);var m=m/((this.scale.x+this.scale.y+this.scale.z)/3),q=m*m,m=new n;if(h.isBufferGeometry){var l=h.index,h=h.attributes.position.array;if(null!==l)for(var p=l.array,l=0,r=p.length;l<r;l++){var ca=p[l];m.fromArray(h,3*ca);f(m,ca)}else for(l=0,p=h.length/3;l<p;l++)m.fromArray(h,3*l),f(m,l)}else for(m=h.vertices,l=0,p=m.length;l<p;l++)f(m[l],l)}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});
14152 Ac.prototype=Object.assign(Object.create(z.prototype),{constructor:Ac});pd.prototype=Object.create(ba.prototype);pd.prototype.constructor=pd;Lb.prototype=Object.create(ba.prototype);Lb.prototype.constructor=Lb;Lb.prototype.isCompressedTexture=!0;qd.prototype=Object.create(ba.prototype);qd.prototype.constructor=qd;Bc.prototype=Object.create(ba.prototype);Bc.prototype.constructor=Bc;Bc.prototype.isDepthTexture=!0;Mb.prototype=Object.create(E.prototype);Mb.prototype.constructor=Mb;Cc.prototype=Object.create(J.prototype);
14153 Cc.prototype.constructor=Cc;Nb.prototype=Object.create(E.prototype);Nb.prototype.constructor=Nb;Dc.prototype=Object.create(J.prototype);Dc.prototype.constructor=Dc;za.prototype=Object.create(E.prototype);za.prototype.constructor=za;Ec.prototype=Object.create(J.prototype);Ec.prototype.constructor=Ec;Ob.prototype=Object.create(za.prototype);Ob.prototype.constructor=Ob;Fc.prototype=Object.create(J.prototype);Fc.prototype.constructor=Fc;lb.prototype=Object.create(za.prototype);lb.prototype.constructor=
14154 lb;Gc.prototype=Object.create(J.prototype);Gc.prototype.constructor=Gc;Pb.prototype=Object.create(za.prototype);Pb.prototype.constructor=Pb;Hc.prototype=Object.create(J.prototype);Hc.prototype.constructor=Hc;Qb.prototype=Object.create(za.prototype);Qb.prototype.constructor=Qb;Ic.prototype=Object.create(J.prototype);Ic.prototype.constructor=Ic;Rb.prototype=Object.create(E.prototype);Rb.prototype.constructor=Rb;Jc.prototype=Object.create(J.prototype);Jc.prototype.constructor=Jc;Sb.prototype=Object.create(E.prototype);
14155 Sb.prototype.constructor=Sb;Kc.prototype=Object.create(J.prototype);Kc.prototype.constructor=Kc;Tb.prototype=Object.create(E.prototype);Tb.prototype.constructor=Tb;var Ia={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,h,k;if(0<Ia.area(a))for(h=0;h<c;h++)e[h]=h;else for(h=0;h<c;h++)e[h]=c-1-h;var m=2*c;for(h=c-1;2<c;){if(0>=m--){console.warn("THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()");
14156 break}g=h;c<=g&&(g=0);h=g+1;c<=h&&(h=0);k=h+1;c<=k&&(k=0);var q;a:{var l,p,r,n,t,y,x,u;l=a[e[g]].x;p=a[e[g]].y;r=a[e[h]].x;n=a[e[h]].y;t=a[e[k]].x;y=a[e[k]].y;if(0>=(r-l)*(y-p)-(n-p)*(t-l))q=!1;else{var H,w,I,z,D,O,B,C,E,G;H=t-r;w=y-n;I=l-t;z=p-y;D=r-l;O=n-p;for(q=0;q<c;q++)if(x=a[e[q]].x,u=a[e[q]].y,!(x===l&&u===p||x===r&&u===n||x===t&&u===y)&&(B=x-l,C=u-p,E=x-r,G=u-n,x-=t,u-=y,E=H*G-w*E,B=D*C-O*B,C=I*u-z*x,E>=-Number.EPSILON&&C>=-Number.EPSILON&&B>=-Number.EPSILON)){q=!1;break a}q=!0}}if(q){d.push([a[e[g]],
14157 a[e[h]],a[e[k]]]);f.push([e[g],e[h],e[k]]);g=h;for(k=h+1;k<c;g++,k++)e[g]=e[k];c--;m=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,m=e.y-c.y,q=a.x-c.x,l=a.y-c.y,p=h*k-g*m,n=h*q-g*l;if(Math.abs(p)>Number.EPSILON){if(0<p){if(0>n||n>p)return[];k=m*q-k*
14158 l;if(0>k||k>p)return[]}else{if(0<n||n<p)return[];k=m*q-k*l;if(0<k||k<p)return[]}if(0===k)return!f||0!==n&&n!==p?[a]:[];if(k===p)return!f||0!==n&&n!==p?[b]:[];if(0===n)return[c];if(n===p)return[e];f=k/p;return[{x:a.x+f*g,y:a.y+f*h}]}if(0!==n||m*q!==k*l)return[];h=0===g&&0===h;k=0===k&&0===m;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,p=c.x,m=e,c=e.x):(b=e,p=e.x,m=c,c=c.x)):
14159 (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,p=c.y,m=e,c=e.y):(b=e,p=e.y,m=c,c=c.y));return k<=p?a<p?[]:a===p?f?[]:[b]:a<=c?[b,h]:[b,m]:k>c?[]:k===c?f?[]:[g]:a<=c?[g,h]:[g,m]}function f(a,b,c,d){var e=b.x-a.x,f=b.y-a.y;b=c.x-a.x;c=c.y-a.y;var g=d.x-a.x;d=d.y-a.y;a=e*c-f*b;e=e*d-f*g;return Math.abs(a)>Number.EPSILON?(b=g*c-d*b,0<a?0<=e&&0<=b:0<=e||0<=b):0<e}c(a);b.forEach(c);var g,h,k,m,q,l={};k=a.concat();g=0;for(h=b.length;g<h;g++)Array.prototype.push.apply(k,b[g]);g=0;for(h=
14160 k.length;g<h;g++)q=k[g].x+":"+k[g].y,void 0!==l[q]&&console.warn("THREE.ShapeUtils: Duplicate point",q,g),l[q]=g;g=function(a,b){function c(a,b){var d=h.length-1,e=a-1;0>e&&(e=d);var g=a+1;g>d&&(g=0);d=f(h[a],h[e],h[g],k[b]);if(!d)return!1;d=k.length-1;e=b-1;0>e&&(e=d);g=b+1;g>d&&(g=0);return(d=f(k[b],k[e],k[g],h[a]))?!0:!1}function d(a,b){var c,f;for(c=0;c<h.length;c++)if(f=c+1,f%=h.length,f=e(a,b,h[c],h[f],!0),0<f.length)return!0;return!1}function g(a,c){var d,f,h,k;for(d=0;d<m.length;d++)for(f=
14161 b[m[d]],h=0;h<f.length;h++)if(k=h+1,k%=f.length,k=e(a,c,f[h],f[k],!0),0<k.length)return!0;return!1}var h=a.concat(),k,m=[],q,l,p,n,v,B=[],C,z,E,G=0;for(q=b.length;G<q;G++)m.push(G);C=0;for(var K=2*m.length;0<m.length;){K--;if(0>K){console.log("Infinite Loop! Holes left:"+m.length+", Probably Hole outside Shape!");break}for(l=C;l<h.length;l++){p=h[l];q=-1;for(G=0;G<m.length;G++)if(n=m[G],v=p.x+":"+p.y+":"+n,void 0===B[v]){k=b[n];for(z=0;z<k.length;z++)if(n=k[z],c(l,z)&&!d(p,n)&&!g(p,n)){q=z;m.splice(G,
14162 1);C=h.slice(0,l+1);n=h.slice(l);z=k.slice(q);E=k.slice(0,q+1);h=C.concat(z).concat(E).concat(n);C=l;break}if(0<=q)break;B[v]=!0}if(0<=q)break}}return h}(a,b);var p=Ia.triangulate(g,!1);g=0;for(h=p.length;g<h;g++)for(m=p[g],k=0;3>k;k++)q=m[k].x+":"+m[k].y,q=l[q],void 0!==q&&(m[k]=q);return p.concat()},isClockWise:function(a){return 0>Ia.area(a)}};cb.prototype=Object.create(J.prototype);cb.prototype.constructor=cb;Ga.prototype=Object.create(E.prototype);Ga.prototype.constructor=Ga;Ga.prototype.getArrays=
14163 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",new B(b.arrays.position,3));this.addAttribute("uv",new B(b.arrays.uv,2))};
14164 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,e,f;e=a.x-b.x;f=a.y-b.y;d=c.x-a.x;var g=c.y-a.y,h=e*e+f*f;if(Math.abs(e*g-f*d)>Number.EPSILON){var k=Math.sqrt(h),m=Math.sqrt(d*d+g*g),h=b.x-f/k;b=b.y+e/k;g=((c.x-g/m-h)*g-(c.y+d/m-b)*d)/(e*g-f*d);d=h+e*g-a.x;e=b+f*g-a.y;f=d*d+e*e;if(2>=f)return new C(d,e);f=Math.sqrt(f/2)}else a=!1,e>Number.EPSILON?d>Number.EPSILON&&
14165 (a=!0):e<-Number.EPSILON?d<-Number.EPSILON&&(a=!0):Math.sign(f)===Math.sign(g)&&(a=!0),a?(d=-f,f=Math.sqrt(h)):(d=e,e=f,f=Math.sqrt(h/2));return new C(d/f,e/f)}function e(a,b){var c,d;for(L=a.length;0<=--L;){c=L;d=L-1;0>d&&(d=a.length-1);var e,f=H+2*y;for(e=0;e<f;e++){var g=ba*e,m=ba*(e+1),l=b+d+g,p=b+d+m,m=b+c+m;h(b+c+g);h(l);h(m);h(l);h(p);h(m);g=q.length/3;g=D.generateSideWallUV(Z,q,g-6,g-3,g-2,g-1);k(g[0]);k(g[1]);k(g[3]);k(g[1]);k(g[2]);k(g[3])}}}function f(a,b,c){r.push(a);r.push(b);r.push(c)}
14166 function g(a,b,c){h(a);h(b);h(c);a=q.length/3;a=D.generateTopUV(Z,q,a-3,a-2,a-1);k(a[0]);k(a[1]);k(a[2])}function h(a){l.push(q.length/3);q.push(r[3*a+0]);q.push(r[3*a+1]);q.push(r[3*a+2])}function k(a){p.push(a.x);p.push(a.y)}var m=b.arrays?b.arrays:this.getArrays(),q=m.position,l=m.index,p=m.uv,r=[],m=void 0!==b.amount?b.amount:100,z=void 0!==b.bevelThickness?b.bevelThickness:6,t=void 0!==b.bevelSize?b.bevelSize:z-2,y=void 0!==b.bevelSegments?b.bevelSegments:3,x=void 0!==b.bevelEnabled?b.bevelEnabled:
14167 !0,u=void 0!==b.curveSegments?b.curveSegments:12,H=void 0!==b.steps?b.steps:1,w=b.extrudePath,I,G=!1,D=void 0!==b.UVGenerator?b.UVGenerator:cb.WorldUVGenerator,O,E,F,K;w&&(I=w.getSpacedPoints(H),G=!0,x=!1,O=void 0!==b.frames?b.frames:w.computeFrenetFrames(H,!1),E=new n,F=new n,K=new n);x||(t=z=y=0);var T,J,U,Z=this,w=a.extractPoints(u),u=w.shape,P=w.holes;if(!Ia.isClockWise(u))for(u=u.reverse(),J=0,U=P.length;J<U;J++)T=P[J],Ia.isClockWise(T)&&(P[J]=T.reverse());var M=Ia.triangulateShape(u,P),V=u;
14168 J=0;for(U=P.length;J<U;J++)T=P[J],u=u.concat(T);var R,S,N,Y,Q,ba=u.length,X,fa=M.length,w=[],L=0;N=V.length;R=N-1;for(S=L+1;L<N;L++,R++,S++)R===N&&(R=0),S===N&&(S=0),w[L]=d(V[L],V[R],V[S]);var ha=[],ea,ia=w.concat();J=0;for(U=P.length;J<U;J++){T=P[J];ea=[];L=0;N=T.length;R=N-1;for(S=L+1;L<N;L++,R++,S++)R===N&&(R=0),S===N&&(S=0),ea[L]=d(T[L],T[R],T[S]);ha.push(ea);ia=ia.concat(ea)}for(R=0;R<y;R++){N=R/y;Y=z*Math.cos(N*Math.PI/2);S=t*Math.sin(N*Math.PI/2);L=0;for(N=V.length;L<N;L++)Q=c(V[L],w[L],S),
14169 f(Q.x,Q.y,-Y);J=0;for(U=P.length;J<U;J++)for(T=P[J],ea=ha[J],L=0,N=T.length;L<N;L++)Q=c(T[L],ea[L],S),f(Q.x,Q.y,-Y)}S=t;for(L=0;L<ba;L++)Q=x?c(u[L],ia[L],S):u[L],G?(F.copy(O.normals[0]).multiplyScalar(Q.x),E.copy(O.binormals[0]).multiplyScalar(Q.y),K.copy(I[0]).add(F).add(E),f(K.x,K.y,K.z)):f(Q.x,Q.y,0);for(N=1;N<=H;N++)for(L=0;L<ba;L++)Q=x?c(u[L],ia[L],S):u[L],G?(F.copy(O.normals[N]).multiplyScalar(Q.x),E.copy(O.binormals[N]).multiplyScalar(Q.y),K.copy(I[N]).add(F).add(E),f(K.x,K.y,K.z)):f(Q.x,Q.y,
14170 m/H*N);for(R=y-1;0<=R;R--){N=R/y;Y=z*Math.cos(N*Math.PI/2);S=t*Math.sin(N*Math.PI/2);L=0;for(N=V.length;L<N;L++)Q=c(V[L],w[L],S),f(Q.x,Q.y,m+Y);J=0;for(U=P.length;J<U;J++)for(T=P[J],ea=ha[J],L=0,N=T.length;L<N;L++)Q=c(T[L],ea[L],S),G?f(Q.x,Q.y+I[H-1].y,I[H-1].x+Y):f(Q.x,Q.y,m+Y)}(function(){var a=q.length/3;if(x){var c=0*ba;for(L=0;L<fa;L++)X=M[L],g(X[2]+c,X[1]+c,X[0]+c);c=ba*(H+2*y);for(L=0;L<fa;L++)X=M[L],g(X[0]+c,X[1]+c,X[2]+c)}else{for(L=0;L<fa;L++)X=M[L],g(X[2],X[1],X[0]);for(L=0;L<fa;L++)X=
14171 M[L],g(X[0]+ba*H,X[1]+ba*H,X[2]+ba*H)}Z.addGroup(a,q.length/3-a,void 0!==b.material?b.material:0)})();(function(){var a=q.length/3,c=0;e(V,c);c+=V.length;J=0;for(U=P.length;J<U;J++)T=P[J],e(T,c),c+=T.length;Z.addGroup(a,q.length/3-a,void 0!==b.extrudeMaterial?b.extrudeMaterial:1)})();b.arrays||(this.setIndex(l),this.addAttribute("position",new B(q,3)),this.addAttribute("uv",new B(b.arrays.uv,2)))};cb.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*
14172 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 m=b[3*e],l=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(m,1-e),new C(n,1-b)]:[new C(g,1-c),new C(k,1-d),new C(l,1-e),new C(p,1-b)]}};Lc.prototype=Object.create(J.prototype);Lc.prototype.constructor=Lc;Ub.prototype=Object.create(Ga.prototype);Ub.prototype.constructor=Ub;Mc.prototype=
14173 Object.create(J.prototype);Mc.prototype.constructor=Mc;mb.prototype=Object.create(E.prototype);mb.prototype.constructor=mb;Nc.prototype=Object.create(J.prototype);Nc.prototype.constructor=Nc;Vb.prototype=Object.create(E.prototype);Vb.prototype.constructor=Vb;Oc.prototype=Object.create(J.prototype);Oc.prototype.constructor=Oc;Wb.prototype=Object.create(E.prototype);Wb.prototype.constructor=Wb;Xb.prototype=Object.create(J.prototype);Xb.prototype.constructor=Xb;Yb.prototype=Object.create(E.prototype);
14174 Yb.prototype.constructor=Yb;Zb.prototype=Object.create(E.prototype);Zb.prototype.constructor=Zb;nb.prototype=Object.create(J.prototype);nb.prototype.constructor=nb;Ua.prototype=Object.create(E.prototype);Ua.prototype.constructor=Ua;Pc.prototype=Object.create(nb.prototype);Pc.prototype.constructor=Pc;Qc.prototype=Object.create(Ua.prototype);Qc.prototype.constructor=Qc;Rc.prototype=Object.create(J.prototype);Rc.prototype.constructor=Rc;$b.prototype=Object.create(E.prototype);$b.prototype.constructor=
14175 $b;var Ma=Object.freeze({WireframeGeometry:Mb,ParametricGeometry:Cc,ParametricBufferGeometry:Nb,TetrahedronGeometry:Ec,TetrahedronBufferGeometry:Ob,OctahedronGeometry:Fc,OctahedronBufferGeometry:lb,IcosahedronGeometry:Gc,IcosahedronBufferGeometry:Pb,DodecahedronGeometry:Hc,DodecahedronBufferGeometry:Qb,PolyhedronGeometry:Dc,PolyhedronBufferGeometry:za,TubeGeometry:Ic,TubeBufferGeometry:Rb,TorusKnotGeometry:Jc,TorusKnotBufferGeometry:Sb,TorusGeometry:Kc,TorusBufferGeometry:Tb,TextGeometry:Lc,TextBufferGeometry:Ub,
14176 SphereGeometry:Mc,SphereBufferGeometry:mb,RingGeometry:Nc,RingBufferGeometry:Vb,PlaneGeometry:vc,PlaneBufferGeometry:jb,LatheGeometry:Oc,LatheBufferGeometry:Wb,ShapeGeometry:Xb,ShapeBufferGeometry:Yb,ExtrudeGeometry:cb,ExtrudeBufferGeometry:Ga,EdgesGeometry:Zb,ConeGeometry:Pc,ConeBufferGeometry:Qc,CylinderGeometry:nb,CylinderBufferGeometry:Ua,CircleGeometry:Rc,CircleBufferGeometry:$b,BoxGeometry:Gb,BoxBufferGeometry:ib});ac.prototype=Object.create(ra.prototype);ac.prototype.constructor=ac;ac.prototype.isShadowMaterial=
14177 !0;bc.prototype=Object.create(ra.prototype);bc.prototype.constructor=bc;bc.prototype.isRawShaderMaterial=!0;Pa.prototype=Object.create(U.prototype);Pa.prototype.constructor=Pa;Pa.prototype.isMeshStandardMaterial=!0;Pa.prototype.copy=function(a){U.prototype.copy.call(this,a);this.defines={STANDARD:""};this.color.copy(a.color);this.roughness=a.roughness;this.metalness=a.metalness;this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=
14178 a.aoMapIntensity;this.emissive.copy(a.emissive);this.emissiveMap=a.emissiveMap;this.emissiveIntensity=a.emissiveIntensity;this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.roughnessMap=a.roughnessMap;this.metalnessMap=a.metalnessMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.envMapIntensity=a.envMapIntensity;
14179 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};ob.prototype=Object.create(Pa.prototype);ob.prototype.constructor=ob;ob.prototype.isMeshPhysicalMaterial=!0;ob.prototype.copy=function(a){Pa.prototype.copy.call(this,a);this.defines={PHYSICAL:""};this.reflectivity=
14180 a.reflectivity;this.clearCoat=a.clearCoat;this.clearCoatRoughness=a.clearCoatRoughness;return this};Ja.prototype=Object.create(U.prototype);Ja.prototype.constructor=Ja;Ja.prototype.isMeshPhongMaterial=!0;Ja.prototype.copy=function(a){U.prototype.copy.call(this,a);this.color.copy(a.color);this.specular.copy(a.specular);this.shininess=a.shininess;this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=a.aoMapIntensity;this.emissive.copy(a.emissive);
14181 this.emissiveMap=a.emissiveMap;this.emissiveIntensity=a.emissiveIntensity;this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.specularMap=a.specularMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.combine=a.combine;this.reflectivity=a.reflectivity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;
14182 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};pb.prototype=Object.create(Ja.prototype);pb.prototype.constructor=pb;pb.prototype.isMeshToonMaterial=!0;pb.prototype.copy=function(a){Ja.prototype.copy.call(this,a);this.gradientMap=a.gradientMap;return this};qb.prototype=Object.create(U.prototype);qb.prototype.constructor=
14183 qb;qb.prototype.isMeshNormalMaterial=!0;qb.prototype.copy=function(a){U.prototype.copy.call(this,a);this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};
14184 rb.prototype=Object.create(U.prototype);rb.prototype.constructor=rb;rb.prototype.isMeshLambertMaterial=!0;rb.prototype.copy=function(a){U.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=a.aoMapIntensity;this.emissive.copy(a.emissive);this.emissiveMap=a.emissiveMap;this.emissiveIntensity=a.emissiveIntensity;this.specularMap=a.specularMap;this.alphaMap=a.alphaMap;this.envMap=
14185 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};sb.prototype=Object.create(U.prototype);sb.prototype.constructor=sb;sb.prototype.isLineDashedMaterial=!0;sb.prototype.copy=function(a){U.prototype.copy.call(this,
14186 a);this.color.copy(a.color);this.linewidth=a.linewidth;this.scale=a.scale;this.dashSize=a.dashSize;this.gapSize=a.gapSize;return this};var mg=Object.freeze({ShadowMaterial:ac,SpriteMaterial:bb,RawShaderMaterial:bc,ShaderMaterial:ra,PointsMaterial:Fa,MeshPhysicalMaterial:ob,MeshStandardMaterial:Pa,MeshPhongMaterial:Ja,MeshToonMaterial:pb,MeshNormalMaterial:qb,MeshLambertMaterial:rb,MeshDepthMaterial:Za,MeshBasicMaterial:ya,LineDashedMaterial:sb,LineBasicMaterial:ea,Material:U}),ed={enabled:!1,files:{},
14187 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={}}},va=new Zd;Object.assign(Ka.prototype,{load:function(a,b,c,d){void 0===a&&(a="");void 0!==this.path&&(a=this.path+a);var e=this,f=ed.get(a);if(void 0!==f)return e.manager.itemStart(a),setTimeout(function(){b&&b(f);e.manager.itemEnd(a)},0),f;var g=a.match(/^data:(.*?)(;base64)?,(.*)$/);if(g){var h=g[1],k=!!g[2],g=
14188 g[3],g=window.decodeURIComponent(g);k&&(g=window.atob(g));try{var m,l=(this.responseType||"").toLowerCase();switch(l){case "arraybuffer":case "blob":m=new ArrayBuffer(g.length);for(var n=new Uint8Array(m),k=0;k<g.length;k++)n[k]=g.charCodeAt(k);"blob"===l&&(m=new Blob([m],{type:h}));break;case "document":m=(new DOMParser).parseFromString(g,h);break;case "json":m=JSON.parse(g);break;default:m=g}window.setTimeout(function(){b&&b(m);e.manager.itemEnd(a)},0)}catch(r){window.setTimeout(function(){d&&d(r);
14189 e.manager.itemEnd(a);e.manager.itemError(a)},0)}}else{var p=new XMLHttpRequest;p.open("GET",a,!0);p.addEventListener("load",function(c){var f=c.target.response;ed.add(a,f);200===this.status?(b&&b(f),e.manager.itemEnd(a)):0===this.status?(console.warn("THREE.FileLoader: HTTP Status 0 received."),b&&b(f),e.manager.itemEnd(a)):(d&&d(c),e.manager.itemEnd(a),e.manager.itemError(a))},!1);void 0!==c&&p.addEventListener("progress",function(a){c(a)},!1);p.addEventListener("error",function(b){d&&d(b);e.manager.itemEnd(a);
14190 e.manager.itemError(a)},!1);void 0!==this.responseType&&(p.responseType=this.responseType);void 0!==this.withCredentials&&(p.withCredentials=this.withCredentials);p.overrideMimeType&&p.overrideMimeType(void 0!==this.mimeType?this.mimeType:"text/plain");for(h in this.requestHeader)p.setRequestHeader(h,this.requestHeader[h]);p.send(null)}e.manager.itemStart(a);return p},setPath:function(a){this.path=a;return this},setResponseType:function(a){this.responseType=a;return this},setWithCredentials:function(a){this.withCredentials=
14191 a;return this},setMimeType:function(a){this.mimeType=a;return this},setRequestHeader:function(a){this.requestHeader=a;return this}});Object.assign(Oe.prototype,{load:function(a,b,c,d){function e(e){k.load(a[e],function(a){a=f._parser(a,!0);g[e]={width:a.width,height:a.height,format:a.format,mipmaps:a.mipmaps};m+=1;6===m&&(1===a.mipmapCount&&(h.minFilter=1006),h.format=a.format,h.needsUpdate=!0,b&&b(h))},c,d)}var f=this,g=[],h=new Lb;h.image=g;var k=new Ka(this.manager);k.setPath(this.path);k.setResponseType("arraybuffer");
14192 if(Array.isArray(a))for(var m=0,l=0,n=a.length;l<n;++l)e(l);else k.load(a,function(a){a=f._parser(a,!0);if(a.isCubemap)for(var c=a.mipmaps.length/a.mipmapCount,d=0;d<c;d++){g[d]={mipmaps:[]};for(var e=0;e<a.mipmapCount;e++)g[d].mipmaps.push(a.mipmaps[d*a.mipmapCount+e]),g[d].format=a.format,g[d].width=a.width,g[d].height=a.height}else h.image.width=a.width,h.image.height=a.height,h.mipmaps=a.mipmaps;1===a.mipmapCount&&(h.minFilter=1006);h.format=a.format;h.needsUpdate=!0;b&&b(h)},c,d);return h},setPath:function(a){this.path=
14193 a;return this}});Object.assign($d.prototype,{load:function(a,b,c,d){var e=this,f=new db,g=new Ka(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!==a.magFilter?a.magFilter:1006,f.minFilter=void 0!==a.minFilter?a.minFilter:1008,f.anisotropy=void 0!==a.anisotropy?
14194 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(Sc.prototype,{load:function(a,b,c,d){void 0===a&&(a="");void 0!==this.path&&(a=this.path+a);var e=this,f=ed.get(a);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");
14195 c.addEventListener("load",function(){ed.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=a;return this},setPath:function(a){this.path=a;return this}});Object.assign(ae.prototype,{load:function(a,b,c,d){function e(c){g.load(a[c],function(a){f.images[c]=
14196 a;h++;6===h&&(f.needsUpdate=!0,b&&b(f))},void 0,d)}var f=new Xa,g=new Sc(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(rd.prototype,{load:function(a,b,c,d){var e=new Sc(this.manager);e.setCrossOrigin(this.crossOrigin);e.setPath(this.path);var f=new ba;f.image=e.load(a,function(){var c=0<a.search(/\.(jpg|jpeg)$/)||
14197 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}});na.prototype=Object.assign(Object.create(z.prototype),{constructor:na,isLight:!0,copy:function(a){z.prototype.copy.call(this,a);this.color.copy(a.color);this.intensity=a.intensity;return this},toJSON:function(a){a=z.prototype.toJSON.call(this,a);a.object.color=this.color.getHex();a.object.intensity=
14198 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&&(a.object.shadow=this.shadow.toJSON());return a}});sd.prototype=Object.assign(Object.create(na.prototype),{constructor:sd,isHemisphereLight:!0,copy:function(a){na.prototype.copy.call(this,
14199 a);this.groundColor.copy(a.groundColor);return this}});Object.assign(tb.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=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;
14200 return a}});td.prototype=Object.assign(Object.create(tb.prototype),{constructor:td,isSpotLightShadow:!0,update:function(a){var b=this.camera,c=2*Y.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()}});ud.prototype=Object.assign(Object.create(na.prototype),{constructor:ud,isSpotLight:!0,copy:function(a){na.prototype.copy.call(this,a);this.distance=a.distance;this.angle=a.angle;this.penumbra=
14201 a.penumbra;this.decay=a.decay;this.target=a.target.clone();this.shadow=a.shadow.clone();return this}});vd.prototype=Object.assign(Object.create(na.prototype),{constructor:vd,isPointLight:!0,copy:function(a){na.prototype.copy.call(this,a);this.distance=a.distance;this.decay=a.decay;this.shadow=a.shadow.clone();return this}});wd.prototype=Object.assign(Object.create(tb.prototype),{constructor:wd});xd.prototype=Object.assign(Object.create(na.prototype),{constructor:xd,isDirectionalLight:!0,copy:function(a){na.prototype.copy.call(this,
14202 a);this.target=a.target.clone();this.shadow=a.shadow.clone();return this}});yd.prototype=Object.assign(Object.create(na.prototype),{constructor:yd,isAmbientLight:!0});zd.prototype=Object.assign(Object.create(na.prototype),{constructor:zd,isRectAreaLight:!0,copy:function(a){na.prototype.copy.call(this,a);this.width=a.width;this.height=a.height;return this},toJSON:function(a){a=na.prototype.toJSON.call(this,a);a.object.width=this.width;a.object.height=this.height;return a}});var ia={arraySlice:function(a,
14203 b,c){return ia.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 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=
14204 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!==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++];
14205 while(void 0!==f)}}}};Object.assign(wa.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;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=
14206 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||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]=
14207 c[a+e];return b},interpolate_:function(a,b,c,d){throw Error("call to abstract method");},intervalChanged_:function(a,b,c){}});Object.assign(wa.prototype,{beforeStart_:wa.prototype.copySampleValue_,afterEnd_:wa.prototype.copySampleValue_});Ad.prototype=Object.assign(Object.create(wa.prototype),{constructor:Ad,DefaultSettings_:{endingStart:2400,endingEnd:2400},intervalChanged_:function(a,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=
14208 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,f=this.sampleValues,g=this.valueSize;a*=g;var h=a-g,k=this._offsetPrev,m=this._offsetNext,l=this._weightPrev,n=this._weightNext,
14209 p=(c-b)/(d-b);c=p*p;d=c*p;b=-l*d+2*l*c-l*p;l=(1+l)*d+(-1.5-2*l)*c+(-.5+l)*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]+l*f[h+c]+p*f[a+c]+n*f[m+c];return e}});Tc.prototype=Object.assign(Object.create(wa.prototype),{constructor:Tc,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-b);c=1-b;for(d=0;d!==g;++d)e[d]=f[h+d]*c+f[a+d]*b;return e}});Bd.prototype=Object.assign(Object.create(wa.prototype),{constructor:Bd,
14210 interpolate_:function(a,b,c,d){return this.copySampleValue_(a-1)}});var Wa;Wa={TimeBufferType:Float32Array,ValueBufferType:Float32Array,DefaultInterpolation:2301,InterpolantFactoryMethodDiscrete:function(a){return new Bd(this.times,this.values,this.getValueSize(),a)},InterpolantFactoryMethodLinear:function(a){return new Tc(this.times,this.values,this.getValueSize(),a)},InterpolantFactoryMethodSmooth:function(a){return new Ad(this.times,this.values,this.getValueSize(),a)},setInterpolation:function(a){var b;
14211 switch(a){case 2300: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:",b)}else this.createInterpolant=b},getInterpolation:function(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return 2300;
14212 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},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,
14213 1),e=f-1),d=this.getValueSize(),this.times=ia.arraySlice(c,e,f),this.values=ia.arraySlice(this.values,e*d,f*d);return this},validate:function(){var a=!0,b=this.getValueSize();0!==b-Math.floor(b)&&(console.error("THREE.KeyframeTrackPrototype: Invalid value size in track.",this),a=!1);var c=this.times,b=this.values,d=c.length;0===d&&(console.error("THREE.KeyframeTrackPrototype: Track is empty.",this),a=!1);for(var e=null,f=0;f!==d;f++){var g=c[f];if("number"===typeof g&&isNaN(g)){console.error("THREE.KeyframeTrackPrototype: Time is not a valid number.",
14214 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&&ia.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=this.times,b=this.values,c=this.getValueSize(),d=2302===this.getInterpolation(),e=1,f=a.length-1,g=1;g<f;++g){var h=!1,k=a[g];if(k!==a[g+1]&&(1!==g||k!==
14215 k[0]))if(d)h=!0;else for(var m=g*c,l=m-c,n=m+c,k=0;k!==c;++k){var p=b[m+k];if(p!==b[l+k]||p!==b[n+k]){h=!0;break}}if(h){if(g!==e)for(a[e]=a[g],h=g*c,m=e*c,k=0;k!==c;++k)b[m+k]=b[h+k];++e}}if(0<f){a[e]=a[f];h=f*c;m=e*c;for(k=0;k!==c;++k)b[m+k]=b[h+k];++e}e!==a.length&&(this.times=ia.arraySlice(a,0,e),this.values=ia.arraySlice(b,0,e*c));return this}};cc.prototype=Object.assign(Object.create(Wa),{constructor:cc,ValueTypeName:"vector"});Cd.prototype=Object.assign(Object.create(wa.prototype),{constructor:Cd,
14216 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)oa.slerpFlat(e,0,f,a-g,f,a,b);return e}});Uc.prototype=Object.assign(Object.create(Wa),{constructor:Uc,ValueTypeName:"quaternion",DefaultInterpolation:2301,InterpolantFactoryMethodLinear:function(a){return new Cd(this.times,this.values,this.getValueSize(),a)},InterpolantFactoryMethodSmooth:void 0});dc.prototype=Object.assign(Object.create(Wa),{constructor:dc,ValueTypeName:"number"});
14217 Dd.prototype=Object.assign(Object.create(Wa),{constructor:Dd,ValueTypeName:"string",ValueBufferType:Array,DefaultInterpolation:2300,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0});Ed.prototype=Object.assign(Object.create(Wa),{constructor:Ed,ValueTypeName:"bool",ValueBufferType:Array,DefaultInterpolation:2300,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0});Fd.prototype=Object.assign(Object.create(Wa),{constructor:Fd,ValueTypeName:"color"});
14218 vb.prototype=Wa;Wa.constructor=vb;Object.assign(vb,{parse:function(a){if(void 0===a.type)throw Error("track type undefined, can not parse");var b=vb._getTrackTypeForValueTypeName(a.type);if(void 0===a.times){var c=[],d=[];ia.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,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:ia.convertArray(a.times,Array),values:ia.convertArray(a.values,
14219 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 dc;case "vector":case "vector2":case "vector3":case "vector4":return cc;case "color":return Fd;case "quaternion":return Uc;case "bool":case "boolean":return Ed;case "string":return Dd}throw Error("Unsupported typeName: "+a);}});Object.assign(Da,{parse:function(a){for(var b=
14220 [],c=a.tracks,d=1/(a.fps||1),e=0,f=c.length;e!==f;++e)b.push(vb.parse(c[e]).scale(d));return new Da(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(vb.toJSON(c[d]));return a},CreateFromMorphTargetSequence:function(a,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 m=ia.getKeyframeOrder(h),h=ia.sortedArray(h,1,m),k=ia.sortedArray(k,1,m);d||0!==h[0]||
14221 (h.push(e),k.push(k[0]));f.push((new dc(".morphTargetInfluences["+b[g].name+"]",h,k)).scale(1/c))}return new Da(a,-1,f)},findByName:function(a,b){var c=a;Array.isArray(a)||(c=a.geometry&&a.geometry.animations||a.animations);for(var d=0;d<c.length;d++)if(c[d].name===b)return c[d];return null},CreateClipsFromMorphTargetSequences:function(a,b,c){for(var d={},e=/^([\w-]*?)([\d]+)$/,f=0,g=a.length;f<g;f++){var h=a[f],k=h.name.match(e);if(k&&1<k.length){var m=k[1];(k=d[m])||(d[m]=k=[]);k.push(h)}}a=[];
14222 for(m in d)a.push(Da.CreateFromMorphTargetSequence(m,d[m],b,c));return a},parseAnimation:function(a,b){if(!a)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;for(var c=function(a,b,c,d,e){if(0!==c.length){var f=[],g=[];ia.flattenJSON(c,f,g,d);0!==f.length&&e.push(new a(b,f,g))}},d=[],e=a.name||"default",f=a.length||-1,g=a.fps||30,h=a.hierarchy||[],k=0;k<h.length;k++){var m=h[k].keys;if(m&&0!==m.length)if(m[0].morphTargets){for(var f={},l=0;l<m.length;l++)if(m[l].morphTargets)for(var n=
14223 0;n<m[l].morphTargets.length;n++)f[m[l].morphTargets[n]]=-1;for(var p in f){for(var r=[],z=[],n=0;n!==m[l].morphTargets.length;++n){var t=m[l];r.push(t.time);z.push(t.morphTarget===p?1:0)}d.push(new dc(".morphTargetInfluence["+p+"]",r,z))}f=f.length*(g||1)}else l=".bones["+b[k].name+"]",c(cc,l+".position",m,"pos",d),c(Uc,l+".quaternion",m,"rot",d),c(cc,l+".scale",m,"scl",d)}return 0===d.length?null:new Da(e,f,d)}});Object.assign(Da.prototype,{resetDuration:function(){for(var a=0,b=0,c=this.tracks.length;b!==
14224 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(Gd.prototype,{load:function(a,b,c,d){var e=this;(new Ka(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===
14225 c[a]&&console.warn("THREE.MaterialLoader: Undefined texture",a);return c[a]}var c=this.textures,d=new mg[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);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=
14226 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!==a.fog&&(d.fog=a.fog);void 0!==a.shading&&(d.shading=a.shading);void 0!==a.blending&&(d.blending=a.blending);void 0!==a.side&&(d.side=a.side);void 0!==a.opacity&&(d.opacity=a.opacity);
14227 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!==a.wireframeLinewidth&&(d.wireframeLinewidth=a.wireframeLinewidth);void 0!==a.wireframeLinecap&&(d.wireframeLinecap=a.wireframeLinecap);void 0!==a.wireframeLinejoin&&(d.wireframeLinejoin=a.wireframeLinejoin);
14228 void 0!==a.skinning&&(d.skinning=a.skinning);void 0!==a.morphTargets&&(d.morphTargets=a.morphTargets);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&&(d.normalMap=b(a.normalMap));if(void 0!==a.normalScale){var e=a.normalScale;!1===Array.isArray(e)&&
14229 (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=b(a.emissiveMap));void 0!==a.emissiveIntensity&&(d.emissiveIntensity=a.emissiveIntensity);
14230 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=b(a.gradientMap));return d}});Object.assign(be.prototype,{load:function(a,b,c,d){var e=
14231 this;(new Ka(e.manager)).load(a,function(a){b(e.parse(JSON.parse(a)))},c,d)},parse:function(a){var b=new E,c=a.data.index;void 0!==c&&(c=new ef[c.type](c.array),b.setIndex(new Z(c,1)));var d=a.data.attributes,e;for(e in d){var f=d[e],c=new ef[f.type](f.array);b.addAttribute(e,new Z(c,f.itemSize,f.normalized))}e=a.data.groups||a.data.drawcalls||a.data.offsets;if(void 0!==e)for(c=0,d=e.length;c!==d;++c)f=e[c],b.addGroup(f.start,f.count,f.materialIndex);a=a.data.boundingSphere;void 0!==a&&(e=new n,void 0!==
14232 a.center&&e.fromArray(a.center),b.boundingSphere=new Ea(e,a.radius));return b}});var ef={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:"undefined"!==typeof Uint8ClampedArray?Uint8ClampedArray:Uint8Array,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};ec.Handlers={handlers:[],add:function(a,b){this.handlers.push(a,b)},get:function(a){for(var b=this.handlers,c=0,d=b.length;c<d;c+=2){var e=
14233 b[c+1];if(b[c].test(a))return e}return null}};Object.assign(ec.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},b=new G,c=new rd,d=new Gd;return function(e,f,g){function h(a,
14234 b,d,e,h){a=f+a;var m=ec.Handlers.get(a);null!==m?a=m.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=Y.generateUUID();k[b]=a;return b}var k={},m={uuid:Y.generateUUID(),type:"MeshLambertMaterial"},l;for(l in e){var n=e[l];
14235 switch(l){case "DbgColor":case "DbgIndex":case "opticalDensity":case "illumination":break;case "DbgName":m.name=n;break;case "blending":m.blending=a[n];break;case "colorAmbient":case "mapAmbient":console.warn("THREE.Loader.createMaterial:",l,"is no longer supported.");break;case "colorDiffuse":m.color=b.fromArray(n).getHex();break;case "colorSpecular":m.specular=b.fromArray(n).getHex();break;case "colorEmissive":m.emissive=b.fromArray(n).getHex();break;case "specularCoef":m.shininess=n;break;case "shading":"basic"===
14236 n.toLowerCase()&&(m.type="MeshBasicMaterial");"phong"===n.toLowerCase()&&(m.type="MeshPhongMaterial");"standard"===n.toLowerCase()&&(m.type="MeshStandardMaterial");break;case "mapDiffuse":m.map=h(n,e.mapDiffuseRepeat,e.mapDiffuseOffset,e.mapDiffuseWrap,e.mapDiffuseAnisotropy);break;case "mapDiffuseRepeat":case "mapDiffuseOffset":case "mapDiffuseWrap":case "mapDiffuseAnisotropy":break;case "mapEmissive":m.emissiveMap=h(n,e.mapEmissiveRepeat,e.mapEmissiveOffset,e.mapEmissiveWrap,e.mapEmissiveAnisotropy);
14237 break;case "mapEmissiveRepeat":case "mapEmissiveOffset":case "mapEmissiveWrap":case "mapEmissiveAnisotropy":break;case "mapLight":m.lightMap=h(n,e.mapLightRepeat,e.mapLightOffset,e.mapLightWrap,e.mapLightAnisotropy);break;case "mapLightRepeat":case "mapLightOffset":case "mapLightWrap":case "mapLightAnisotropy":break;case "mapAO":m.aoMap=h(n,e.mapAORepeat,e.mapAOOffset,e.mapAOWrap,e.mapAOAnisotropy);break;case "mapAORepeat":case "mapAOOffset":case "mapAOWrap":case "mapAOAnisotropy":break;case "mapBump":m.bumpMap=
14238 h(n,e.mapBumpRepeat,e.mapBumpOffset,e.mapBumpWrap,e.mapBumpAnisotropy);break;case "mapBumpScale":m.bumpScale=n;break;case "mapBumpRepeat":case "mapBumpOffset":case "mapBumpWrap":case "mapBumpAnisotropy":break;case "mapNormal":m.normalMap=h(n,e.mapNormalRepeat,e.mapNormalOffset,e.mapNormalWrap,e.mapNormalAnisotropy);break;case "mapNormalFactor":m.normalScale=[n,n];break;case "mapNormalRepeat":case "mapNormalOffset":case "mapNormalWrap":case "mapNormalAnisotropy":break;case "mapSpecular":m.specularMap=
14239 h(n,e.mapSpecularRepeat,e.mapSpecularOffset,e.mapSpecularWrap,e.mapSpecularAnisotropy);break;case "mapSpecularRepeat":case "mapSpecularOffset":case "mapSpecularWrap":case "mapSpecularAnisotropy":break;case "mapMetalness":m.metalnessMap=h(n,e.mapMetalnessRepeat,e.mapMetalnessOffset,e.mapMetalnessWrap,e.mapMetalnessAnisotropy);break;case "mapMetalnessRepeat":case "mapMetalnessOffset":case "mapMetalnessWrap":case "mapMetalnessAnisotropy":break;case "mapRoughness":m.roughnessMap=h(n,e.mapRoughnessRepeat,
14240 e.mapRoughnessOffset,e.mapRoughnessWrap,e.mapRoughnessAnisotropy);break;case "mapRoughnessRepeat":case "mapRoughnessOffset":case "mapRoughnessWrap":case "mapRoughnessAnisotropy":break;case "mapAlpha":m.alphaMap=h(n,e.mapAlphaRepeat,e.mapAlphaOffset,e.mapAlphaWrap,e.mapAlphaAnisotropy);break;case "mapAlphaRepeat":case "mapAlphaOffset":case "mapAlphaWrap":case "mapAlphaAnisotropy":break;case "flipSided":m.side=1;break;case "doubleSided":m.side=2;break;case "transparency":console.warn("THREE.Loader.createMaterial: transparency has been renamed to opacity");
14241 m.opacity=n;break;case "depthTest":case "depthWrite":case "colorWrite":case "opacity":case "reflectivity":case "transparent":case "visible":case "wireframe":m[l]=n;break;case "vertexColors":!0===n&&(m.vertexColors=2);"face"===n&&(m.vertexColors=1);break;default:console.error("THREE.Loader.createMaterial: Unsupported",l,n)}}"MeshBasicMaterial"===m.type&&delete m.emissive;"MeshPhongMaterial"!==m.type&&delete m.specular;1>m.opacity&&(m.transparent=!0);d.setTextures(k);return d.parse(m)}}()});Object.assign(ce.prototype,
14242 {load:function(a,b,c,d){var e=this,f=this.texturePath&&"string"===typeof this.texturePath?this.texturePath:ec.prototype.extractUrlBase(a),g=new Ka(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.");
14243 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 J,d=a,e,f,g,h,k,m,l,v,p,r,z,t,y,x,u=d.faces;p=d.vertices;var B=d.normals,w=d.colors;m=d.scale;var I=0;if(void 0!==d.uvs){for(e=0;e<d.uvs.length;e++)d.uvs[e].length&&I++;for(e=0;e<I;e++)c.faceVertexUvs[e]=[]}h=0;for(k=p.length;h<k;)e=new n,e.x=p[h++]*m,e.y=p[h++]*m,e.z=p[h++]*m,c.vertices.push(e);
14244 h=0;for(k=u.length;h<k;)if(p=u[h++],r=p&1,g=p&2,e=p&8,l=p&16,z=p&32,m=p&64,p&=128,r){r=new Sa;r.a=u[h];r.b=u[h+1];r.c=u[h+3];t=new Sa;t.a=u[h+1];t.b=u[h+2];t.c=u[h+3];h+=4;g&&(g=u[h++],r.materialIndex=g,t.materialIndex=g);g=c.faces.length;if(e)for(e=0;e<I;e++)for(y=d.uvs[e],c.faceVertexUvs[e][g]=[],c.faceVertexUvs[e][g+1]=[],f=0;4>f;f++)v=u[h++],x=y[2*v],v=y[2*v+1],x=new C(x,v),2!==f&&c.faceVertexUvs[e][g].push(x),0!==f&&c.faceVertexUvs[e][g+1].push(x);l&&(l=3*u[h++],r.normal.set(B[l++],B[l++],B[l]),
14245 t.normal.copy(r.normal));if(z)for(e=0;4>e;e++)l=3*u[h++],z=new n(B[l++],B[l++],B[l]),2!==e&&r.vertexNormals.push(z),0!==e&&t.vertexNormals.push(z);m&&(m=u[h++],m=w[m],r.color.setHex(m),t.color.setHex(m));if(p)for(e=0;4>e;e++)m=u[h++],m=w[m],2!==e&&r.vertexColors.push(new G(m)),0!==e&&t.vertexColors.push(new G(m));c.faces.push(r);c.faces.push(t)}else{r=new Sa;r.a=u[h++];r.b=u[h++];r.c=u[h++];g&&(g=u[h++],r.materialIndex=g);g=c.faces.length;if(e)for(e=0;e<I;e++)for(y=d.uvs[e],c.faceVertexUvs[e][g]=
14246 [],f=0;3>f;f++)v=u[h++],x=y[2*v],v=y[2*v+1],x=new C(x,v),c.faceVertexUvs[e][g].push(x);l&&(l=3*u[h++],r.normal.set(B[l++],B[l++],B[l]));if(z)for(e=0;3>e;e++)l=3*u[h++],z=new n(B[l++],B[l++],B[l]),r.vertexNormals.push(z);m&&(m=u[h++],r.color.setHex(w[m]));if(p)for(e=0;3>e;e++)m=u[h++],r.vertexColors.push(new G(w[m]));c.faces.push(r)}d=a;h=void 0!==d.influencesPerVertex?d.influencesPerVertex:2;if(d.skinWeights)for(k=0,u=d.skinWeights.length;k<u;k+=h)c.skinWeights.push(new fa(d.skinWeights[k],1<h?d.skinWeights[k+
14247 1]:0,2<h?d.skinWeights[k+2]:0,3<h?d.skinWeights[k+3]:0));if(d.skinIndices)for(k=0,u=d.skinIndices.length;k<u;k+=h)c.skinIndices.push(new fa(d.skinIndices[k],1<h?d.skinIndices[k+1]:0,2<h?d.skinIndices[k+2]:0,3<h?d.skinIndices[k+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 ("+c.skinWeights.length+
14248 ") should match.");k=a;u=k.scale;if(void 0!==k.morphTargets)for(d=0,h=k.morphTargets.length;d<h;d++)for(c.morphTargets[d]={},c.morphTargets[d].name=k.morphTargets[d].name,c.morphTargets[d].vertices=[],B=c.morphTargets[d].vertices,w=k.morphTargets[d].vertices,I=0,p=w.length;I<p;I+=3)m=new n,m.x=w[I]*u,m.y=w[I+1]*u,m.z=w[I+2]*u,B.push(m);if(void 0!==k.morphColors&&0<k.morphColors.length)for(console.warn('THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.'),u=c.faces,k=k.morphColors[0].colors,
14249 d=0,h=u.length;d<h;d++)u[d].color.fromArray(k,3*d);k=a;d=[];h=[];void 0!==k.animation&&h.push(k.animation);void 0!==k.animations&&(k.animations.length?h=h.concat(k.animations):h.push(k.animations));for(k=0;k<h.length;k++)(u=Da.parseAnimation(h[k],c.bones))&&d.push(u);c.morphTargets&&(h=Da.CreateClipsFromMorphTargetSequences(c.morphTargets,10),d=d.concat(h));0<d.length&&(c.animations=d);c.computeFaceNormals();c.computeBoundingSphere();if(void 0===a.materials||0===a.materials.length)return{geometry:c};
14250 d=ec.prototype.initMaterials(a.materials,b,this.crossOrigin);return{geometry:c,materials:d}}}()});Object.assign(Pe.prototype,{load:function(a,b,c,d){""===this.texturePath&&(this.texturePath=a.substring(0,a.lastIndexOf("/")+1));var e=this;(new Ka(e.manager)).load(a,function(c){var g=null;try{g=JSON.parse(c)}catch(h){void 0!==d&&d(h);console.error("THREE:ObjectLoader: Can't parse "+a+".",h.message);return}c=g.metadata;void 0===c||void 0===c.type||"geometry"===c.type.toLowerCase()?console.error("THREE.ObjectLoader: Can't load "+
14251 a+". Use THREE.JSONLoader instead."):e.parse(g,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&&0!==a.images.length||void 0===b||b(e);return e},
14252 parseGeometries:function(a){var b={};if(void 0!==a)for(var c=new ce,d=new be,e=0,f=a.length;e<f;e++){var g,h=a[e];switch(h.type){case "PlaneGeometry":case "PlaneBufferGeometry":g=new Ma[h.type](h.width,h.height,h.widthSegments,h.heightSegments);break;case "BoxGeometry":case "BoxBufferGeometry":case "CubeGeometry":g=new Ma[h.type](h.width,h.height,h.depth,h.widthSegments,h.heightSegments,h.depthSegments);break;case "CircleGeometry":case "CircleBufferGeometry":g=new Ma[h.type](h.radius,h.segments,h.thetaStart,
14253 h.thetaLength);break;case "CylinderGeometry":case "CylinderBufferGeometry":g=new Ma[h.type](h.radiusTop,h.radiusBottom,h.height,h.radialSegments,h.heightSegments,h.openEnded,h.thetaStart,h.thetaLength);break;case "ConeGeometry":case "ConeBufferGeometry":g=new Ma[h.type](h.radius,h.height,h.radialSegments,h.heightSegments,h.openEnded,h.thetaStart,h.thetaLength);break;case "SphereGeometry":case "SphereBufferGeometry":g=new Ma[h.type](h.radius,h.widthSegments,h.heightSegments,h.phiStart,h.phiLength,
14254 h.thetaStart,h.thetaLength);break;case "DodecahedronGeometry":case "IcosahedronGeometry":case "OctahedronGeometry":case "TetrahedronGeometry":g=new Ma[h.type](h.radius,h.detail);break;case "RingGeometry":case "RingBufferGeometry":g=new Ma[h.type](h.innerRadius,h.outerRadius,h.thetaSegments,h.phiSegments,h.thetaStart,h.thetaLength);break;case "TorusGeometry":case "TorusBufferGeometry":g=new Ma[h.type](h.radius,h.tube,h.radialSegments,h.tubularSegments,h.arc);break;case "TorusKnotGeometry":case "TorusKnotBufferGeometry":g=
14255 new Ma[h.type](h.radius,h.tube,h.tubularSegments,h.radialSegments,h.p,h.q);break;case "LatheGeometry":case "LatheBufferGeometry":g=new Ma[h.type](h.points,h.segments,h.phiStart,h.phiLength);break;case "BufferGeometry":g=d.parse(h);break;case "Geometry":g=c.parse(h,this.texturePath).geometry;break;default:console.warn('THREE.ObjectLoader: Unsupported geometry type "'+h.type+'"');continue}g.uuid=h.uuid;void 0!==h.name&&(g.name=h.name);b[h.uuid]=g}return b},parseMaterials:function(a,b){var c={};if(void 0!==
14256 a){var d=new Gd;d.setTextures(b);for(var e=0,f=a.length;e<f;e++){var g=a[e];if("MultiMaterial"===g.type){for(var h=[],k=0;k<g.materials.length;k++)h.push(d.parse(g.materials[k]));c[g.uuid]=h}else c[g.uuid]=d.parse(g)}}return c},parseAnimations:function(a){for(var b=[],c=0;c<a.length;c++){var d=Da.parse(a[c]);b.push(d)}return b},parseImages:function(a,b){function c(a){d.manager.itemStart(a);return g.load(a,function(){d.manager.itemEnd(a)},void 0,function(){d.manager.itemEnd(a);d.manager.itemError(a)})}
14257 var d=this,e={};if(void 0!==a&&0<a.length){var f=new Zd(b),g=new Sc(f);g.setCrossOrigin(this.crossOrigin);for(var f=0,h=a.length;f<h;f++){var k=a[f],m=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(k.url)?k.url:d.texturePath+k.url;e[k.uuid]=c(m)}}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&&
14258 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 ba(b[g.image]);h.needsUpdate=!0;h.uuid=g.uuid;void 0!==g.name&&(h.name=g.name);void 0!==g.mapping&&(h.mapping=c(g.mapping,ng));void 0!==g.offset&&h.offset.fromArray(g.offset);void 0!==g.repeat&&h.repeat.fromArray(g.repeat);void 0!==g.wrap&&(h.wrapS=c(g.wrap[0],ff),h.wrapT=c(g.wrap[1],ff));void 0!==g.minFilter&&(h.minFilter=c(g.minFilter,gf));
14259 void 0!==g.magFilter&&(h.magFilter=c(g.magFilter,gf));void 0!==g.anisotropy&&(h.anisotropy=g.anisotropy);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===
14260 d[a]&&console.warn("THREE.ObjectLoader: Undefined material",a);return d[a]}}var g;switch(b.type){case "Scene":g=new ld;void 0!==b.background&&Number.isInteger(b.background)&&(g.background=new G(b.background));void 0!==b.fog&&("Fog"===b.fog.type?g.fog=new Jb(b.fog.color,b.fog.near,b.fog.far):"FogExp2"===b.fog.type&&(g.fog=new Ib(b.fog.color,b.fog.density)));break;case "PerspectiveCamera":g=new qa(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!==
14261 b.filmGauge&&(g.filmGauge=b.filmGauge);void 0!==b.filmOffset&&(g.filmOffset=b.filmOffset);void 0!==b.view&&(g.view=Object.assign({},b.view));break;case "OrthographicCamera":g=new Fb(b.left,b.right,b.top,b.bottom,b.near,b.far);break;case "AmbientLight":g=new yd(b.color,b.intensity);break;case "DirectionalLight":g=new xd(b.color,b.intensity);break;case "PointLight":g=new vd(b.color,b.intensity,b.distance,b.decay);break;case "RectAreaLight":g=new zd(b.color,b.intensity,b.width,b.height);break;case "SpotLight":g=
14262 new ud(b.color,b.intensity,b.distance,b.angle,b.penumbra,b.decay);break;case "HemisphereLight":g=new sd(b.color,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 nd(g,h):new la(g,h);break;case "LOD":g=new yc;break;case "Line":g=new sa(e(b.geometry),f(b.material),b.mode);break;case "LineLoop":g=new od(e(b.geometry),f(b.material));break;
14263 case "LineSegments":g=new Q(e(b.geometry),f(b.material));break;case "PointCloud":case "Points":g=new Kb(e(b.geometry),f(b.material));break;case "Sprite":g=new xc(f(b.material));break;case "Group":g=new Ac;break;default:g=new z}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),
14264 void 0!==b.scale&&g.scale.fromArray(b.scale));void 0!==b.castShadow&&(g.castShadow=b.castShadow);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=
14265 b.userData);if(void 0!==b.children)for(var k in b.children)g.add(this.parseObject(b.children[k],c,d));if("LOD"===b.type)for(b=b.levels,h=0;h<b.length;h++){var m=b[h];k=g.getObjectByProperty("uuid",m.object);void 0!==k&&g.addLevel(k,m.distance)}return g}}()});var ng={UVMapping:300,CubeReflectionMapping:301,CubeRefractionMapping:302,EquirectangularReflectionMapping:303,EquirectangularRefractionMapping:304,SphericalReflectionMapping:305,CubeUVReflectionMapping:306,CubeUVRefractionMapping:307},ff={RepeatWrapping:1E3,
14266 ClampToEdgeWrapping:1001,MirroredRepeatWrapping:1002},gf={NearestFilter:1003,NearestMipMapNearestFilter:1004,NearestMipMapLinearFilter:1005,LinearFilter:1006,LinearMipMapNearestFilter:1007,LinearMipMapLinearFilter:1008};Object.assign(ua.prototype,{getPoint:function(){console.warn("THREE.Curve: .getPoint() not implemented.");return null},getPointAt:function(a){a=this.getUtoTmapping(a);return this.getPoint(a)},getPoints:function(a){void 0===a&&(a=5);for(var b=[],c=0;c<=a;c++)b.push(this.getPoint(c/
14267 a));return b},getSpacedPoints:function(a){void 0===a&&(a=5);for(var b=[],c=0;c<=a;c++)b.push(this.getPointAt(c/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,d=this.getPoint(0),e,f=0;b.push(0);for(e=1;e<=a;e++)c=this.getPoint(e/a),f+=c.distanceTo(d),b.push(f),d=c;return this.cacheArcLengths=
14268 b},updateArcLengths:function(){this.needsUpdate=!0;this.getLengths()},getUtoTmapping:function(a,b){var c=this.getLengths(),d,e=c.length,f;f=b?b:a*c[e-1];for(var g=0,h=e-1,k;g<=h;)if(d=Math.floor(g+(h-g)/2),k=c[d]-f,0>k)g=d+1;else if(0<k)h=d-1;else{h=d;break}d=h;if(c[d]===f)return d/(e-1);g=c[d];return(d+(f-g)/(c[d+1]-g))/(e-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);
14269 return this.getTangent(a)},computeFrenetFrames:function(a,b){var c=new n,d=[],e=[],f=[],g=new n,h=new K,k,m;for(k=0;k<=a;k++)m=k/a,d[k]=this.getTangentAt(m),d[k].normalize();e[0]=new n;f[0]=new n;k=Number.MAX_VALUE;m=Math.abs(d[0].x);var l=Math.abs(d[0].y),v=Math.abs(d[0].z);m<=k&&(k=m,c.set(1,0,0));l<=k&&(k=l,c.set(0,1,0));v<=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-
14270 1],d[k]),g.length()>Number.EPSILON&&(g.normalize(),c=Math.acos(Y.clamp(d[k-1].dot(d[k]),-1,1)),e[k].applyMatrix4(h.makeRotationAxis(g,c))),f[k].crossVectors(d[k],e[k]);if(!0===b)for(c=Math.acos(Y.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}}});Qa.prototype=Object.create(ua.prototype);Qa.prototype.constructor=Qa;Qa.prototype.isLineCurve=
14271 !0;Qa.prototype.getPoint=function(a){if(1===a)return this.v2.clone();var b=this.v2.clone().sub(this.v1);b.multiplyScalar(a).add(this.v1);return b};Qa.prototype.getPointAt=function(a){return this.getPoint(a)};Qa.prototype.getTangent=function(a){return this.v2.clone().sub(this.v1).normalize()};Vc.prototype=Object.assign(Object.create(ua.prototype),{constructor:Vc,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);
14272 a.equals(b)||this.curves.push(new Qa(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=!0;this.cacheLengths=null;this.getCurveLengths()},getCurveLengths:function(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;
14273 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=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),
14274 c=h)}this.autoClose&&1<b.length&&!b[b.length-1].equals(b[0])&&b.push(b[0]);return b},createPointsGeometry:function(a){a=this.getPoints(a);return this.createGeometry(a)},createSpacedPointsGeometry:function(a){a=this.getSpacedPoints(a);return this.createGeometry(a)},createGeometry:function(a){for(var b=new J,c=0,d=a.length;c<d;c++){var e=a[c];b.vertices.push(new n(e.x,e.y,e.z||0))}return b}});Va.prototype=Object.create(ua.prototype);Va.prototype.constructor=Va;Va.prototype.isEllipseCurve=!0;Va.prototype.getPoint=
14275 function(a){for(var b=2*Math.PI,c=this.aEndAngle-this.aStartAngle,d=Math.abs(c)<Number.EPSILON;0>c;)c+=b;for(;c>b;)c-=b;c<Number.EPSILON&&(c=d?0:b);!0!==this.aClockwise||d||(c=c===b?-b:c-b);b=this.aStartAngle+a*c;a=this.aX+this.xRadius*Math.cos(b);var e=this.aY+this.yRadius*Math.sin(b);0!==this.aRotation&&(b=Math.cos(this.aRotation),c=Math.sin(this.aRotation),d=a-this.aX,e-=this.aY,a=d*b-e*c+this.aX,e=d*c+e*b+this.aY);return new C(a,e)};yb.prototype=Object.create(ua.prototype);yb.prototype.constructor=
14276 yb;yb.prototype.isSplineCurve=!0;yb.prototype.getPoint=function(a){var b=this.points,c=(b.length-1)*a;a=Math.floor(c);var c=c-a,d=b[0===a?a:a-1],e=b[a],f=b[a>b.length-2?b.length-1:a+1],b=b[a>b.length-3?b.length-1:a+2];return new C(Qe(c,d.x,e.x,f.x,b.x),Qe(c,d.y,e.y,f.y,b.y))};fc.prototype=Object.create(ua.prototype);fc.prototype.constructor=fc;fc.prototype.getPoint=function(a){var b=this.v0,c=this.v1,d=this.v2,e=this.v3;return new C(xb(a,b.x,c.x,d.x,e.x),xb(a,b.y,c.y,d.y,e.y))};gc.prototype=Object.create(ua.prototype);
14277 gc.prototype.constructor=gc;gc.prototype.getPoint=function(a){var b=this.v0,c=this.v1,d=this.v2;return new C(wb(a,b.x,c.x,d.x),wb(a,b.y,c.y,d.y))};var te=Object.assign(Object.create(Vc.prototype),{fromPoints: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 Qa(this.currentPoint.clone(),new C(a,b));this.curves.push(c);this.currentPoint.set(a,b)},quadraticCurveTo:function(a,
14278 b,c,d){a=new gc(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 fc(this.currentPoint.clone(),new C(a,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 yb(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,
14279 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,e,f,g,h){a=new Va(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)}});Wc.prototype=te;te.constructor=Wc;zb.prototype=Object.assign(Object.create(te),{constructor:zb,getPointsHoles:function(a){for(var b=
14280 [],c=0,d=this.holes.length;c<d;c++)b[c]=this.holes[c].getPoints(a);return b},extractAllPoints:function(a){return{shape:this.getPoints(a),holes:this.getPointsHoles(a)}},extractPoints:function(a){return this.extractAllPoints(a)}});Object.assign(de.prototype,{moveTo:function(a,b){this.currentPath=new Wc;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,
14281 b,c,d,e,f){this.currentPath.bezierCurveTo(a,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 zb;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,m=h.y-g.y;if(Math.abs(m)>Number.EPSILON){if(0>m&&(g=b[f],k=-k,h=b[e],m=-m),!(a.y<g.y||a.y>h.y))if(a.y===g.y){if(a.x===g.x)return!0}else{e=m*(a.x-g.x)-k*(a.y-g.y);if(0===e)return!0;
14282 0>e||(d=!d)}}else if(a.y===g.y&&(h.x<=a.x&&a.x<=g.x||g.x<=a.x&&a.x<=h.x))return!0}return d}var e=Ia.isClockWise,f=this.subPaths;if(0===f.length)return[];if(!0===b)return c(f);var g,h,k,m=[];if(1===f.length)return h=f[0],k=new zb,k.curves=h.curves,m.push(k),m;var l=!e(f[0].getPoints()),l=a?!l:l;k=[];var n=[],p=[],r=0,z;n[r]=void 0;p[r]=[];for(var t=0,y=f.length;t<y;t++)h=f[t],z=h.getPoints(),g=e(z),(g=a?!g:g)?(!l&&n[r]&&r++,n[r]={s:new zb,p:z},n[r].s.curves=h.curves,l&&r++,p[r]=[]):p[r].push({h:h,
14283 p:z[0]});if(!n[0])return c(f);if(1<n.length){t=!1;h=[];e=0;for(f=n.length;e<f;e++)k[e]=[];e=0;for(f=n.length;e<f;e++)for(g=p[e],l=0;l<g.length;l++){r=g[l];z=!0;for(y=0;y<n.length;y++)d(r.p,n[y].p)&&(e!==y&&h.push({froms:e,tos:y,hole:l}),z?(z=!1,k[y].push(r)):t=!0);z&&k[e].push(r)}0<h.length&&(t||(p=k))}t=0;for(e=n.length;t<e;t++)for(k=n[t].s,m.push(k),h=p[t],f=0,g=h.length;f<g;f++)k.holes.push(h[f].h);return m}});Object.assign(ee.prototype,{isFont:!0,generateShapes:function(a,b,c){void 0===b&&(b=
14284 100);void 0===c&&(c=4);var d=this.data;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 m=a[k];if("\n"===m)g=0,h-=f;else{var l;l=e;var n=g,p=h;if(m=d.glyphs[m]||d.glyphs["?"]){var r=new de,z=[],t,y,x,u,B,w,C,G;if(m.o)for(var D=m._cachedOutline||(m._cachedOutline=m.o.split(" ")),E=0,J=D.length;E<J;)switch(D[E++]){case "m":t=D[E++]*l+n;y=D[E++]*l+p;r.moveTo(t,y);break;case "l":t=D[E++]*l+n;y=D[E++]*
14285 l+p;r.lineTo(t,y);break;case "q":t=D[E++]*l+n;y=D[E++]*l+p;B=D[E++]*l+n;w=D[E++]*l+p;r.quadraticCurveTo(B,w,t,y);if(u=z[z.length-1]){x=u.x;u=u.y;for(var F=1;F<=c;F++){var K=F/c;wb(K,x,B,t);wb(K,u,w,y)}}break;case "b":if(t=D[E++]*l+n,y=D[E++]*l+p,B=D[E++]*l+n,w=D[E++]*l+p,C=D[E++]*l+n,G=D[E++]*l+p,r.bezierCurveTo(B,w,C,G,t,y),u=z[z.length-1])for(x=u.x,u=u.y,F=1;F<=c;F++)K=F/c,xb(K,x,B,C,t),xb(K,u,w,G,y)}l={offsetX:m.ha*l,path:r}}else l=void 0;g+=l.offsetX;b.push(l.path)}}c=[];d=0;for(a=b.length;d<
14286 a;d++)Array.prototype.push.apply(c,b[d].toShapes());return c}});Object.assign(Re.prototype,{load:function(a,b,c,d){var e=this;(new Ka(this.manager)).load(a,function(a){var c;try{c=JSON.parse(a)}catch(d){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 ee(a)}});var Nd,he={getContext:function(){void 0===Nd&&(Nd=new (window.AudioContext||window.webkitAudioContext));
14287 return Nd},setContext:function(a){Nd=a}};Object.assign(fe.prototype,{load:function(a,b,c,d){var e=new Ka(this.manager);e.setResponseType("arraybuffer");e.load(a,function(a){he.getContext().decodeAudioData(a,function(a){b(a)})},c,d)}});Object.assign(Se.prototype,{update:function(){var a,b,c,d,e,f,g,h,k=new K,m=new K;return function(l){if(a!==this||b!==l.focus||c!==l.fov||d!==l.aspect*this.aspect||e!==l.near||f!==l.far||g!==l.zoom||h!==this.eyeSep){a=this;b=l.focus;c=l.fov;d=l.aspect*this.aspect;e=
14288 l.near;f=l.far;g=l.zoom;var n=l.projectionMatrix.clone();h=this.eyeSep/2;var p=h*e/b,r=e*Math.tan(Y.DEG2RAD*c*.5)/g,z,t;m.elements[12]=-h;k.elements[12]=h;z=-r*d+p;t=r*d+p;n.elements[0]=2*e/(t-z);n.elements[8]=(t+z)/(t-z);this.cameraL.projectionMatrix.copy(n);z=-r*d-p;t=r*d-p;n.elements[0]=2*e/(t-z);n.elements[8]=(t+z)/(t-z);this.cameraR.projectionMatrix.copy(n)}this.cameraL.matrixWorld.copy(l.matrixWorld).multiply(m);this.cameraR.matrixWorld.copy(l.matrixWorld).multiply(k)}}()});Hd.prototype=Object.create(z.prototype);
14289 Hd.prototype.constructor=Hd;ge.prototype=Object.assign(Object.create(z.prototype),{constructor:ge,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)):this.gain.disconnect(this.context.destination);
14290 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 n,b=new oa,c=new n,d=new n;return function(e){z.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,this.context.currentTime),
14291 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,d.y,d.z,f.x,f.y,
14292 f.z))}}()});hc.prototype=Object.assign(Object.create(z.prototype),{constructor:hc,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.");
14293 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);a.start(0,this.startTime);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 this.source.stop(),this.startTime=this.context.currentTime,this.isPlaying=!1,this},stop:function(){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");
14294 else return this.source.stop(),this.startTime=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());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-
14295 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]},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.");
14296 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."),!1):this.loop},setLoop:function(a){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");else return this.loop=
14297 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}});ie.prototype=Object.assign(Object.create(hc.prototype),{constructor:ie,getOutput:function(){return this.panner},getRefDistance:function(){return this.panner.refDistance},setRefDistance:function(a){this.panner.refDistance=a},getRolloffFactor:function(){return this.panner.rolloffFactor},setRolloffFactor:function(a){this.panner.rolloffFactor=
14298 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 n;return function(b){z.prototype.updateMatrixWorld.call(this,b);a.setFromMatrixPosition(this.matrixWorld);this.panner.setPosition(a.x,a.y,a.z)}}()});Object.assign(je.prototype,{getFrequencyData:function(){this.analyser.getByteFrequencyData(this.data);
14299 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(ke.prototype,{accumulate:function(a,b){var c=this.buffer,d=this.valueSize,e=a*d+d,f=this.cumulativeWeight;if(0===f){for(f=0;f!==d;++f)c[e+f]=c[f];f=b}else f+=b,this._mixBufferRegion(c,e,0,b/f,d);this.cumulativeWeight=f},apply:function(a){var b=this.valueSize,c=this.buffer;a=a*b+b;var d=this.cumulativeWeight,e=this.binding;this.cumulativeWeight=0;1>d&&
14300 this._mixBufferRegion(c,a,3*b,1-d,b);for(var d=b,f=b+b;d!==f;++d)if(c[d]!==c[d+b]){e.setValue(c,a);break}},saveOriginalState:function(){var a=this.buffer,b=this.valueSize,c=3*b;this.binding.getValue(a,c);for(var d=b;d!==c;++d)a[d]=a[c+d%b];this.cumulativeWeight=0},restoreOriginalState:function(){this.binding.setValue(this.buffer,3*this.valueSize)},_select:function(a,b,c,d,e){if(.5<=d)for(d=0;d!==e;++d)a[b+d]=a[c+d]},_slerp:function(a,b,c,d){oa.slerpFlat(a,b,a,b,a,c,d)},_lerp:function(a,b,c,d,e){for(var f=
14301 1-d,g=0;g!==e;++g){var h=b+g;a[h]=a[h]*f+a[c+g]*d}}});Object.assign(Te.prototype,{getValue:function(a,b){this.bind();var c=this._bindings[this._targetGroup.nCachedObjects_];void 0!==c&&c.getValue(a,b)},setValue:function(a,b){for(var c=this._bindings,d=this._targetGroup.nCachedObjects_,e=c.length;d!==e;++d)c[d].setValue(a,b)},bind:function(){for(var a=this._bindings,b=this._targetGroup.nCachedObjects_,c=a.length;b!==c;++b)a[b].bind()},unbind:function(){for(var a=this._bindings,b=this._targetGroup.nCachedObjects_,
14302 c=a.length;b!==c;++b)a[b].unbind()}});Object.assign(ha,{Composite:Te,create:function(a,b,c){return a&&a.isAnimationObjectGroup?new ha.Composite(a,b,c):new ha(a,b,c)},sanitizeNodeName:function(a){return a.replace(/\s/g,"_").replace(/[^\w-]/g,"")},parseTrackName:function(){var a=new RegExp("^"+/((?:[\w-]+[\/:])*)/.source+/([\w-\.]+)?/.source+/(?:\.([\w-]+)(?:\[(.+)\])?)?/.source+/\.([\w-]+)(?:\[(.+)\])?/.source+"$"),b=["material","materials","bones"];return function(c){var d=a.exec(c);if(!d)throw Error("PropertyBinding: Cannot parse trackName: "+
14303 c);var d={nodeName:d[2],objectName:d[3],objectIndex:d[4],propertyName:d[5],propertyIndex:d[6]},e=d.nodeName&&d.nodeName.lastIndexOf(".");if(void 0!==e&&-1!==e){var f=d.nodeName.substring(e+1);-1!==b.indexOf(f)&&(d.nodeName=d.nodeName.substring(0,e),d.objectName=f)}if(null===d.propertyName||0===d.propertyName.length)throw Error("PropertyBinding: can not parse propertyName from trackName: "+c);return d}}(),findNode:function(a,b){if(!b||""===b||"root"===b||"."===b||-1===b||b===a.name||b===a.uuid)return a;
14304 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 g=a[c];if(g.name===b||g.uuid===b||(g=d(g.children)))return g}return null};if(c=d(a.children))return c}return null}});Object.assign(ha.prototype,{_getValue_unavailable:function(){},_setValue_unavailable:function(){},BindingType:{Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},Versioning:{None:0,
14305 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.node[this.propertyName]=a[b]},function(a,b){this.node[this.propertyName]=a[b];this.targetObject.needsUpdate=!0},function(a,b){this.node[this.propertyName]=
14306 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=!0}],[function(a,b){this.resolvedProperty[this.propertyIndex]=a[b]},function(a,b){this.resolvedProperty[this.propertyIndex]=
14307 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}]],getValue:function(a,b){this.bind();this.getValue(a,b)},setValue:function(a,b){this.bind();this.setValue(a,b)},bind:function(){var a=
14308 this.node,b=this.parsedPath,c=b.objectName,d=b.propertyName,e=b.propertyIndex;a||(this.node=a=ha.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.",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.",
14309 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.",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.",
14310 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=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.",
14311 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===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.",
14312 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,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: "+
14313 this.path+" but it wasn't found.")},unbind:function(){this.node=null;this.getValue=this._getValue_unbound;this.setValue=this._setValue_unbound}});Object.assign(ha.prototype,{_getValue_unbound:ha.prototype.getValue,_setValue_unbound:ha.prototype.setValue});Object.assign(Ue.prototype,{isAnimationObjectGroup:!0,add:function(a){for(var b=this._objects,c=b.length,d=this.nCachedObjects_,e=this._indicesByUUID,f=this._paths,g=this._parsedPaths,h=this._bindings,k=h.length,m=0,l=arguments.length;m!==l;++m){var n=
14314 arguments[m],p=n.uuid,r=e[p];if(void 0===r){r=c++;e[p]=r;b.push(n);for(var p=0,z=k;p!==z;++p)h[p].push(new ha(n,f[p],g[p]))}else if(r<d){var t=--d,z=b[t];e[z.uuid]=r;b[r]=z;e[p]=t;b[t]=n;p=0;for(z=k;p!==z;++p){var y=h[p],x=y[r];y[r]=y[t];void 0===x&&(x=new ha(n,f[p],g[p]));y[t]=x}}else void 0!==b[r]&&console.error("THREE.AnimationObjectGroup: Different objects with the same UUID detected. Clean the caches or recreate your infrastructure when reloading scenes.")}this.nCachedObjects_=d},remove:function(a){for(var b=
14315 this._objects,c=this.nCachedObjects_,d=this._indicesByUUID,e=this._bindings,f=e.length,g=0,h=arguments.length;g!==h;++g){var k=arguments[g],m=k.uuid,l=d[m];if(void 0!==l&&l>=c){var n=c++,p=b[n];d[p.uuid]=l;b[l]=p;d[m]=n;b[n]=k;k=0;for(m=f;k!==m;++k){var p=e[k],r=p[l];p[l]=p[n];p[n]=r}}}this.nCachedObjects_=c},uncache:function(a){for(var b=this._objects,c=b.length,d=this.nCachedObjects_,e=this._indicesByUUID,f=this._bindings,g=f.length,h=0,k=arguments.length;h!==k;++h){var l=arguments[h].uuid,n=e[l];
14316 if(void 0!==n)if(delete e[l],n<d){var l=--d,v=b[l],p=--c,r=b[p];e[v.uuid]=n;b[n]=v;e[r.uuid]=l;b[l]=r;b.pop();v=0;for(r=g;v!==r;++v){var z=f[v],t=z[p];z[n]=z[l];z[l]=t;z.pop()}}else for(p=--c,r=b[p],e[r.uuid]=n,b[n]=r,b.pop(),v=0,r=g;v!==r;++v)z=f[v],z[n]=z[p],z.pop()}this.nCachedObjects_=d},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;
14317 c[a]=d;f.push(a);g.push(b);e.push(l);c=k;for(d=h.length;c!==d;++c)l[c]=new ha(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=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(Ve.prototype,{play:function(){this._mixer._activateAction(this);return this},stop:function(){this._mixer._deactivateAction(this);return this.reset()},reset:function(){this.paused=
14318 !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)},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?
14319 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);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=
14320 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},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,
14321 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=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||
14322 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;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],
14323 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],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===
14324 d)a:{if(-1===e&&(this._loopCount=0,this._setEndings(!0,!0,!1)),b>=c)b=c;else if(0>b)b=0;else break a;this.clampWhenFinished?this.paused=!0:this.enabled=!1;this._mixer.dispatchEvent({type:"finished",action:this,direction:0>a?-1:1})}else{d=2202===d;-1===e&&(0<=a?(e=0,this._setEndings(!0,0===this.repetitions,d)):this._setEndings(0===this.repetitions,!0,d));if(b>=c||0>b){var f=Math.floor(b/c),b=b-c*f,e=e+Math.abs(f),g=this.repetitions-e;0>g?(this.clampWhenFinished?this.paused=!0:this.enabled=!1,b=0<a?
14325 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=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,
14326 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(We.prototype,xa.prototype,{_bindAction:function(a,b){var c=a._localRoot||this._root,d=a._clip.tracks,e=d.length,f=a._propertyBindings,g=a._interpolants,h=c.uuid,k=this._bindingsByRootAndName,l=k[h];void 0===l&&(l={},k[h]=l);for(k=0;k!==e;++k){var n=d[k],v=n.name,p=l[v];if(void 0===
14327 p){p=f[k];if(void 0!==p){null===p._cacheIndex&&(++p.referenceCount,this._addInactiveBinding(p,h,v));continue}p=new ke(ha.create(c,v,b&&b._propertyBindings[k].binding.parsedPath),n.ValueTypeName,n.getValueSize());++p.referenceCount;this._addInactiveBinding(p,h,v)}f[k]=p;g[k].resultBuffer=p.buffer}},_activateAction:function(a){if(!this._isActiveAction(a)){if(null===a._cacheIndex){var b=(a._localRoot||this._root).uuid,c=a._clip.uuid,d=this._actionsByClip[c];this._bindAction(a,d&&d.knownActions[0]);this._addInactiveAction(a,
14328 c,b)}b=a._propertyBindings;c=0;for(d=b.length;c!==d;++c){var e=b[c];0===e.useCount++&&(this._lendBinding(e),e.saveOriginalState())}this._lendAction(a)}},_deactivateAction:function(a){if(this._isActiveAction(a)){for(var b=a._propertyBindings,c=0,d=b.length;c!==d;++c){var e=b[c];0===--e.useCount&&(e.restoreOriginalState(),this._takeBackBinding(e))}this._takeBackAction(a)}},_initMemoryManager:function(){this._actions=[];this._nActiveActions=0;this._actionsByClip={};this._bindings=[];this._nActiveBindings=
14329 0;this._bindingsByRootAndName={};this._controlInterpolants=[];this._nActiveControlInterpolants=0;var a=this;this.stats={actions:{get total(){return a._actions.length},get inUse(){return a._nActiveActions}},bindings:{get total(){return a._bindings.length},get inUse(){return a._nActiveBindings}},controlInterpolants:{get total(){return a._controlInterpolants.length},get inUse(){return a._nActiveControlInterpolants}}}},_isActiveAction:function(a){a=a._cacheIndex;return null!==a&&a<this._nActiveActions},
14330 _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);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;
14331 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;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=
14332 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]=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;
14333 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=--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 Tc(new Float32Array(2),new Float32Array(2),1,this._controlInterpolantsResultBuffer),
14334 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;b[c]=e},_controlInterpolantsResultBuffer:new Float32Array(1),clipAction:function(a,b){var c=b||this._root,d=c.uuid,e="string"===typeof a?Da.findByName(c,a):a,c=null!==e?e.uuid:a,f=this._actionsByClip[c],g=null;if(void 0!==f){g=f.actionByRoot[d];if(void 0!==g)return g;g=f.knownActions[0];null===
14335 e&&(e=g._clip)}if(null===e)return null;e=new Ve(this,e,b);this._bindAction(e,g);this._addInactiveAction(e,c,d);return e},existingAction:function(a,b){var c=b||this._root,d=c.uuid,c="string"===typeof a?Da.findByName(c,a):a,c=this._actionsByClip[c?c.uuid:a];return void 0!==c?c.actionByRoot[d]||null:null},stopAllAction:function(){for(var a=this._actions,b=this._nActiveActions,c=this._bindings,d=this._nActiveBindings,e=this._nActiveBindings=this._nActiveActions=0;e!==b;++e)a[e].reset();for(e=0;e!==d;++e)c[e].useCount=
14336 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;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=
14337 g._cacheIndex,k=b[b.length-1];g._cacheIndex=null;g._byClipCacheIndex=null;k._cacheIndex=h;b[h]=k;b.pop();this._removeInactiveBindingsForAction(g)}delete c[a]}},uncacheRoot:function(a){a=a.uuid;var b=this._actionsByClip,c;for(c in b){var d=b[c].actionByRoot[a];void 0!==d&&(this._deactivateAction(d),this._removeInactiveAction(d))}c=this._bindingsByRootAndName[a];if(void 0!==c)for(var e in c)a=c[e],a.restoreOriginalState(),this._removeInactiveBinding(a)},uncacheAction:function(a,b){var c=this.existingAction(a,
14338 b);null!==c&&(this._deactivateAction(c),this._removeInactiveAction(c))}});Id.prototype.clone=function(){return new Id(void 0===this.value.clone?this.value:this.value.clone())};le.prototype=Object.assign(Object.create(E.prototype),{constructor:le,isInstancedBufferGeometry:!0,addGroup:function(a,b,c){this.groups.push({start:a,count:b,materialIndex:c})},copy:function(a){var b=a.index;null!==b&&this.setIndex(b.clone());var b=a.attributes,c;for(c in b)this.addAttribute(c,b[c].clone());a=a.groups;c=0;for(b=
14339 a.length;c<b;c++){var d=a[c];this.addGroup(d.start,d.count,d.materialIndex)}return this}});Object.defineProperties(me.prototype,{count:{get:function(){return this.data.count}},array:{get:function(){return this.data.array}}});Object.assign(me.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*this.data.stride+this.offset+1]=b;return this},setZ:function(a,b){this.data.array[a*this.data.stride+
14340 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+3]},setXY:function(a,b,c){a=a*this.data.stride+this.offset;this.data.array[a+0]=b;this.data.array[a+
14341 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(ic.prototype,"needsUpdate",{set:function(a){!0===a&&this.version++}});Object.assign(ic.prototype,{isInterleavedBuffer:!0,setArray:function(a){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");
14342 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+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=
14343 a;return this}});ne.prototype=Object.assign(Object.create(ic.prototype),{constructor:ne,isInstancedInterleavedBuffer:!0,copy:function(a){ic.prototype.copy.call(this,a);this.meshPerAttribute=a.meshPerAttribute;return this}});oe.prototype=Object.assign(Object.create(Z.prototype),{constructor:oe,isInstancedBufferAttribute:!0,copy:function(a){Z.prototype.copy.call(this,a);this.meshPerAttribute=a.meshPerAttribute;return this}});Object.assign(Xe.prototype,{linePrecision:1,set:function(a,b){this.ray.set(a,
14344 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)):console.error("THREE.Raycaster: Unsupported camera type.")},intersectObject:function(a,b){var c=[];pe(a,this,c,b);c.sort(Ye);return c},intersectObjects:function(a,
14345 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++)pe(a[d],this,c,b);c.sort(Ye);return c}});Object.assign(Ze.prototype,{start:function(){this.oldTime=this.startTime=("undefined"===typeof performance?Date:performance).now();this.elapsedTime=0;this.running=!0},stop:function(){this.getElapsedTime();this.autoStart=this.running=!1},getElapsedTime:function(){this.getDelta();return this.elapsedTime},getDelta:function(){var a=
14346 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($e.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)},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-
14347 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(Y.clamp(a.y/this.radius,-1,1)));return this}});Object.assign(af.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)},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*
14348 a.x+a.z*a.z);this.theta=Math.atan2(a.x,a.z);this.y=a.y;return this}});ta.prototype=Object.create(la.prototype);ta.prototype.constructor=ta;ta.prototype.createAnimation=function(a,b,c,d){b={start:b,end:c,length:c-b+1,fps:d,duration:(c-b)/d,lastFrame:0,currentFrame:0,active:!1,time:0,direction:1,weight:1,directionBackwards:!1,mirroredLoop:!1};this.animationsMap[a]=b;this.animationsList.push(b)};ta.prototype.autoCreateAnimations=function(a){for(var b=/([a-z]+)_?(\d+)/i,c,d={},e=this.geometry,f=0,g=e.morphTargets.length;f<
14349 g;f++){var h=e.morphTargets[f].name.match(b);if(h&&1<h.length){var k=h[1];d[k]||(d[k]={start:Infinity,end:-Infinity});h=d[k];f<h.start&&(h.start=f);f>h.end&&(h.end=f);c||(c=k)}}for(k in d)h=d[k],this.createAnimation(k,h.start,h.end,a);this.firstAnimation=c};ta.prototype.setAnimationDirectionForward=function(a){if(a=this.animationsMap[a])a.direction=1,a.directionBackwards=!1};ta.prototype.setAnimationDirectionBackward=function(a){if(a=this.animationsMap[a])a.direction=-1,a.directionBackwards=!0};ta.prototype.setAnimationFPS=
14350 function(a,b){var c=this.animationsMap[a];c&&(c.fps=b,c.duration=(c.end-c.start)/c.fps)};ta.prototype.setAnimationDuration=function(a,b){var c=this.animationsMap[a];c&&(c.duration=b,c.fps=(c.end-c.start)/c.duration)};ta.prototype.setAnimationWeight=function(a,b){var c=this.animationsMap[a];c&&(c.weight=b)};ta.prototype.setAnimationTime=function(a,b){var c=this.animationsMap[a];c&&(c.time=b)};ta.prototype.getAnimationTime=function(a){var b=0;if(a=this.animationsMap[a])b=a.time;return b};ta.prototype.getAnimationDuration=
14351 function(a){var b=-1;if(a=this.animationsMap[a])b=a.duration;return b};ta.prototype.playAnimation=function(a){var b=this.animationsMap[a];b?(b.time=0,b.active=!0):console.warn("THREE.MorphBlendMesh: animation["+a+"] undefined in .playAnimation()")};ta.prototype.stopAnimation=function(a){if(a=this.animationsMap[a])a.active=!1};ta.prototype.update=function(a){for(var b=0,c=this.animationsList.length;b<c;b++){var d=this.animationsList[b];if(d.active){var e=d.duration/d.length;d.time+=d.direction*a;if(d.mirroredLoop){if(d.time>
14352 d.duration||0>d.time)d.direction*=-1,d.time>d.duration&&(d.time=d.duration,d.directionBackwards=!0),0>d.time&&(d.time=0,d.directionBackwards=!1)}else d.time%=d.duration,0>d.time&&(d.time+=d.duration);var f=d.start+Y.clamp(Math.floor(d.time/e),0,d.length-1),g=d.weight;f!==d.currentFrame&&(this.morphTargetInfluences[d.lastFrame]=0,this.morphTargetInfluences[d.currentFrame]=1*g,this.morphTargetInfluences[f]=0,d.lastFrame=d.currentFrame,d.currentFrame=f);e=d.time%e/e;d.directionBackwards&&(e=1-e);d.currentFrame!==
14353 d.lastFrame?(this.morphTargetInfluences[d.currentFrame]=e*g,this.morphTargetInfluences[d.lastFrame]=(1-e)*g):this.morphTargetInfluences[d.currentFrame]=g}}};Xc.prototype=Object.create(z.prototype);Xc.prototype.constructor=Xc;Xc.prototype.isImmediateRenderObject=!0;Yc.prototype=Object.create(Q.prototype);Yc.prototype.constructor=Yc;Yc.prototype.update=function(){var a=new n,b=new n,c=new Ba;return function(){var d=["a","b","c"];this.object.updateMatrixWorld(!0);c.getNormalMatrix(this.object.matrixWorld);
14354 var e=this.object.matrixWorld,f=this.geometry.attributes.position,g=this.object.geometry;if(g&&g.isGeometry)for(var h=g.vertices,k=g.faces,l=g=0,n=k.length;l<n;l++)for(var v=k[l],p=0,r=v.vertexNormals.length;p<r;p++){var z=v.vertexNormals[p];a.copy(h[v[d[p]]]).applyMatrix4(e);b.copy(z).applyMatrix3(c).normalize().multiplyScalar(this.size).add(a);f.setXYZ(g,a.x,a.y,a.z);g+=1;f.setXYZ(g,b.x,b.y,b.z);g+=1}else if(g&&g.isBufferGeometry)for(d=g.attributes.position,h=g.attributes.normal,p=g=0,r=d.count;p<
14355 r;p++)a.set(d.getX(p),d.getY(p),d.getZ(p)).applyMatrix4(e),b.set(h.getX(p),h.getY(p),h.getZ(p)),b.applyMatrix3(c).normalize().multiplyScalar(this.size).add(a),f.setXYZ(g,a.x,a.y,a.z),g+=1,f.setXYZ(g,b.x,b.y,b.z),g+=1;f.needsUpdate=!0}}();jc.prototype=Object.create(z.prototype);jc.prototype.constructor=jc;jc.prototype.dispose=function(){this.cone.geometry.dispose();this.cone.material.dispose()};jc.prototype.update=function(){var a=new n,b=new n;return function(){this.light.updateMatrixWorld();var c=
14356 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));this.cone.material.color.copy(this.light.color)}}();kc.prototype=Object.create(Q.prototype);kc.prototype.constructor=kc;kc.prototype.onBeforeRender=function(){var a=new n,b=new K,c=new K;return function(){var d=this.bones,e=this.geometry,f=e.getAttribute("position");c.getInverse(this.root.matrixWorld);
14357 for(var g=0,h=0;g<d.length;g++){var k=d[g];k.parent&&k.parent.isBone&&(b.multiplyMatrices(c,k.matrixWorld),a.setFromMatrixPosition(b),f.setXYZ(h,a.x,a.y,a.z),b.multiplyMatrices(c,k.parent.matrixWorld),a.setFromMatrixPosition(b),f.setXYZ(h+1,a.x,a.y,a.z),h+=2)}e.getAttribute("position").needsUpdate=!0}}();lc.prototype=Object.create(la.prototype);lc.prototype.constructor=lc;lc.prototype.dispose=function(){this.geometry.dispose();this.material.dispose()};lc.prototype.update=function(){this.material.color.copy(this.light.color)};
14358 mc.prototype=Object.create(z.prototype);mc.prototype.constructor=mc;mc.prototype.dispose=function(){this.children[0].geometry.dispose();this.children[0].material.dispose()};mc.prototype.update=function(){var a=this.children[0];a.material.color.copy(this.light.color);var b=.5*this.light.width,c=.5*this.light.height,a=a.geometry.attributes.position,d=a.array;d[0]=b;d[1]=-c;d[2]=0;d[3]=b;d[4]=c;d[5]=0;d[6]=-b;d[7]=c;d[8]=0;d[9]=-b;d[10]=-c;d[11]=0;d[12]=b;d[13]=-c;d[14]=0;a.needsUpdate=!0};nc.prototype=
14359 Object.create(z.prototype);nc.prototype.constructor=nc;nc.prototype.dispose=function(){this.children[0].geometry.dispose();this.children[0].material.dispose()};nc.prototype.update=function(){var a=new n,b=new G,c=new G;return function(){var d=this.children[0],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)}d.lookAt(a.setFromMatrixPosition(this.light.matrixWorld).negate());e.needsUpdate=
14360 !0}}();Zc.prototype=Object.create(Q.prototype);Zc.prototype.constructor=Zc;Jd.prototype=Object.create(Q.prototype);Jd.prototype.constructor=Jd;$c.prototype=Object.create(Q.prototype);$c.prototype.constructor=$c;$c.prototype.update=function(){var a=new n,b=new n,c=new Ba;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<
14361 l;k++){var n=f[k],v=n.normal;a.copy(g[n.a]).add(g[n.b]).add(g[n.c]).divideScalar(3).applyMatrix4(d);b.copy(v).applyMatrix3(c).normalize().multiplyScalar(this.size).add(a);e.setXYZ(h,a.x,a.y,a.z);h+=1;e.setXYZ(h,b.x,b.y,b.z);h+=1}e.needsUpdate=!0}}();oc.prototype=Object.create(z.prototype);oc.prototype.constructor=oc;oc.prototype.dispose=function(){var a=this.children[0],b=this.children[1];a.geometry.dispose();a.material.dispose();b.geometry.dispose();b.material.dispose()};oc.prototype.update=function(){var a=
14362 new n,b=new n,c=new n;return function(){a.setFromMatrixPosition(this.light.matrixWorld);b.setFromMatrixPosition(this.light.target.matrixWorld);c.subVectors(b,a);var d=this.children[0],e=this.children[1];d.lookAt(c);d.material.color.copy(this.light.color);e.lookAt(c);e.scale.z=c.length()}}();ad.prototype=Object.create(Q.prototype);ad.prototype.constructor=ad;ad.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"),h=0,k=a.length;h<
14363 k;h++)g.setXYZ(a[h],d.x,d.y,d.z)}var b,c,d=new n,e=new Na;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",0,1,-1);b.getAttribute("position").needsUpdate=
14364 !0}}();Ab.prototype=Object.create(Q.prototype);Ab.prototype.constructor=Ab;Ab.prototype.update=function(){var a=new Ra;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]=c.z;e[12]=c.x;e[13]=c.y;e[14]=b.z;e[15]=b.x;
14365 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()}}}();Ab.prototype.setFromObject=function(a){this.object=a;this.update();return this};var Kd,qe;Bb.prototype=Object.create(z.prototype);Bb.prototype.constructor=Bb;Bb.prototype.setDirection=function(){var a=new n,b;return function(c){.99999<c.y?this.quaternion.set(0,0,0,1):-.99999>c.y?this.quaternion.set(1,0,0,0):(a.set(c.z,0,-c.x).normalize(),b=Math.acos(c.y),this.quaternion.setFromAxisAngle(a,
14366 b))}}();Bb.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()};Bb.prototype.setColor=function(a){this.line.material.color.copy(a);this.cone.material.color.copy(a)};Ld.prototype=Object.create(Q.prototype);Ld.prototype.constructor=Ld;var Od=new n,ue=new re,ve=new re,we=new re;La.prototype=Object.create(ua.prototype);La.prototype.constructor=
14367 La;La.prototype.getPoint=function(a){var b=this.points,c=b.length;a*=c-(this.closed?0:1);var d=Math.floor(a);a-=d;this.closed?d+=0<d?0:(Math.floor(Math.abs(d)/b.length)+1)*b.length:0===a&&d===c-1&&(d=c-2,a=1);var e,f,g;this.closed||0<d?e=b[(d-1)%c]:(Od.subVectors(b[0],b[1]).add(b[0]),e=Od);f=b[d%c];g=b[(d+1)%c];this.closed||d+2<c?b=b[(d+2)%c]:(Od.subVectors(b[c-1],b[c-2]).add(b[c-1]),b=Od);if(void 0===this.type||"centripetal"===this.type||"chordal"===this.type){var h="chordal"===this.type?.5:.25,
14368 c=Math.pow(e.distanceToSquared(f),h),d=Math.pow(f.distanceToSquared(g),h),h=Math.pow(g.distanceToSquared(b),h);1E-4>d&&(d=1);1E-4>c&&(c=d);1E-4>h&&(h=d);ue.initNonuniformCatmullRom(e.x,f.x,g.x,b.x,c,d,h);ve.initNonuniformCatmullRom(e.y,f.y,g.y,b.y,c,d,h);we.initNonuniformCatmullRom(e.z,f.z,g.z,b.z,c,d,h)}else"catmullrom"===this.type&&(c=void 0!==this.tension?this.tension:.5,ue.initCatmullRom(e.x,f.x,g.x,b.x,c),ve.initCatmullRom(e.y,f.y,g.y,b.y,c),we.initCatmullRom(e.z,f.z,g.z,b.z,c));return new n(ue.calc(a),
14369 ve.calc(a),we.calc(a))};bd.prototype=Object.create(ua.prototype);bd.prototype.constructor=bd;bd.prototype.getPoint=function(a){var b=this.v0,c=this.v1,d=this.v2,e=this.v3;return new n(xb(a,b.x,c.x,d.x,e.x),xb(a,b.y,c.y,d.y,e.y),xb(a,b.z,c.z,d.z,e.z))};cd.prototype=Object.create(ua.prototype);cd.prototype.constructor=cd;cd.prototype.getPoint=function(a){var b=this.v0,c=this.v1,d=this.v2;return new n(wb(a,b.x,c.x,d.x),wb(a,b.y,c.y,d.y),wb(a,b.z,c.z,d.z))};dd.prototype=Object.create(ua.prototype);dd.prototype.constructor=
14370 dd;dd.prototype.getPoint=function(a){if(1===a)return this.v2.clone();var b=new n;b.subVectors(this.v2,this.v1);b.multiplyScalar(a);b.add(this.v1);return b};Md.prototype=Object.create(Va.prototype);Md.prototype.constructor=Md;ua.create=function(a,b){console.log("THREE.Curve.create() has been deprecated");a.prototype=Object.create(ua.prototype);a.prototype.constructor=a;a.prototype.getPoint=b;return a};cf.prototype=Object.create(La.prototype);df.prototype=Object.create(La.prototype);se.prototype=Object.create(La.prototype);
14371 Object.assign(se.prototype,{initFromArray:function(a){console.error("THREE.Spline: .initFromArray() has been removed.")},getControlPointsArray:function(a){console.error("THREE.Spline: .getControlPointsArray() has been removed.")},reparametrizeByArcLength:function(a){console.error("THREE.Spline: .reparametrizeByArcLength() has been removed.")}});Zc.prototype.setColors=function(){console.error("THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.")};kc.prototype.update=
14372 function(){console.error("THREE.SkeletonHelper: update() no longer needs to be called.")};Object.assign(fd.prototype,{center:function(a){console.warn("THREE.Box2: .center() has been renamed to .getCenter().");return this.getCenter(a)},empty:function(){console.warn("THREE.Box2: .empty() has been renamed to .isEmpty().");return this.isEmpty()},isIntersectionBox:function(a){console.warn("THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().");return this.intersectsBox(a)},size:function(a){console.warn("THREE.Box2: .size() has been renamed to .getSize().");
14373 return this.getSize(a)}});Object.assign(Ra.prototype,{center:function(a){console.warn("THREE.Box3: .center() has been renamed to .getCenter().");return this.getCenter(a)},empty:function(){console.warn("THREE.Box3: .empty() has been renamed to .isEmpty().");return this.isEmpty()},isIntersectionBox:function(a){console.warn("THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().");return this.intersectsBox(a)},isIntersectionSphere:function(a){console.warn("THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().");
14374 return this.intersectsSphere(a)},size:function(a){console.warn("THREE.Box3: .size() has been renamed to .getSize().");return this.getSize(a)}});Hb.prototype.center=function(a){console.warn("THREE.Line3: .center() has been renamed to .getCenter().");return this.getCenter(a)};Y.random16=function(){console.warn("THREE.Math.random16() has been deprecated. Use Math.random() instead.");return Math.random()};Object.assign(Ba.prototype,{flattenToArrayOffset:function(a,b){console.warn("THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
14375 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(a){console.error("THREE.Matrix3: .multiplyVector3Array() has been removed.")},applyToBuffer:function(a,b,c){console.warn("THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.");return this.applyToBufferAttribute(a)},applyToVector3Array:function(a,
14376 b,c){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;return function(){void 0===a&&(a=new n);console.warn("THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.");
14377 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.");return a.applyMatrix4(this)},multiplyVector4:function(a){console.warn("THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.");
14378 return a.applyMatrix4(this)},multiplyVector3Array:function(a){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.");return a.applyMatrix4(this)},translate:function(){console.error("THREE.Matrix4: .translate() has been removed.")},
14379 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,b,c){console.warn("THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.");return this.applyToBufferAttribute(a)},
14380 applyToVector3Array:function(a,b,c){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)};oa.prototype.multiplyVector3=
14381 function(a){console.warn("THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.");return a.applyQuaternion(this)};Object.assign(kb.prototype,{isIntersectionBox:function(a){console.warn("THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().");return this.intersectsBox(a)},isIntersectionPlane:function(a){console.warn("THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().");return this.intersectsPlane(a)},isIntersectionSphere:function(a){console.warn("THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().");
14382 return this.intersectsSphere(a)}});Object.assign(zb.prototype,{extrude:function(a){console.warn("THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.");return new cb(this,a)},makeGeometry:function(a){console.warn("THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.");return new Xb(this,a)}});Object.assign(C.prototype,{fromAttribute:function(a,b,c){console.error("THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().");return this.fromBufferAttribute(a,
14383 b,c)}});Object.assign(n.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)},
14384 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,
14385 b,c){console.error("THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().");return this.fromBufferAttribute(a,b,c)}});Object.assign(fa.prototype,{fromAttribute:function(a,b,c){console.error("THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().");return this.fromBufferAttribute(a,b,c)}});J.prototype.computeTangents=function(){console.warn("THREE.Geometry: .computeTangents() has been removed.")};Object.assign(z.prototype,{getChildByName:function(a){console.warn("THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().");
14386 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(z.prototype,{eulerOrder:{get:function(){console.warn("THREE.Object3D: .eulerOrder is now .rotation.order.");return this.rotation.order},set:function(a){console.warn("THREE.Object3D: .eulerOrder is now .rotation.order.");
14387 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(yc.prototype,{objects:{get:function(){console.warn("THREE.LOD: .objects has been renamed to .levels.");return this.levels}}});Object.defineProperty(zc.prototype,"useVertexTexture",{get:function(){console.warn("THREE.Skeleton: useVertexTexture has been removed.")},
14388 set:function(){console.warn("THREE.Skeleton: useVertexTexture has been removed.")}});Object.defineProperty(ua.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}});qa.prototype.setLens=function(a,b){console.warn("THREE.PerspectiveCamera.setLens is deprecated. Use .setFocalLength and .filmGauge for a photographic setup.");
14389 void 0!==b&&(this.filmGauge=b);this.setFocalLength(a)};Object.defineProperties(na.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.");
14390 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.");
14391 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.");
14392 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(Z.prototype,{length:{get:function(){console.warn("THREE.BufferAttribute: .length has been deprecated. Use .count instead.");return this.array.length}}});Object.assign(E.prototype,{addIndex:function(a){console.warn("THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().");this.setIndex(a)},addDrawCall:function(a,
14393 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.")}});
14394 Object.defineProperties(E.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(Id.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.");
14395 return this}}});Object.defineProperties(U.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 G}}});Object.defineProperties(Ja.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")}}});
14396 Object.defineProperties(ra.prototype,{derivatives:{get:function(){console.warn("THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.");return this.extensions.derivatives},set:function(a){console.warn("THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.");this.extensions.derivatives=a}}});Object.assign(Xd.prototype,{getCurrentRenderTarget:function(){console.warn("THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().");return this.getRenderTarget()},
14397 supportsFloatTextures:function(){console.warn("THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( 'OES_texture_float' ).");return this.extensions.get("OES_texture_float")},supportsHalfFloatTextures:function(){console.warn("THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( 'OES_texture_half_float' ).");return this.extensions.get("OES_texture_half_float")},supportsStandardDerivatives:function(){console.warn("THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( 'OES_standard_derivatives' ).");
14398 return this.extensions.get("OES_standard_derivatives")},supportsCompressedTextureS3TC:function(){console.warn("THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( 'WEBGL_compressed_texture_s3tc' ).");return this.extensions.get("WEBGL_compressed_texture_s3tc")},supportsCompressedTexturePVRTC:function(){console.warn("THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( 'WEBGL_compressed_texture_pvrtc' ).");return this.extensions.get("WEBGL_compressed_texture_pvrtc")},
14399 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.");return this.capabilities.vertexTextures},supportsInstancedArrays:function(){console.warn("THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( 'ANGLE_instanced_arrays' ).");
14400 return this.extensions.get("ANGLE_instanced_arrays")},enableScissorTest:function(a){console.warn("THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().");this.setScissorTest(a)},initMaterial:function(){console.warn("THREE.WebGLRenderer: .initMaterial() has been removed.")},addPrePlugin:function(){console.warn("THREE.WebGLRenderer: .addPrePlugin() has been removed.")},addPostPlugin:function(){console.warn("THREE.WebGLRenderer: .addPostPlugin() has been removed.")},updateShadowMap:function(){console.warn("THREE.WebGLRenderer: .updateShadowMap() has been removed.")}});
14401 Object.defineProperties(Xd.prototype,{shadowMapEnabled:{get:function(){return this.shadowMap.enabled},set:function(a){console.warn("THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.");this.shadowMap.enabled=a}},shadowMapType:{get:function(){return this.shadowMap.type},set:function(a){console.warn("THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.");this.shadowMap.type=a}},shadowMapCullFace:{get:function(){return this.shadowMap.cullFace},set:function(a){console.warn("THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.");
14402 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(Cb.prototype,{wrapS:{get:function(){console.warn("THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.");return this.texture.wrapS},set:function(a){console.warn("THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.");
14403 this.texture.wrapS=a}},wrapT:{get:function(){console.warn("THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.");return this.texture.wrapT},set:function(a){console.warn("THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.");this.texture.wrapT=a}},magFilter:{get:function(){console.warn("THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.");return this.texture.magFilter},set:function(a){console.warn("THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.");this.texture.magFilter=
14404 a}},minFilter:{get:function(){console.warn("THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.");return this.texture.minFilter},set:function(a){console.warn("THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.");this.texture.minFilter=a}},anisotropy:{get:function(){console.warn("THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.");return this.texture.anisotropy},set:function(a){console.warn("THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.");this.texture.anisotropy=
14405 a}},offset:{get:function(){console.warn("THREE.WebGLRenderTarget: .offset is now .texture.offset.");return this.texture.offset},set:function(a){console.warn("THREE.WebGLRenderTarget: .offset is now .texture.offset.");this.texture.offset=a}},repeat:{get:function(){console.warn("THREE.WebGLRenderTarget: .repeat is now .texture.repeat.");return this.texture.repeat},set:function(a){console.warn("THREE.WebGLRenderTarget: .repeat is now .texture.repeat.");this.texture.repeat=a}},format:{get:function(){console.warn("THREE.WebGLRenderTarget: .format is now .texture.format.");
14406 return this.texture.format},set:function(a){console.warn("THREE.WebGLRenderTarget: .format is now .texture.format.");this.texture.format=a}},type:{get:function(){console.warn("THREE.WebGLRenderTarget: .type is now .texture.type.");return this.texture.type},set:function(a){console.warn("THREE.WebGLRenderTarget: .type is now .texture.type.");this.texture.type=a}},generateMipmaps:{get:function(){console.warn("THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.");return this.texture.generateMipmaps},
14407 set:function(a){console.warn("THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.");this.texture.generateMipmaps=a}}});hc.prototype.load=function(a){console.warn("THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.");var b=this;(new fe).load(a,function(a){b.setBuffer(a)});return this};je.prototype.getData=function(){console.warn("THREE.AudioAnalyser: .getData() is now .getFrequencyData().");return this.getFrequencyData()};l.WebGLRenderTargetCube=Db;l.WebGLRenderTarget=
14408 Cb;l.WebGLRenderer=Xd;l.ShaderLib=$a;l.UniformsLib=R;l.UniformsUtils=Ca;l.ShaderChunk=X;l.FogExp2=Ib;l.Fog=Jb;l.Scene=ld;l.LensFlare=Yd;l.Sprite=xc;l.LOD=yc;l.SkinnedMesh=nd;l.Skeleton=zc;l.Bone=md;l.Mesh=la;l.LineSegments=Q;l.LineLoop=od;l.Line=sa;l.Points=Kb;l.Group=Ac;l.VideoTexture=pd;l.DataTexture=db;l.CompressedTexture=Lb;l.CubeTexture=Xa;l.CanvasTexture=qd;l.DepthTexture=Bc;l.Texture=ba;l.CompressedTextureLoader=Oe;l.DataTextureLoader=$d;l.CubeTextureLoader=ae;l.TextureLoader=rd;l.ObjectLoader=
14409 Pe;l.MaterialLoader=Gd;l.BufferGeometryLoader=be;l.DefaultLoadingManager=va;l.LoadingManager=Zd;l.JSONLoader=ce;l.ImageLoader=Sc;l.FontLoader=Re;l.FileLoader=Ka;l.Loader=ec;l.Cache=ed;l.AudioLoader=fe;l.SpotLightShadow=td;l.SpotLight=ud;l.PointLight=vd;l.RectAreaLight=zd;l.HemisphereLight=sd;l.DirectionalLightShadow=wd;l.DirectionalLight=xd;l.AmbientLight=yd;l.LightShadow=tb;l.Light=na;l.StereoCamera=Se;l.PerspectiveCamera=qa;l.OrthographicCamera=Fb;l.CubeCamera=Hd;l.ArrayCamera=kd;l.Camera=Na;l.AudioListener=
14410 ge;l.PositionalAudio=ie;l.AudioContext=he;l.AudioAnalyser=je;l.Audio=hc;l.VectorKeyframeTrack=cc;l.StringKeyframeTrack=Dd;l.QuaternionKeyframeTrack=Uc;l.NumberKeyframeTrack=dc;l.ColorKeyframeTrack=Fd;l.BooleanKeyframeTrack=Ed;l.PropertyMixer=ke;l.PropertyBinding=ha;l.KeyframeTrack=vb;l.AnimationUtils=ia;l.AnimationObjectGroup=Ue;l.AnimationMixer=We;l.AnimationClip=Da;l.Uniform=Id;l.InstancedBufferGeometry=le;l.BufferGeometry=E;l.GeometryIdCount=function(){return Rd++};l.Geometry=J;l.InterleavedBufferAttribute=
14411 me;l.InstancedInterleavedBuffer=ne;l.InterleavedBuffer=ic;l.InstancedBufferAttribute=oe;l.Face3=Sa;l.Object3D=z;l.Raycaster=Xe;l.Layers=Qd;l.EventDispatcher=xa;l.Clock=Ze;l.QuaternionLinearInterpolant=Cd;l.LinearInterpolant=Tc;l.DiscreteInterpolant=Bd;l.CubicInterpolant=Ad;l.Interpolant=wa;l.Triangle=Ta;l.Math=Y;l.Spherical=$e;l.Cylindrical=af;l.Plane=Aa;l.Frustum=gd;l.Sphere=Ea;l.Ray=kb;l.Matrix4=K;l.Matrix3=Ba;l.Box3=Ra;l.Box2=fd;l.Line3=Hb;l.Euler=ab;l.Vector4=fa;l.Vector3=n;l.Vector2=C;l.Quaternion=
14412 oa;l.Color=G;l.MorphBlendMesh=ta;l.ImmediateRenderObject=Xc;l.VertexNormalsHelper=Yc;l.SpotLightHelper=jc;l.SkeletonHelper=kc;l.PointLightHelper=lc;l.RectAreaLightHelper=mc;l.HemisphereLightHelper=nc;l.GridHelper=Zc;l.PolarGridHelper=Jd;l.FaceNormalsHelper=$c;l.DirectionalLightHelper=oc;l.CameraHelper=ad;l.BoxHelper=Ab;l.ArrowHelper=Bb;l.AxisHelper=Ld;l.CatmullRomCurve3=La;l.CubicBezierCurve3=bd;l.QuadraticBezierCurve3=cd;l.LineCurve3=dd;l.ArcCurve=Md;l.EllipseCurve=Va;l.SplineCurve=yb;l.CubicBezierCurve=
14413 fc;l.QuadraticBezierCurve=gc;l.LineCurve=Qa;l.Shape=zb;l.Path=Wc;l.ShapePath=de;l.Font=ee;l.CurvePath=Vc;l.Curve=ua;l.ShapeUtils=Ia;l.SceneUtils={createMultiMaterialObject:function(a,b){for(var c=new Ac,d=0,e=b.length;d<e;d++)c.add(new la(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)}};l.WireframeGeometry=Mb;l.ParametricGeometry=Cc;l.ParametricBufferGeometry=
14414 Nb;l.TetrahedronGeometry=Ec;l.TetrahedronBufferGeometry=Ob;l.OctahedronGeometry=Fc;l.OctahedronBufferGeometry=lb;l.IcosahedronGeometry=Gc;l.IcosahedronBufferGeometry=Pb;l.DodecahedronGeometry=Hc;l.DodecahedronBufferGeometry=Qb;l.PolyhedronGeometry=Dc;l.PolyhedronBufferGeometry=za;l.TubeGeometry=Ic;l.TubeBufferGeometry=Rb;l.TorusKnotGeometry=Jc;l.TorusKnotBufferGeometry=Sb;l.TorusGeometry=Kc;l.TorusBufferGeometry=Tb;l.TextGeometry=Lc;l.TextBufferGeometry=Ub;l.SphereGeometry=Mc;l.SphereBufferGeometry=
14415 mb;l.RingGeometry=Nc;l.RingBufferGeometry=Vb;l.PlaneGeometry=vc;l.PlaneBufferGeometry=jb;l.LatheGeometry=Oc;l.LatheBufferGeometry=Wb;l.ShapeGeometry=Xb;l.ShapeBufferGeometry=Yb;l.ExtrudeGeometry=cb;l.ExtrudeBufferGeometry=Ga;l.EdgesGeometry=Zb;l.ConeGeometry=Pc;l.ConeBufferGeometry=Qc;l.CylinderGeometry=nb;l.CylinderBufferGeometry=Ua;l.CircleGeometry=Rc;l.CircleBufferGeometry=$b;l.BoxGeometry=Gb;l.BoxBufferGeometry=ib;l.ShadowMaterial=ac;l.SpriteMaterial=bb;l.RawShaderMaterial=bc;l.ShaderMaterial=
14416 ra;l.PointsMaterial=Fa;l.MeshPhysicalMaterial=ob;l.MeshStandardMaterial=Pa;l.MeshPhongMaterial=Ja;l.MeshToonMaterial=pb;l.MeshNormalMaterial=qb;l.MeshLambertMaterial=rb;l.MeshDepthMaterial=Za;l.MeshBasicMaterial=ya;l.LineDashedMaterial=sb;l.LineBasicMaterial=ea;l.Material=U;l.Float64BufferAttribute=uc;l.Float32BufferAttribute=B;l.Uint32BufferAttribute=hb;l.Int32BufferAttribute=tc;l.Uint16BufferAttribute=gb;l.Int16BufferAttribute=sc;l.Uint8ClampedBufferAttribute=rc;l.Uint8BufferAttribute=qc;l.Int8BufferAttribute=
14417 pc;l.BufferAttribute=Z;l.REVISION="86";l.MOUSE={LEFT:0,MIDDLE:1,RIGHT:2};l.CullFaceNone=0;l.CullFaceBack=1;l.CullFaceFront=2;l.CullFaceFrontBack=3;l.FrontFaceDirectionCW=0;l.FrontFaceDirectionCCW=1;l.BasicShadowMap=0;l.PCFShadowMap=1;l.PCFSoftShadowMap=2;l.FrontSide=0;l.BackSide=1;l.DoubleSide=2;l.FlatShading=1;l.SmoothShading=2;l.NoColors=0;l.FaceColors=1;l.VertexColors=2;l.NoBlending=0;l.NormalBlending=1;l.AdditiveBlending=2;l.SubtractiveBlending=3;l.MultiplyBlending=4;l.CustomBlending=5;l.AddEquation=
14418 100;l.SubtractEquation=101;l.ReverseSubtractEquation=102;l.MinEquation=103;l.MaxEquation=104;l.ZeroFactor=200;l.OneFactor=201;l.SrcColorFactor=202;l.OneMinusSrcColorFactor=203;l.SrcAlphaFactor=204;l.OneMinusSrcAlphaFactor=205;l.DstAlphaFactor=206;l.OneMinusDstAlphaFactor=207;l.DstColorFactor=208;l.OneMinusDstColorFactor=209;l.SrcAlphaSaturateFactor=210;l.NeverDepth=0;l.AlwaysDepth=1;l.LessDepth=2;l.LessEqualDepth=3;l.EqualDepth=4;l.GreaterEqualDepth=5;l.GreaterDepth=6;l.NotEqualDepth=7;l.MultiplyOperation=
14419 0;l.MixOperation=1;l.AddOperation=2;l.NoToneMapping=0;l.LinearToneMapping=1;l.ReinhardToneMapping=2;l.Uncharted2ToneMapping=3;l.CineonToneMapping=4;l.UVMapping=300;l.CubeReflectionMapping=301;l.CubeRefractionMapping=302;l.EquirectangularReflectionMapping=303;l.EquirectangularRefractionMapping=304;l.SphericalReflectionMapping=305;l.CubeUVReflectionMapping=306;l.CubeUVRefractionMapping=307;l.RepeatWrapping=1E3;l.ClampToEdgeWrapping=1001;l.MirroredRepeatWrapping=1002;l.NearestFilter=1003;l.NearestMipMapNearestFilter=
14420 1004;l.NearestMipMapLinearFilter=1005;l.LinearFilter=1006;l.LinearMipMapNearestFilter=1007;l.LinearMipMapLinearFilter=1008;l.UnsignedByteType=1009;l.ByteType=1010;l.ShortType=1011;l.UnsignedShortType=1012;l.IntType=1013;l.UnsignedIntType=1014;l.FloatType=1015;l.HalfFloatType=1016;l.UnsignedShort4444Type=1017;l.UnsignedShort5551Type=1018;l.UnsignedShort565Type=1019;l.UnsignedInt248Type=1020;l.AlphaFormat=1021;l.RGBFormat=1022;l.RGBAFormat=1023;l.LuminanceFormat=1024;l.LuminanceAlphaFormat=1025;l.RGBEFormat=
14421 1023;l.DepthFormat=1026;l.DepthStencilFormat=1027;l.RGB_S3TC_DXT1_Format=2001;l.RGBA_S3TC_DXT1_Format=2002;l.RGBA_S3TC_DXT3_Format=2003;l.RGBA_S3TC_DXT5_Format=2004;l.RGB_PVRTC_4BPPV1_Format=2100;l.RGB_PVRTC_2BPPV1_Format=2101;l.RGBA_PVRTC_4BPPV1_Format=2102;l.RGBA_PVRTC_2BPPV1_Format=2103;l.RGB_ETC1_Format=2151;l.LoopOnce=2200;l.LoopRepeat=2201;l.LoopPingPong=2202;l.InterpolateDiscrete=2300;l.InterpolateLinear=2301;l.InterpolateSmooth=2302;l.ZeroCurvatureEnding=2400;l.ZeroSlopeEnding=2401;l.WrapAroundEnding=
14422 2402;l.TrianglesDrawMode=0;l.TriangleStripDrawMode=1;l.TriangleFanDrawMode=2;l.LinearEncoding=3E3;l.sRGBEncoding=3001;l.GammaEncoding=3007;l.RGBEEncoding=3002;l.LogLuvEncoding=3003;l.RGBM7Encoding=3004;l.RGBM16Encoding=3005;l.RGBDEncoding=3006;l.BasicDepthPacking=3200;l.RGBADepthPacking=3201;l.CubeGeometry=Gb;l.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 Sa(a,b,c,e,f,g)};l.LineStrip=0;l.LinePieces=1;l.MeshFaceMaterial=
14423 function(a){console.warn("THREE.MeshFaceMaterial has been removed. Use an Array instead.");return a};l.MultiMaterial=function(a){void 0===a&&(a=[]);console.warn("THREE.MultiMaterial has been removed. Use an Array instead.");a.isMultiMaterial=!0;a.materials=a;a.clone=function(){return a.slice()};return a};l.PointCloud=function(a,b){console.warn("THREE.PointCloud has been renamed to THREE.Points.");return new Kb(a,b)};l.Particle=function(a){console.warn("THREE.Particle has been renamed to THREE.Sprite.");
14424 return new xc(a)};l.ParticleSystem=function(a,b){console.warn("THREE.ParticleSystem has been renamed to THREE.Points.");return new Kb(a,b)};l.PointCloudMaterial=function(a){console.warn("THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.");return new Fa(a)};l.ParticleBasicMaterial=function(a){console.warn("THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.");return new Fa(a)};l.ParticleSystemMaterial=function(a){console.warn("THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.");
14425 return new Fa(a)};l.Vertex=function(a,b,c){console.warn("THREE.Vertex has been removed. Use THREE.Vector3 instead.");return new n(a,b,c)};l.DynamicBufferAttribute=function(a,b){console.warn("THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.");return(new Z(a,b)).setDynamic(!0)};l.Int8Attribute=function(a,b){console.warn("THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.");return new pc(a,b)};l.Uint8Attribute=
14426 function(a,b){console.warn("THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.");return new qc(a,b)};l.Uint8ClampedAttribute=function(a,b){console.warn("THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.");return new rc(a,b)};l.Int16Attribute=function(a,b){console.warn("THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.");return new sc(a,b)};l.Uint16Attribute=function(a,b){console.warn("THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.");
14427 return new gb(a,b)};l.Int32Attribute=function(a,b){console.warn("THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.");return new tc(a,b)};l.Uint32Attribute=function(a,b){console.warn("THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.");return new hb(a,b)};l.Float32Attribute=function(a,b){console.warn("THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.");return new B(a,b)};l.Float64Attribute=
14428 function(a,b){console.warn("THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.");return new uc(a,b)};l.ClosedSplineCurve3=cf;l.SplineCurve3=df;l.Spline=se;l.BoundingBoxHelper=function(a,b){console.warn("THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.");return new Ab(a,b)};l.EdgesHelper=function(a,b){console.warn("THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.");return new Q(new Zb(a.geometry),new ea({color:void 0!==
14429 b?b:16777215}))};l.WireframeHelper=function(a,b){console.warn("THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.");return new Q(new Mb(a.geometry),new ea({color:void 0!==b?b:16777215}))};l.XHRLoader=function(a){console.warn("THREE.XHRLoader has been renamed to THREE.FileLoader.");return new Ka(a)};l.BinaryTextureLoader=function(a){console.warn("THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.");return new $d(a)};l.GeometryUtils={merge:function(a,b,
14430 c){console.warn("THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.");var d;b.isMesh&&(b.matrixAutoUpdate&&b.updateMatrix(),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()}};l.ImageUtils={crossOrigin:void 0,loadTexture:function(a,b,c,d){console.warn("THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.");
14431 var e=new rd;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.");var e=new ae;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.")}};
14432 l.Projector=function(){console.error("THREE.Projector has been moved to /examples/js/renderers/Projector.js.");this.projectVector=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().")}};l.CanvasRenderer=function(){console.error("THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js");
14433 this.domElement=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");this.clear=function(){};this.render=function(){};this.setClearColor=function(){};this.setSize=function(){}};Object.defineProperty(l,"__esModule",{value:!0})});
14435 },{}],177:[function(require,module,exports){
14438 module.exports = TinyQueue;
14440 function TinyQueue(data, compare) {
14441 if (!(this instanceof TinyQueue)) return new TinyQueue(data, compare);
14443 this.data = data || [];
14444 this.length = this.data.length;
14445 this.compare = compare || defaultCompare;
14447 if (this.length > 0) {
14448 for (var i = (this.length >> 1); i >= 0; i--) this._down(i);
14452 function defaultCompare(a, b) {
14453 return a < b ? -1 : a > b ? 1 : 0;
14456 TinyQueue.prototype = {
14458 push: function (item) {
14459 this.data.push(item);
14461 this._up(this.length - 1);
14465 if (this.length === 0) return undefined;
14466 var top = this.data[0];
14468 if (this.length > 0) {
14469 this.data[0] = this.data[this.length];
14476 peek: function () {
14477 return this.data[0];
14480 _up: function (pos) {
14481 var data = this.data;
14482 var compare = this.compare;
14483 var item = data[pos];
14486 var parent = (pos - 1) >> 1;
14487 var current = data[parent];
14488 if (compare(item, current) >= 0) break;
14489 data[pos] = current;
14496 _down: function (pos) {
14497 var data = this.data;
14498 var compare = this.compare;
14499 var len = this.length;
14500 var halfLen = len >> 1;
14501 var item = data[pos];
14503 while (pos < halfLen) {
14504 var left = (pos << 1) + 1;
14505 var right = left + 1;
14506 var best = data[left];
14508 if (right < len && compare(data[right], best) < 0) {
14510 best = data[right];
14512 if (compare(best, item) >= 0) break;
14522 },{}],178:[function(require,module,exports){
14523 // Underscore.js 1.8.3
14524 // http://underscorejs.org
14525 // (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
14526 // Underscore may be freely distributed under the MIT license.
14533 // Establish the root object, `window` in the browser, or `exports` on the server.
14536 // Save the previous value of the `_` variable.
14537 var previousUnderscore = root._;
14539 // Save bytes in the minified (but not gzipped) version:
14540 var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
14542 // Create quick reference variables for speed access to core prototypes.
14544 push = ArrayProto.push,
14545 slice = ArrayProto.slice,
14546 toString = ObjProto.toString,
14547 hasOwnProperty = ObjProto.hasOwnProperty;
14549 // All **ECMAScript 5** native function implementations that we hope to use
14550 // are declared here.
14552 nativeIsArray = Array.isArray,
14553 nativeKeys = Object.keys,
14554 nativeBind = FuncProto.bind,
14555 nativeCreate = Object.create;
14557 // Naked function reference for surrogate-prototype-swapping.
14558 var Ctor = function(){};
14560 // Create a safe reference to the Underscore object for use below.
14561 var _ = function(obj) {
14562 if (obj instanceof _) return obj;
14563 if (!(this instanceof _)) return new _(obj);
14564 this._wrapped = obj;
14567 // Export the Underscore object for **Node.js**, with
14568 // backwards-compatibility for the old `require()` API. If we're in
14569 // the browser, add `_` as a global object.
14570 if (typeof exports !== 'undefined') {
14571 if (typeof module !== 'undefined' && module.exports) {
14572 exports = module.exports = _;
14579 // Current version.
14580 _.VERSION = '1.8.3';
14582 // Internal function that returns an efficient (for current engines) version
14583 // of the passed-in callback, to be repeatedly applied in other Underscore
14585 var optimizeCb = function(func, context, argCount) {
14586 if (context === void 0) return func;
14587 switch (argCount == null ? 3 : argCount) {
14588 case 1: return function(value) {
14589 return func.call(context, value);
14591 case 2: return function(value, other) {
14592 return func.call(context, value, other);
14594 case 3: return function(value, index, collection) {
14595 return func.call(context, value, index, collection);
14597 case 4: return function(accumulator, value, index, collection) {
14598 return func.call(context, accumulator, value, index, collection);
14601 return function() {
14602 return func.apply(context, arguments);
14606 // A mostly-internal function to generate callbacks that can be applied
14607 // to each element in a collection, returning the desired result — either
14608 // identity, an arbitrary callback, a property matcher, or a property accessor.
14609 var cb = function(value, context, argCount) {
14610 if (value == null) return _.identity;
14611 if (_.isFunction(value)) return optimizeCb(value, context, argCount);
14612 if (_.isObject(value)) return _.matcher(value);
14613 return _.property(value);
14615 _.iteratee = function(value, context) {
14616 return cb(value, context, Infinity);
14619 // An internal function for creating assigner functions.
14620 var createAssigner = function(keysFunc, undefinedOnly) {
14621 return function(obj) {
14622 var length = arguments.length;
14623 if (length < 2 || obj == null) return obj;
14624 for (var index = 1; index < length; index++) {
14625 var source = arguments[index],
14626 keys = keysFunc(source),
14628 for (var i = 0; i < l; i++) {
14630 if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];
14637 // An internal function for creating a new object that inherits from another.
14638 var baseCreate = function(prototype) {
14639 if (!_.isObject(prototype)) return {};
14640 if (nativeCreate) return nativeCreate(prototype);
14641 Ctor.prototype = prototype;
14642 var result = new Ctor;
14643 Ctor.prototype = null;
14647 var property = function(key) {
14648 return function(obj) {
14649 return obj == null ? void 0 : obj[key];
14653 // Helper for collection methods to determine whether a collection
14654 // should be iterated as an array or as an object
14655 // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
14656 // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
14657 var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
14658 var getLength = property('length');
14659 var isArrayLike = function(collection) {
14660 var length = getLength(collection);
14661 return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
14664 // Collection Functions
14665 // --------------------
14667 // The cornerstone, an `each` implementation, aka `forEach`.
14668 // Handles raw objects in addition to array-likes. Treats all
14669 // sparse array-likes as if they were dense.
14670 _.each = _.forEach = function(obj, iteratee, context) {
14671 iteratee = optimizeCb(iteratee, context);
14673 if (isArrayLike(obj)) {
14674 for (i = 0, length = obj.length; i < length; i++) {
14675 iteratee(obj[i], i, obj);
14678 var keys = _.keys(obj);
14679 for (i = 0, length = keys.length; i < length; i++) {
14680 iteratee(obj[keys[i]], keys[i], obj);
14686 // Return the results of applying the iteratee to each element.
14687 _.map = _.collect = function(obj, iteratee, context) {
14688 iteratee = cb(iteratee, context);
14689 var keys = !isArrayLike(obj) && _.keys(obj),
14690 length = (keys || obj).length,
14691 results = Array(length);
14692 for (var index = 0; index < length; index++) {
14693 var currentKey = keys ? keys[index] : index;
14694 results[index] = iteratee(obj[currentKey], currentKey, obj);
14699 // Create a reducing function iterating left or right.
14700 function createReduce(dir) {
14701 // Optimized iterator function as using arguments.length
14702 // in the main function will deoptimize the, see #1991.
14703 function iterator(obj, iteratee, memo, keys, index, length) {
14704 for (; index >= 0 && index < length; index += dir) {
14705 var currentKey = keys ? keys[index] : index;
14706 memo = iteratee(memo, obj[currentKey], currentKey, obj);
14711 return function(obj, iteratee, memo, context) {
14712 iteratee = optimizeCb(iteratee, context, 4);
14713 var keys = !isArrayLike(obj) && _.keys(obj),
14714 length = (keys || obj).length,
14715 index = dir > 0 ? 0 : length - 1;
14716 // Determine the initial value if none is provided.
14717 if (arguments.length < 3) {
14718 memo = obj[keys ? keys[index] : index];
14721 return iterator(obj, iteratee, memo, keys, index, length);
14725 // **Reduce** builds up a single result from a list of values, aka `inject`,
14727 _.reduce = _.foldl = _.inject = createReduce(1);
14729 // The right-associative version of reduce, also known as `foldr`.
14730 _.reduceRight = _.foldr = createReduce(-1);
14732 // Return the first value which passes a truth test. Aliased as `detect`.
14733 _.find = _.detect = function(obj, predicate, context) {
14735 if (isArrayLike(obj)) {
14736 key = _.findIndex(obj, predicate, context);
14738 key = _.findKey(obj, predicate, context);
14740 if (key !== void 0 && key !== -1) return obj[key];
14743 // Return all the elements that pass a truth test.
14744 // Aliased as `select`.
14745 _.filter = _.select = function(obj, predicate, context) {
14747 predicate = cb(predicate, context);
14748 _.each(obj, function(value, index, list) {
14749 if (predicate(value, index, list)) results.push(value);
14754 // Return all the elements for which a truth test fails.
14755 _.reject = function(obj, predicate, context) {
14756 return _.filter(obj, _.negate(cb(predicate)), context);
14759 // Determine whether all of the elements match a truth test.
14760 // Aliased as `all`.
14761 _.every = _.all = function(obj, predicate, context) {
14762 predicate = cb(predicate, context);
14763 var keys = !isArrayLike(obj) && _.keys(obj),
14764 length = (keys || obj).length;
14765 for (var index = 0; index < length; index++) {
14766 var currentKey = keys ? keys[index] : index;
14767 if (!predicate(obj[currentKey], currentKey, obj)) return false;
14772 // Determine if at least one element in the object matches a truth test.
14773 // Aliased as `any`.
14774 _.some = _.any = function(obj, predicate, context) {
14775 predicate = cb(predicate, context);
14776 var keys = !isArrayLike(obj) && _.keys(obj),
14777 length = (keys || obj).length;
14778 for (var index = 0; index < length; index++) {
14779 var currentKey = keys ? keys[index] : index;
14780 if (predicate(obj[currentKey], currentKey, obj)) return true;
14785 // Determine if the array or object contains a given item (using `===`).
14786 // Aliased as `includes` and `include`.
14787 _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {
14788 if (!isArrayLike(obj)) obj = _.values(obj);
14789 if (typeof fromIndex != 'number' || guard) fromIndex = 0;
14790 return _.indexOf(obj, item, fromIndex) >= 0;
14793 // Invoke a method (with arguments) on every item in a collection.
14794 _.invoke = function(obj, method) {
14795 var args = slice.call(arguments, 2);
14796 var isFunc = _.isFunction(method);
14797 return _.map(obj, function(value) {
14798 var func = isFunc ? method : value[method];
14799 return func == null ? func : func.apply(value, args);
14803 // Convenience version of a common use case of `map`: fetching a property.
14804 _.pluck = function(obj, key) {
14805 return _.map(obj, _.property(key));
14808 // Convenience version of a common use case of `filter`: selecting only objects
14809 // containing specific `key:value` pairs.
14810 _.where = function(obj, attrs) {
14811 return _.filter(obj, _.matcher(attrs));
14814 // Convenience version of a common use case of `find`: getting the first object
14815 // containing specific `key:value` pairs.
14816 _.findWhere = function(obj, attrs) {
14817 return _.find(obj, _.matcher(attrs));
14820 // Return the maximum element (or element-based computation).
14821 _.max = function(obj, iteratee, context) {
14822 var result = -Infinity, lastComputed = -Infinity,
14824 if (iteratee == null && obj != null) {
14825 obj = isArrayLike(obj) ? obj : _.values(obj);
14826 for (var i = 0, length = obj.length; i < length; i++) {
14828 if (value > result) {
14833 iteratee = cb(iteratee, context);
14834 _.each(obj, function(value, index, list) {
14835 computed = iteratee(value, index, list);
14836 if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
14838 lastComputed = computed;
14845 // Return the minimum element (or element-based computation).
14846 _.min = function(obj, iteratee, context) {
14847 var result = Infinity, lastComputed = Infinity,
14849 if (iteratee == null && obj != null) {
14850 obj = isArrayLike(obj) ? obj : _.values(obj);
14851 for (var i = 0, length = obj.length; i < length; i++) {
14853 if (value < result) {
14858 iteratee = cb(iteratee, context);
14859 _.each(obj, function(value, index, list) {
14860 computed = iteratee(value, index, list);
14861 if (computed < lastComputed || computed === Infinity && result === Infinity) {
14863 lastComputed = computed;
14870 // Shuffle a collection, using the modern version of the
14871 // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
14872 _.shuffle = function(obj) {
14873 var set = isArrayLike(obj) ? obj : _.values(obj);
14874 var length = set.length;
14875 var shuffled = Array(length);
14876 for (var index = 0, rand; index < length; index++) {
14877 rand = _.random(0, index);
14878 if (rand !== index) shuffled[index] = shuffled[rand];
14879 shuffled[rand] = set[index];
14884 // Sample **n** random values from a collection.
14885 // If **n** is not specified, returns a single random element.
14886 // The internal `guard` argument allows it to work with `map`.
14887 _.sample = function(obj, n, guard) {
14888 if (n == null || guard) {
14889 if (!isArrayLike(obj)) obj = _.values(obj);
14890 return obj[_.random(obj.length - 1)];
14892 return _.shuffle(obj).slice(0, Math.max(0, n));
14895 // Sort the object's values by a criterion produced by an iteratee.
14896 _.sortBy = function(obj, iteratee, context) {
14897 iteratee = cb(iteratee, context);
14898 return _.pluck(_.map(obj, function(value, index, list) {
14902 criteria: iteratee(value, index, list)
14904 }).sort(function(left, right) {
14905 var a = left.criteria;
14906 var b = right.criteria;
14908 if (a > b || a === void 0) return 1;
14909 if (a < b || b === void 0) return -1;
14911 return left.index - right.index;
14915 // An internal function used for aggregate "group by" operations.
14916 var group = function(behavior) {
14917 return function(obj, iteratee, context) {
14919 iteratee = cb(iteratee, context);
14920 _.each(obj, function(value, index) {
14921 var key = iteratee(value, index, obj);
14922 behavior(result, value, key);
14928 // Groups the object's values by a criterion. Pass either a string attribute
14929 // to group by, or a function that returns the criterion.
14930 _.groupBy = group(function(result, value, key) {
14931 if (_.has(result, key)) result[key].push(value); else result[key] = [value];
14934 // Indexes the object's values by a criterion, similar to `groupBy`, but for
14935 // when you know that your index values will be unique.
14936 _.indexBy = group(function(result, value, key) {
14937 result[key] = value;
14940 // Counts instances of an object that group by a certain criterion. Pass
14941 // either a string attribute to count by, or a function that returns the
14943 _.countBy = group(function(result, value, key) {
14944 if (_.has(result, key)) result[key]++; else result[key] = 1;
14947 // Safely create a real, live array from anything iterable.
14948 _.toArray = function(obj) {
14949 if (!obj) return [];
14950 if (_.isArray(obj)) return slice.call(obj);
14951 if (isArrayLike(obj)) return _.map(obj, _.identity);
14952 return _.values(obj);
14955 // Return the number of elements in an object.
14956 _.size = function(obj) {
14957 if (obj == null) return 0;
14958 return isArrayLike(obj) ? obj.length : _.keys(obj).length;
14961 // Split a collection into two arrays: one whose elements all satisfy the given
14962 // predicate, and one whose elements all do not satisfy the predicate.
14963 _.partition = function(obj, predicate, context) {
14964 predicate = cb(predicate, context);
14965 var pass = [], fail = [];
14966 _.each(obj, function(value, key, obj) {
14967 (predicate(value, key, obj) ? pass : fail).push(value);
14969 return [pass, fail];
14975 // Get the first element of an array. Passing **n** will return the first N
14976 // values in the array. Aliased as `head` and `take`. The **guard** check
14977 // allows it to work with `_.map`.
14978 _.first = _.head = _.take = function(array, n, guard) {
14979 if (array == null) return void 0;
14980 if (n == null || guard) return array[0];
14981 return _.initial(array, array.length - n);
14984 // Returns everything but the last entry of the array. Especially useful on
14985 // the arguments object. Passing **n** will return all the values in
14986 // the array, excluding the last N.
14987 _.initial = function(array, n, guard) {
14988 return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
14991 // Get the last element of an array. Passing **n** will return the last N
14992 // values in the array.
14993 _.last = function(array, n, guard) {
14994 if (array == null) return void 0;
14995 if (n == null || guard) return array[array.length - 1];
14996 return _.rest(array, Math.max(0, array.length - n));
14999 // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
15000 // Especially useful on the arguments object. Passing an **n** will return
15001 // the rest N values in the array.
15002 _.rest = _.tail = _.drop = function(array, n, guard) {
15003 return slice.call(array, n == null || guard ? 1 : n);
15006 // Trim out all falsy values from an array.
15007 _.compact = function(array) {
15008 return _.filter(array, _.identity);
15011 // Internal implementation of a recursive `flatten` function.
15012 var flatten = function(input, shallow, strict, startIndex) {
15013 var output = [], idx = 0;
15014 for (var i = startIndex || 0, length = getLength(input); i < length; i++) {
15015 var value = input[i];
15016 if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
15017 //flatten current level of array or arguments object
15018 if (!shallow) value = flatten(value, shallow, strict);
15019 var j = 0, len = value.length;
15020 output.length += len;
15022 output[idx++] = value[j++];
15024 } else if (!strict) {
15025 output[idx++] = value;
15031 // Flatten out an array, either recursively (by default), or just one level.
15032 _.flatten = function(array, shallow) {
15033 return flatten(array, shallow, false);
15036 // Return a version of the array that does not contain the specified value(s).
15037 _.without = function(array) {
15038 return _.difference(array, slice.call(arguments, 1));
15041 // Produce a duplicate-free version of the array. If the array has already
15042 // been sorted, you have the option of using a faster algorithm.
15043 // Aliased as `unique`.
15044 _.uniq = _.unique = function(array, isSorted, iteratee, context) {
15045 if (!_.isBoolean(isSorted)) {
15046 context = iteratee;
15047 iteratee = isSorted;
15050 if (iteratee != null) iteratee = cb(iteratee, context);
15053 for (var i = 0, length = getLength(array); i < length; i++) {
15054 var value = array[i],
15055 computed = iteratee ? iteratee(value, i, array) : value;
15057 if (!i || seen !== computed) result.push(value);
15059 } else if (iteratee) {
15060 if (!_.contains(seen, computed)) {
15061 seen.push(computed);
15062 result.push(value);
15064 } else if (!_.contains(result, value)) {
15065 result.push(value);
15071 // Produce an array that contains the union: each distinct element from all of
15072 // the passed-in arrays.
15073 _.union = function() {
15074 return _.uniq(flatten(arguments, true, true));
15077 // Produce an array that contains every item shared between all the
15078 // passed-in arrays.
15079 _.intersection = function(array) {
15081 var argsLength = arguments.length;
15082 for (var i = 0, length = getLength(array); i < length; i++) {
15083 var item = array[i];
15084 if (_.contains(result, item)) continue;
15085 for (var j = 1; j < argsLength; j++) {
15086 if (!_.contains(arguments[j], item)) break;
15088 if (j === argsLength) result.push(item);
15093 // Take the difference between one array and a number of other arrays.
15094 // Only the elements present in just the first array will remain.
15095 _.difference = function(array) {
15096 var rest = flatten(arguments, true, true, 1);
15097 return _.filter(array, function(value){
15098 return !_.contains(rest, value);
15102 // Zip together multiple lists into a single array -- elements that share
15103 // an index go together.
15104 _.zip = function() {
15105 return _.unzip(arguments);
15108 // Complement of _.zip. Unzip accepts an array of arrays and groups
15109 // each array's elements on shared indices
15110 _.unzip = function(array) {
15111 var length = array && _.max(array, getLength).length || 0;
15112 var result = Array(length);
15114 for (var index = 0; index < length; index++) {
15115 result[index] = _.pluck(array, index);
15120 // Converts lists into objects. Pass either a single array of `[key, value]`
15121 // pairs, or two parallel arrays of the same length -- one of keys, and one of
15122 // the corresponding values.
15123 _.object = function(list, values) {
15125 for (var i = 0, length = getLength(list); i < length; i++) {
15127 result[list[i]] = values[i];
15129 result[list[i][0]] = list[i][1];
15135 // Generator function to create the findIndex and findLastIndex functions
15136 function createPredicateIndexFinder(dir) {
15137 return function(array, predicate, context) {
15138 predicate = cb(predicate, context);
15139 var length = getLength(array);
15140 var index = dir > 0 ? 0 : length - 1;
15141 for (; index >= 0 && index < length; index += dir) {
15142 if (predicate(array[index], index, array)) return index;
15148 // Returns the first index on an array-like that passes a predicate test
15149 _.findIndex = createPredicateIndexFinder(1);
15150 _.findLastIndex = createPredicateIndexFinder(-1);
15152 // Use a comparator function to figure out the smallest index at which
15153 // an object should be inserted so as to maintain order. Uses binary search.
15154 _.sortedIndex = function(array, obj, iteratee, context) {
15155 iteratee = cb(iteratee, context, 1);
15156 var value = iteratee(obj);
15157 var low = 0, high = getLength(array);
15158 while (low < high) {
15159 var mid = Math.floor((low + high) / 2);
15160 if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
15165 // Generator function to create the indexOf and lastIndexOf functions
15166 function createIndexFinder(dir, predicateFind, sortedIndex) {
15167 return function(array, item, idx) {
15168 var i = 0, length = getLength(array);
15169 if (typeof idx == 'number') {
15171 i = idx >= 0 ? idx : Math.max(idx + length, i);
15173 length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
15175 } else if (sortedIndex && idx && length) {
15176 idx = sortedIndex(array, item);
15177 return array[idx] === item ? idx : -1;
15179 if (item !== item) {
15180 idx = predicateFind(slice.call(array, i, length), _.isNaN);
15181 return idx >= 0 ? idx + i : -1;
15183 for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
15184 if (array[idx] === item) return idx;
15190 // Return the position of the first occurrence of an item in an array,
15191 // or -1 if the item is not included in the array.
15192 // If the array is large and already in sort order, pass `true`
15193 // for **isSorted** to use binary search.
15194 _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
15195 _.lastIndexOf = createIndexFinder(-1, _.findLastIndex);
15197 // Generate an integer Array containing an arithmetic progression. A port of
15198 // the native Python `range()` function. See
15199 // [the Python documentation](http://docs.python.org/library/functions.html#range).
15200 _.range = function(start, stop, step) {
15201 if (stop == null) {
15207 var length = Math.max(Math.ceil((stop - start) / step), 0);
15208 var range = Array(length);
15210 for (var idx = 0; idx < length; idx++, start += step) {
15211 range[idx] = start;
15217 // Function (ahem) Functions
15218 // ------------------
15220 // Determines whether to execute a function as a constructor
15221 // or a normal function with the provided arguments
15222 var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {
15223 if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
15224 var self = baseCreate(sourceFunc.prototype);
15225 var result = sourceFunc.apply(self, args);
15226 if (_.isObject(result)) return result;
15230 // Create a function bound to a given object (assigning `this`, and arguments,
15231 // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
15233 _.bind = function(func, context) {
15234 if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
15235 if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
15236 var args = slice.call(arguments, 2);
15237 var bound = function() {
15238 return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));
15243 // Partially apply a function by creating a version that has had some of its
15244 // arguments pre-filled, without changing its dynamic `this` context. _ acts
15245 // as a placeholder, allowing any combination of arguments to be pre-filled.
15246 _.partial = function(func) {
15247 var boundArgs = slice.call(arguments, 1);
15248 var bound = function() {
15249 var position = 0, length = boundArgs.length;
15250 var args = Array(length);
15251 for (var i = 0; i < length; i++) {
15252 args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];
15254 while (position < arguments.length) args.push(arguments[position++]);
15255 return executeBound(func, bound, this, this, args);
15260 // Bind a number of an object's methods to that object. Remaining arguments
15261 // are the method names to be bound. Useful for ensuring that all callbacks
15262 // defined on an object belong to it.
15263 _.bindAll = function(obj) {
15264 var i, length = arguments.length, key;
15265 if (length <= 1) throw new Error('bindAll must be passed function names');
15266 for (i = 1; i < length; i++) {
15267 key = arguments[i];
15268 obj[key] = _.bind(obj[key], obj);
15273 // Memoize an expensive function by storing its results.
15274 _.memoize = function(func, hasher) {
15275 var memoize = function(key) {
15276 var cache = memoize.cache;
15277 var address = '' + (hasher ? hasher.apply(this, arguments) : key);
15278 if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
15279 return cache[address];
15281 memoize.cache = {};
15285 // Delays a function for the given number of milliseconds, and then calls
15286 // it with the arguments supplied.
15287 _.delay = function(func, wait) {
15288 var args = slice.call(arguments, 2);
15289 return setTimeout(function(){
15290 return func.apply(null, args);
15294 // Defers a function, scheduling it to run after the current call stack has
15296 _.defer = _.partial(_.delay, _, 1);
15298 // Returns a function, that, when invoked, will only be triggered at most once
15299 // during a given window of time. Normally, the throttled function will run
15300 // as much as it can, without ever going more than once per `wait` duration;
15301 // but if you'd like to disable the execution on the leading edge, pass
15302 // `{leading: false}`. To disable execution on the trailing edge, ditto.
15303 _.throttle = function(func, wait, options) {
15304 var context, args, result;
15305 var timeout = null;
15307 if (!options) options = {};
15308 var later = function() {
15309 previous = options.leading === false ? 0 : _.now();
15311 result = func.apply(context, args);
15312 if (!timeout) context = args = null;
15314 return function() {
15316 if (!previous && options.leading === false) previous = now;
15317 var remaining = wait - (now - previous);
15320 if (remaining <= 0 || remaining > wait) {
15322 clearTimeout(timeout);
15326 result = func.apply(context, args);
15327 if (!timeout) context = args = null;
15328 } else if (!timeout && options.trailing !== false) {
15329 timeout = setTimeout(later, remaining);
15335 // Returns a function, that, as long as it continues to be invoked, will not
15336 // be triggered. The function will be called after it stops being called for
15337 // N milliseconds. If `immediate` is passed, trigger the function on the
15338 // leading edge, instead of the trailing.
15339 _.debounce = function(func, wait, immediate) {
15340 var timeout, args, context, timestamp, result;
15342 var later = function() {
15343 var last = _.now() - timestamp;
15345 if (last < wait && last >= 0) {
15346 timeout = setTimeout(later, wait - last);
15350 result = func.apply(context, args);
15351 if (!timeout) context = args = null;
15356 return function() {
15359 timestamp = _.now();
15360 var callNow = immediate && !timeout;
15361 if (!timeout) timeout = setTimeout(later, wait);
15363 result = func.apply(context, args);
15364 context = args = null;
15371 // Returns the first function passed as an argument to the second,
15372 // allowing you to adjust arguments, run code before and after, and
15373 // conditionally execute the original function.
15374 _.wrap = function(func, wrapper) {
15375 return _.partial(wrapper, func);
15378 // Returns a negated version of the passed-in predicate.
15379 _.negate = function(predicate) {
15380 return function() {
15381 return !predicate.apply(this, arguments);
15385 // Returns a function that is the composition of a list of functions, each
15386 // consuming the return value of the function that follows.
15387 _.compose = function() {
15388 var args = arguments;
15389 var start = args.length - 1;
15390 return function() {
15392 var result = args[start].apply(this, arguments);
15393 while (i--) result = args[i].call(this, result);
15398 // Returns a function that will only be executed on and after the Nth call.
15399 _.after = function(times, func) {
15400 return function() {
15402 return func.apply(this, arguments);
15407 // Returns a function that will only be executed up to (but not including) the Nth call.
15408 _.before = function(times, func) {
15410 return function() {
15412 memo = func.apply(this, arguments);
15414 if (times <= 1) func = null;
15419 // Returns a function that will be executed at most one time, no matter how
15420 // often you call it. Useful for lazy initialization.
15421 _.once = _.partial(_.before, 2);
15423 // Object Functions
15424 // ----------------
15426 // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
15427 var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
15428 var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
15429 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
15431 function collectNonEnumProps(obj, keys) {
15432 var nonEnumIdx = nonEnumerableProps.length;
15433 var constructor = obj.constructor;
15434 var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto;
15436 // Constructor is a special case.
15437 var prop = 'constructor';
15438 if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);
15440 while (nonEnumIdx--) {
15441 prop = nonEnumerableProps[nonEnumIdx];
15442 if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
15448 // Retrieve the names of an object's own properties.
15449 // Delegates to **ECMAScript 5**'s native `Object.keys`
15450 _.keys = function(obj) {
15451 if (!_.isObject(obj)) return [];
15452 if (nativeKeys) return nativeKeys(obj);
15454 for (var key in obj) if (_.has(obj, key)) keys.push(key);
15456 if (hasEnumBug) collectNonEnumProps(obj, keys);
15460 // Retrieve all the property names of an object.
15461 _.allKeys = function(obj) {
15462 if (!_.isObject(obj)) return [];
15464 for (var key in obj) keys.push(key);
15466 if (hasEnumBug) collectNonEnumProps(obj, keys);
15470 // Retrieve the values of an object's properties.
15471 _.values = function(obj) {
15472 var keys = _.keys(obj);
15473 var length = keys.length;
15474 var values = Array(length);
15475 for (var i = 0; i < length; i++) {
15476 values[i] = obj[keys[i]];
15481 // Returns the results of applying the iteratee to each element of the object
15482 // In contrast to _.map it returns an object
15483 _.mapObject = function(obj, iteratee, context) {
15484 iteratee = cb(iteratee, context);
15485 var keys = _.keys(obj),
15486 length = keys.length,
15489 for (var index = 0; index < length; index++) {
15490 currentKey = keys[index];
15491 results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
15496 // Convert an object into a list of `[key, value]` pairs.
15497 _.pairs = function(obj) {
15498 var keys = _.keys(obj);
15499 var length = keys.length;
15500 var pairs = Array(length);
15501 for (var i = 0; i < length; i++) {
15502 pairs[i] = [keys[i], obj[keys[i]]];
15507 // Invert the keys and values of an object. The values must be serializable.
15508 _.invert = function(obj) {
15510 var keys = _.keys(obj);
15511 for (var i = 0, length = keys.length; i < length; i++) {
15512 result[obj[keys[i]]] = keys[i];
15517 // Return a sorted list of the function names available on the object.
15518 // Aliased as `methods`
15519 _.functions = _.methods = function(obj) {
15521 for (var key in obj) {
15522 if (_.isFunction(obj[key])) names.push(key);
15524 return names.sort();
15527 // Extend a given object with all the properties in passed-in object(s).
15528 _.extend = createAssigner(_.allKeys);
15530 // Assigns a given object with all the own properties in the passed-in object(s)
15531 // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
15532 _.extendOwn = _.assign = createAssigner(_.keys);
15534 // Returns the first key on an object that passes a predicate test
15535 _.findKey = function(obj, predicate, context) {
15536 predicate = cb(predicate, context);
15537 var keys = _.keys(obj), key;
15538 for (var i = 0, length = keys.length; i < length; i++) {
15540 if (predicate(obj[key], key, obj)) return key;
15544 // Return a copy of the object only containing the whitelisted properties.
15545 _.pick = function(object, oiteratee, context) {
15546 var result = {}, obj = object, iteratee, keys;
15547 if (obj == null) return result;
15548 if (_.isFunction(oiteratee)) {
15549 keys = _.allKeys(obj);
15550 iteratee = optimizeCb(oiteratee, context);
15552 keys = flatten(arguments, false, false, 1);
15553 iteratee = function(value, key, obj) { return key in obj; };
15556 for (var i = 0, length = keys.length; i < length; i++) {
15558 var value = obj[key];
15559 if (iteratee(value, key, obj)) result[key] = value;
15564 // Return a copy of the object without the blacklisted properties.
15565 _.omit = function(obj, iteratee, context) {
15566 if (_.isFunction(iteratee)) {
15567 iteratee = _.negate(iteratee);
15569 var keys = _.map(flatten(arguments, false, false, 1), String);
15570 iteratee = function(value, key) {
15571 return !_.contains(keys, key);
15574 return _.pick(obj, iteratee, context);
15577 // Fill in a given object with default properties.
15578 _.defaults = createAssigner(_.allKeys, true);
15580 // Creates an object that inherits from the given prototype object.
15581 // If additional properties are provided then they will be added to the
15583 _.create = function(prototype, props) {
15584 var result = baseCreate(prototype);
15585 if (props) _.extendOwn(result, props);
15589 // Create a (shallow-cloned) duplicate of an object.
15590 _.clone = function(obj) {
15591 if (!_.isObject(obj)) return obj;
15592 return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
15595 // Invokes interceptor with the obj, and then returns obj.
15596 // The primary purpose of this method is to "tap into" a method chain, in
15597 // order to perform operations on intermediate results within the chain.
15598 _.tap = function(obj, interceptor) {
15603 // Returns whether an object has a given set of `key:value` pairs.
15604 _.isMatch = function(object, attrs) {
15605 var keys = _.keys(attrs), length = keys.length;
15606 if (object == null) return !length;
15607 var obj = Object(object);
15608 for (var i = 0; i < length; i++) {
15610 if (attrs[key] !== obj[key] || !(key in obj)) return false;
15616 // Internal recursive comparison function for `isEqual`.
15617 var eq = function(a, b, aStack, bStack) {
15618 // Identical objects are equal. `0 === -0`, but they aren't identical.
15619 // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
15620 if (a === b) return a !== 0 || 1 / a === 1 / b;
15621 // A strict comparison is necessary because `null == undefined`.
15622 if (a == null || b == null) return a === b;
15623 // Unwrap any wrapped objects.
15624 if (a instanceof _) a = a._wrapped;
15625 if (b instanceof _) b = b._wrapped;
15626 // Compare `[[Class]]` names.
15627 var className = toString.call(a);
15628 if (className !== toString.call(b)) return false;
15629 switch (className) {
15630 // Strings, numbers, regular expressions, dates, and booleans are compared by value.
15631 case '[object RegExp]':
15632 // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
15633 case '[object String]':
15634 // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
15635 // equivalent to `new String("5")`.
15636 return '' + a === '' + b;
15637 case '[object Number]':
15638 // `NaN`s are equivalent, but non-reflexive.
15639 // Object(NaN) is equivalent to NaN
15640 if (+a !== +a) return +b !== +b;
15641 // An `egal` comparison is performed for other numeric values.
15642 return +a === 0 ? 1 / +a === 1 / b : +a === +b;
15643 case '[object Date]':
15644 case '[object Boolean]':
15645 // Coerce dates and booleans to numeric primitive values. Dates are compared by their
15646 // millisecond representations. Note that invalid dates with millisecond representations
15647 // of `NaN` are not equivalent.
15651 var areArrays = className === '[object Array]';
15653 if (typeof a != 'object' || typeof b != 'object') return false;
15655 // Objects with different constructors are not equivalent, but `Object`s or `Array`s
15656 // from different frames are.
15657 var aCtor = a.constructor, bCtor = b.constructor;
15658 if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
15659 _.isFunction(bCtor) && bCtor instanceof bCtor)
15660 && ('constructor' in a && 'constructor' in b)) {
15664 // Assume equality for cyclic structures. The algorithm for detecting cyclic
15665 // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
15667 // Initializing stack of traversed objects.
15668 // It's done here since we only need them for objects and arrays comparison.
15669 aStack = aStack || [];
15670 bStack = bStack || [];
15671 var length = aStack.length;
15673 // Linear search. Performance is inversely proportional to the number of
15674 // unique nested structures.
15675 if (aStack[length] === a) return bStack[length] === b;
15678 // Add the first object to the stack of traversed objects.
15682 // Recursively compare objects and arrays.
15684 // Compare array lengths to determine if a deep comparison is necessary.
15686 if (length !== b.length) return false;
15687 // Deep compare the contents, ignoring non-numeric properties.
15689 if (!eq(a[length], b[length], aStack, bStack)) return false;
15692 // Deep compare objects.
15693 var keys = _.keys(a), key;
15694 length = keys.length;
15695 // Ensure that both objects contain the same number of properties before comparing deep equality.
15696 if (_.keys(b).length !== length) return false;
15698 // Deep compare each member
15699 key = keys[length];
15700 if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
15703 // Remove the first object from the stack of traversed objects.
15709 // Perform a deep comparison to check if two objects are equal.
15710 _.isEqual = function(a, b) {
15714 // Is a given array, string, or object empty?
15715 // An "empty" object has no enumerable own-properties.
15716 _.isEmpty = function(obj) {
15717 if (obj == null) return true;
15718 if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
15719 return _.keys(obj).length === 0;
15722 // Is a given value a DOM element?
15723 _.isElement = function(obj) {
15724 return !!(obj && obj.nodeType === 1);
15727 // Is a given value an array?
15728 // Delegates to ECMA5's native Array.isArray
15729 _.isArray = nativeIsArray || function(obj) {
15730 return toString.call(obj) === '[object Array]';
15733 // Is a given variable an object?
15734 _.isObject = function(obj) {
15735 var type = typeof obj;
15736 return type === 'function' || type === 'object' && !!obj;
15739 // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.
15740 _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) {
15741 _['is' + name] = function(obj) {
15742 return toString.call(obj) === '[object ' + name + ']';
15746 // Define a fallback version of the method in browsers (ahem, IE < 9), where
15747 // there isn't any inspectable "Arguments" type.
15748 if (!_.isArguments(arguments)) {
15749 _.isArguments = function(obj) {
15750 return _.has(obj, 'callee');
15754 // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
15755 // IE 11 (#1621), and in Safari 8 (#1929).
15756 if (typeof /./ != 'function' && typeof Int8Array != 'object') {
15757 _.isFunction = function(obj) {
15758 return typeof obj == 'function' || false;
15762 // Is a given object a finite number?
15763 _.isFinite = function(obj) {
15764 return isFinite(obj) && !isNaN(parseFloat(obj));
15767 // Is the given value `NaN`? (NaN is the only number which does not equal itself).
15768 _.isNaN = function(obj) {
15769 return _.isNumber(obj) && obj !== +obj;
15772 // Is a given value a boolean?
15773 _.isBoolean = function(obj) {
15774 return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
15777 // Is a given value equal to null?
15778 _.isNull = function(obj) {
15779 return obj === null;
15782 // Is a given variable undefined?
15783 _.isUndefined = function(obj) {
15784 return obj === void 0;
15787 // Shortcut function for checking if an object has a given property directly
15788 // on itself (in other words, not on a prototype).
15789 _.has = function(obj, key) {
15790 return obj != null && hasOwnProperty.call(obj, key);
15793 // Utility Functions
15794 // -----------------
15796 // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
15797 // previous owner. Returns a reference to the Underscore object.
15798 _.noConflict = function() {
15799 root._ = previousUnderscore;
15803 // Keep the identity function around for default iteratees.
15804 _.identity = function(value) {
15808 // Predicate-generating functions. Often useful outside of Underscore.
15809 _.constant = function(value) {
15810 return function() {
15815 _.noop = function(){};
15817 _.property = property;
15819 // Generates a function for a given object that returns a given property.
15820 _.propertyOf = function(obj) {
15821 return obj == null ? function(){} : function(key) {
15826 // Returns a predicate for checking whether an object has a given set of
15827 // `key:value` pairs.
15828 _.matcher = _.matches = function(attrs) {
15829 attrs = _.extendOwn({}, attrs);
15830 return function(obj) {
15831 return _.isMatch(obj, attrs);
15835 // Run a function **n** times.
15836 _.times = function(n, iteratee, context) {
15837 var accum = Array(Math.max(0, n));
15838 iteratee = optimizeCb(iteratee, context, 1);
15839 for (var i = 0; i < n; i++) accum[i] = iteratee(i);
15843 // Return a random integer between min and max (inclusive).
15844 _.random = function(min, max) {
15849 return min + Math.floor(Math.random() * (max - min + 1));
15852 // A (possibly faster) way to get the current timestamp as an integer.
15853 _.now = Date.now || function() {
15854 return new Date().getTime();
15857 // List of HTML entities for escaping.
15866 var unescapeMap = _.invert(escapeMap);
15868 // Functions for escaping and unescaping strings to/from HTML interpolation.
15869 var createEscaper = function(map) {
15870 var escaper = function(match) {
15873 // Regexes for identifying a key that needs to be escaped
15874 var source = '(?:' + _.keys(map).join('|') + ')';
15875 var testRegexp = RegExp(source);
15876 var replaceRegexp = RegExp(source, 'g');
15877 return function(string) {
15878 string = string == null ? '' : '' + string;
15879 return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
15882 _.escape = createEscaper(escapeMap);
15883 _.unescape = createEscaper(unescapeMap);
15885 // If the value of the named `property` is a function then invoke it with the
15886 // `object` as context; otherwise, return it.
15887 _.result = function(object, property, fallback) {
15888 var value = object == null ? void 0 : object[property];
15889 if (value === void 0) {
15892 return _.isFunction(value) ? value.call(object) : value;
15895 // Generate a unique integer id (unique within the entire client session).
15896 // Useful for temporary DOM ids.
15898 _.uniqueId = function(prefix) {
15899 var id = ++idCounter + '';
15900 return prefix ? prefix + id : id;
15903 // By default, Underscore uses ERB-style template delimiters, change the
15904 // following template settings to use alternative delimiters.
15905 _.templateSettings = {
15906 evaluate : /<%([\s\S]+?)%>/g,
15907 interpolate : /<%=([\s\S]+?)%>/g,
15908 escape : /<%-([\s\S]+?)%>/g
15911 // When customizing `templateSettings`, if you don't want to define an
15912 // interpolation, evaluation or escaping regex, we need one that is
15913 // guaranteed not to match.
15914 var noMatch = /(.)^/;
15916 // Certain characters need to be escaped so that they can be put into a
15927 var escaper = /\\|'|\r|\n|\u2028|\u2029/g;
15929 var escapeChar = function(match) {
15930 return '\\' + escapes[match];
15933 // JavaScript micro-templating, similar to John Resig's implementation.
15934 // Underscore templating handles arbitrary delimiters, preserves whitespace,
15935 // and correctly escapes quotes within interpolated code.
15936 // NB: `oldSettings` only exists for backwards compatibility.
15937 _.template = function(text, settings, oldSettings) {
15938 if (!settings && oldSettings) settings = oldSettings;
15939 settings = _.defaults({}, settings, _.templateSettings);
15941 // Combine delimiters into one regular expression via alternation.
15942 var matcher = RegExp([
15943 (settings.escape || noMatch).source,
15944 (settings.interpolate || noMatch).source,
15945 (settings.evaluate || noMatch).source
15946 ].join('|') + '|$', 'g');
15948 // Compile the template source, escaping string literals appropriately.
15950 var source = "__p+='";
15951 text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
15952 source += text.slice(index, offset).replace(escaper, escapeChar);
15953 index = offset + match.length;
15956 source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
15957 } else if (interpolate) {
15958 source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
15959 } else if (evaluate) {
15960 source += "';\n" + evaluate + "\n__p+='";
15963 // Adobe VMs need the match returned to produce the correct offest.
15968 // If a variable is not specified, place data values in local scope.
15969 if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
15971 source = "var __t,__p='',__j=Array.prototype.join," +
15972 "print=function(){__p+=__j.call(arguments,'');};\n" +
15973 source + 'return __p;\n';
15976 var render = new Function(settings.variable || 'obj', '_', source);
15982 var template = function(data) {
15983 return render.call(this, data, _);
15986 // Provide the compiled source as a convenience for precompilation.
15987 var argument = settings.variable || 'obj';
15988 template.source = 'function(' + argument + '){\n' + source + '}';
15993 // Add a "chain" function. Start chaining a wrapped Underscore object.
15994 _.chain = function(obj) {
15995 var instance = _(obj);
15996 instance._chain = true;
16002 // If Underscore is called as a function, it returns a wrapped object that
16003 // can be used OO-style. This wrapper holds altered versions of all the
16004 // underscore functions. Wrapped objects may be chained.
16006 // Helper function to continue chaining intermediate results.
16007 var result = function(instance, obj) {
16008 return instance._chain ? _(obj).chain() : obj;
16011 // Add your own custom functions to the Underscore object.
16012 _.mixin = function(obj) {
16013 _.each(_.functions(obj), function(name) {
16014 var func = _[name] = obj[name];
16015 _.prototype[name] = function() {
16016 var args = [this._wrapped];
16017 push.apply(args, arguments);
16018 return result(this, func.apply(_, args));
16023 // Add all of the Underscore functions to the wrapper object.
16026 // Add all mutator Array functions to the wrapper.
16027 _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
16028 var method = ArrayProto[name];
16029 _.prototype[name] = function() {
16030 var obj = this._wrapped;
16031 method.apply(obj, arguments);
16032 if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
16033 return result(this, obj);
16037 // Add all accessor Array functions to the wrapper.
16038 _.each(['concat', 'join', 'slice'], function(name) {
16039 var method = ArrayProto[name];
16040 _.prototype[name] = function() {
16041 return result(this, method.apply(this._wrapped, arguments));
16045 // Extracts the result from a wrapped and chained object.
16046 _.prototype.value = function() {
16047 return this._wrapped;
16050 // Provide unwrapping proxy for some methods used in engine operations
16051 // such as arithmetic and JSON stringification.
16052 _.prototype.valueOf = _.prototype.toJSON = _.prototype.value;
16054 _.prototype.toString = function() {
16055 return '' + this._wrapped;
16058 // AMD registration happens at the end for compatibility with AMD loaders
16059 // that may not enforce next-turn semantics on modules. Even though general
16060 // practice for AMD registration is to be anonymous, underscore registers
16061 // as a named module because, like jQuery, it is a base library that is
16062 // popular enough to be bundled in a third party lib, but not be part of
16063 // an AMD load request. Those cases could generate an error when an
16064 // anonymous define() is called outside of a loader request.
16065 if (typeof define === 'function' && define.amd) {
16066 define('underscore', [], function() {
16072 },{}],179:[function(require,module,exports){
16073 var createElement = require("./vdom/create-element.js")
16075 module.exports = createElement
16077 },{"./vdom/create-element.js":185}],180:[function(require,module,exports){
16078 var diff = require("./vtree/diff.js")
16080 module.exports = diff
16082 },{"./vtree/diff.js":205}],181:[function(require,module,exports){
16083 var h = require("./virtual-hyperscript/index.js")
16087 },{"./virtual-hyperscript/index.js":192}],182:[function(require,module,exports){
16088 var diff = require("./diff.js")
16089 var patch = require("./patch.js")
16090 var h = require("./h.js")
16091 var create = require("./create-element.js")
16092 var VNode = require('./vnode/vnode.js')
16093 var VText = require('./vnode/vtext.js')
16104 },{"./create-element.js":179,"./diff.js":180,"./h.js":181,"./patch.js":183,"./vnode/vnode.js":201,"./vnode/vtext.js":203}],183:[function(require,module,exports){
16105 var patch = require("./vdom/patch.js")
16107 module.exports = patch
16109 },{"./vdom/patch.js":188}],184:[function(require,module,exports){
16110 var isObject = require("is-object")
16111 var isHook = require("../vnode/is-vhook.js")
16113 module.exports = applyProperties
16115 function applyProperties(node, props, previous) {
16116 for (var propName in props) {
16117 var propValue = props[propName]
16119 if (propValue === undefined) {
16120 removeProperty(node, propName, propValue, previous);
16121 } else if (isHook(propValue)) {
16122 removeProperty(node, propName, propValue, previous)
16123 if (propValue.hook) {
16124 propValue.hook(node,
16126 previous ? previous[propName] : undefined)
16129 if (isObject(propValue)) {
16130 patchObject(node, props, previous, propName, propValue);
16132 node[propName] = propValue
16138 function removeProperty(node, propName, propValue, previous) {
16140 var previousValue = previous[propName]
16142 if (!isHook(previousValue)) {
16143 if (propName === "attributes") {
16144 for (var attrName in previousValue) {
16145 node.removeAttribute(attrName)
16147 } else if (propName === "style") {
16148 for (var i in previousValue) {
16151 } else if (typeof previousValue === "string") {
16152 node[propName] = ""
16154 node[propName] = null
16156 } else if (previousValue.unhook) {
16157 previousValue.unhook(node, propName, propValue)
16162 function patchObject(node, props, previous, propName, propValue) {
16163 var previousValue = previous ? previous[propName] : undefined
16166 if (propName === "attributes") {
16167 for (var attrName in propValue) {
16168 var attrValue = propValue[attrName]
16170 if (attrValue === undefined) {
16171 node.removeAttribute(attrName)
16173 node.setAttribute(attrName, attrValue)
16180 if(previousValue && isObject(previousValue) &&
16181 getPrototype(previousValue) !== getPrototype(propValue)) {
16182 node[propName] = propValue
16186 if (!isObject(node[propName])) {
16187 node[propName] = {}
16190 var replacer = propName === "style" ? "" : undefined
16192 for (var k in propValue) {
16193 var value = propValue[k]
16194 node[propName][k] = (value === undefined) ? replacer : value
16198 function getPrototype(value) {
16199 if (Object.getPrototypeOf) {
16200 return Object.getPrototypeOf(value)
16201 } else if (value.__proto__) {
16202 return value.__proto__
16203 } else if (value.constructor) {
16204 return value.constructor.prototype
16208 },{"../vnode/is-vhook.js":196,"is-object":20}],185:[function(require,module,exports){
16209 var document = require("global/document")
16211 var applyProperties = require("./apply-properties")
16213 var isVNode = require("../vnode/is-vnode.js")
16214 var isVText = require("../vnode/is-vtext.js")
16215 var isWidget = require("../vnode/is-widget.js")
16216 var handleThunk = require("../vnode/handle-thunk.js")
16218 module.exports = createElement
16220 function createElement(vnode, opts) {
16221 var doc = opts ? opts.document || document : document
16222 var warn = opts ? opts.warn : null
16224 vnode = handleThunk(vnode).a
16226 if (isWidget(vnode)) {
16227 return vnode.init()
16228 } else if (isVText(vnode)) {
16229 return doc.createTextNode(vnode.text)
16230 } else if (!isVNode(vnode)) {
16232 warn("Item is not a valid virtual dom node", vnode)
16237 var node = (vnode.namespace === null) ?
16238 doc.createElement(vnode.tagName) :
16239 doc.createElementNS(vnode.namespace, vnode.tagName)
16241 var props = vnode.properties
16242 applyProperties(node, props)
16244 var children = vnode.children
16246 for (var i = 0; i < children.length; i++) {
16247 var childNode = createElement(children[i], opts)
16249 node.appendChild(childNode)
16256 },{"../vnode/handle-thunk.js":194,"../vnode/is-vnode.js":197,"../vnode/is-vtext.js":198,"../vnode/is-widget.js":199,"./apply-properties":184,"global/document":16}],186:[function(require,module,exports){
16257 // Maps a virtual DOM tree onto a real DOM tree in an efficient manner.
16258 // We don't want to read all of the DOM nodes in the tree so we use
16259 // the in-order tree indexing to eliminate recursion down certain branches.
16260 // We only recurse into a DOM node if we know that it contains a child of
16265 module.exports = domIndex
16267 function domIndex(rootNode, tree, indices, nodes) {
16268 if (!indices || indices.length === 0) {
16271 indices.sort(ascending)
16272 return recurse(rootNode, tree, indices, nodes, 0)
16276 function recurse(rootNode, tree, indices, nodes, rootIndex) {
16277 nodes = nodes || {}
16281 if (indexInRange(indices, rootIndex, rootIndex)) {
16282 nodes[rootIndex] = rootNode
16285 var vChildren = tree.children
16289 var childNodes = rootNode.childNodes
16291 for (var i = 0; i < tree.children.length; i++) {
16294 var vChild = vChildren[i] || noChild
16295 var nextIndex = rootIndex + (vChild.count || 0)
16297 // skip recursion down the tree if there are no nodes down here
16298 if (indexInRange(indices, rootIndex, nextIndex)) {
16299 recurse(childNodes[i], vChild, indices, nodes, rootIndex)
16302 rootIndex = nextIndex
16310 // Binary search for an index in the interval [left, right]
16311 function indexInRange(indices, left, right) {
16312 if (indices.length === 0) {
16317 var maxIndex = indices.length - 1
16321 while (minIndex <= maxIndex) {
16322 currentIndex = ((maxIndex + minIndex) / 2) >> 0
16323 currentItem = indices[currentIndex]
16325 if (minIndex === maxIndex) {
16326 return currentItem >= left && currentItem <= right
16327 } else if (currentItem < left) {
16328 minIndex = currentIndex + 1
16329 } else if (currentItem > right) {
16330 maxIndex = currentIndex - 1
16339 function ascending(a, b) {
16340 return a > b ? 1 : -1
16343 },{}],187:[function(require,module,exports){
16344 var applyProperties = require("./apply-properties")
16346 var isWidget = require("../vnode/is-widget.js")
16347 var VPatch = require("../vnode/vpatch.js")
16349 var updateWidget = require("./update-widget")
16351 module.exports = applyPatch
16353 function applyPatch(vpatch, domNode, renderOptions) {
16354 var type = vpatch.type
16355 var vNode = vpatch.vNode
16356 var patch = vpatch.patch
16359 case VPatch.REMOVE:
16360 return removeNode(domNode, vNode)
16361 case VPatch.INSERT:
16362 return insertNode(domNode, patch, renderOptions)
16364 return stringPatch(domNode, vNode, patch, renderOptions)
16365 case VPatch.WIDGET:
16366 return widgetPatch(domNode, vNode, patch, renderOptions)
16368 return vNodePatch(domNode, vNode, patch, renderOptions)
16370 reorderChildren(domNode, patch)
16373 applyProperties(domNode, patch, vNode.properties)
16376 return replaceRoot(domNode,
16377 renderOptions.patch(domNode, patch, renderOptions))
16383 function removeNode(domNode, vNode) {
16384 var parentNode = domNode.parentNode
16387 parentNode.removeChild(domNode)
16390 destroyWidget(domNode, vNode);
16395 function insertNode(parentNode, vNode, renderOptions) {
16396 var newNode = renderOptions.render(vNode, renderOptions)
16399 parentNode.appendChild(newNode)
16405 function stringPatch(domNode, leftVNode, vText, renderOptions) {
16408 if (domNode.nodeType === 3) {
16409 domNode.replaceData(0, domNode.length, vText.text)
16412 var parentNode = domNode.parentNode
16413 newNode = renderOptions.render(vText, renderOptions)
16415 if (parentNode && newNode !== domNode) {
16416 parentNode.replaceChild(newNode, domNode)
16423 function widgetPatch(domNode, leftVNode, widget, renderOptions) {
16424 var updating = updateWidget(leftVNode, widget)
16428 newNode = widget.update(leftVNode, domNode) || domNode
16430 newNode = renderOptions.render(widget, renderOptions)
16433 var parentNode = domNode.parentNode
16435 if (parentNode && newNode !== domNode) {
16436 parentNode.replaceChild(newNode, domNode)
16440 destroyWidget(domNode, leftVNode)
16446 function vNodePatch(domNode, leftVNode, vNode, renderOptions) {
16447 var parentNode = domNode.parentNode
16448 var newNode = renderOptions.render(vNode, renderOptions)
16450 if (parentNode && newNode !== domNode) {
16451 parentNode.replaceChild(newNode, domNode)
16457 function destroyWidget(domNode, w) {
16458 if (typeof w.destroy === "function" && isWidget(w)) {
16463 function reorderChildren(domNode, moves) {
16464 var childNodes = domNode.childNodes
16470 for (var i = 0; i < moves.removes.length; i++) {
16471 remove = moves.removes[i]
16472 node = childNodes[remove.from]
16474 keyMap[remove.key] = node
16476 domNode.removeChild(node)
16479 var length = childNodes.length
16480 for (var j = 0; j < moves.inserts.length; j++) {
16481 insert = moves.inserts[j]
16482 node = keyMap[insert.key]
16483 // this is the weirdest bug i've ever seen in webkit
16484 domNode.insertBefore(node, insert.to >= length++ ? null : childNodes[insert.to])
16488 function replaceRoot(oldRoot, newRoot) {
16489 if (oldRoot && newRoot && oldRoot !== newRoot && oldRoot.parentNode) {
16490 oldRoot.parentNode.replaceChild(newRoot, oldRoot)
16496 },{"../vnode/is-widget.js":199,"../vnode/vpatch.js":202,"./apply-properties":184,"./update-widget":189}],188:[function(require,module,exports){
16497 var document = require("global/document")
16498 var isArray = require("x-is-array")
16500 var render = require("./create-element")
16501 var domIndex = require("./dom-index")
16502 var patchOp = require("./patch-op")
16503 module.exports = patch
16505 function patch(rootNode, patches, renderOptions) {
16506 renderOptions = renderOptions || {}
16507 renderOptions.patch = renderOptions.patch && renderOptions.patch !== patch
16508 ? renderOptions.patch
16510 renderOptions.render = renderOptions.render || render
16512 return renderOptions.patch(rootNode, patches, renderOptions)
16515 function patchRecursive(rootNode, patches, renderOptions) {
16516 var indices = patchIndices(patches)
16518 if (indices.length === 0) {
16522 var index = domIndex(rootNode, patches.a, indices)
16523 var ownerDocument = rootNode.ownerDocument
16525 if (!renderOptions.document && ownerDocument !== document) {
16526 renderOptions.document = ownerDocument
16529 for (var i = 0; i < indices.length; i++) {
16530 var nodeIndex = indices[i]
16531 rootNode = applyPatch(rootNode,
16533 patches[nodeIndex],
16540 function applyPatch(rootNode, domNode, patchList, renderOptions) {
16547 if (isArray(patchList)) {
16548 for (var i = 0; i < patchList.length; i++) {
16549 newNode = patchOp(patchList[i], domNode, renderOptions)
16551 if (domNode === rootNode) {
16556 newNode = patchOp(patchList, domNode, renderOptions)
16558 if (domNode === rootNode) {
16566 function patchIndices(patches) {
16569 for (var key in patches) {
16571 indices.push(Number(key))
16578 },{"./create-element":185,"./dom-index":186,"./patch-op":187,"global/document":16,"x-is-array":224}],189:[function(require,module,exports){
16579 var isWidget = require("../vnode/is-widget.js")
16581 module.exports = updateWidget
16583 function updateWidget(a, b) {
16584 if (isWidget(a) && isWidget(b)) {
16585 if ("name" in a && "name" in b) {
16586 return a.id === b.id
16588 return a.init === b.init
16595 },{"../vnode/is-widget.js":199}],190:[function(require,module,exports){
16598 var EvStore = require('ev-store');
16600 module.exports = EvHook;
16602 function EvHook(value) {
16603 if (!(this instanceof EvHook)) {
16604 return new EvHook(value);
16607 this.value = value;
16610 EvHook.prototype.hook = function (node, propertyName) {
16611 var es = EvStore(node);
16612 var propName = propertyName.substr(3);
16614 es[propName] = this.value;
16617 EvHook.prototype.unhook = function(node, propertyName) {
16618 var es = EvStore(node);
16619 var propName = propertyName.substr(3);
16621 es[propName] = undefined;
16624 },{"ev-store":9}],191:[function(require,module,exports){
16627 module.exports = SoftSetHook;
16629 function SoftSetHook(value) {
16630 if (!(this instanceof SoftSetHook)) {
16631 return new SoftSetHook(value);
16634 this.value = value;
16637 SoftSetHook.prototype.hook = function (node, propertyName) {
16638 if (node[propertyName] !== this.value) {
16639 node[propertyName] = this.value;
16643 },{}],192:[function(require,module,exports){
16646 var isArray = require('x-is-array');
16648 var VNode = require('../vnode/vnode.js');
16649 var VText = require('../vnode/vtext.js');
16650 var isVNode = require('../vnode/is-vnode');
16651 var isVText = require('../vnode/is-vtext');
16652 var isWidget = require('../vnode/is-widget');
16653 var isHook = require('../vnode/is-vhook');
16654 var isVThunk = require('../vnode/is-thunk');
16656 var parseTag = require('./parse-tag.js');
16657 var softSetHook = require('./hooks/soft-set-hook.js');
16658 var evHook = require('./hooks/ev-hook.js');
16660 module.exports = h;
16662 function h(tagName, properties, children) {
16663 var childNodes = [];
16664 var tag, props, key, namespace;
16666 if (!children && isChildren(properties)) {
16667 children = properties;
16671 props = props || properties || {};
16672 tag = parseTag(tagName, props);
16675 if (props.hasOwnProperty('key')) {
16677 props.key = undefined;
16680 // support namespace
16681 if (props.hasOwnProperty('namespace')) {
16682 namespace = props.namespace;
16683 props.namespace = undefined;
16687 if (tag === 'INPUT' &&
16689 props.hasOwnProperty('value') &&
16690 props.value !== undefined &&
16691 !isHook(props.value)
16693 props.value = softSetHook(props.value);
16696 transformProperties(props);
16698 if (children !== undefined && children !== null) {
16699 addChild(children, childNodes, tag, props);
16703 return new VNode(tag, props, childNodes, key, namespace);
16706 function addChild(c, childNodes, tag, props) {
16707 if (typeof c === 'string') {
16708 childNodes.push(new VText(c));
16709 } else if (typeof c === 'number') {
16710 childNodes.push(new VText(String(c)));
16711 } else if (isChild(c)) {
16712 childNodes.push(c);
16713 } else if (isArray(c)) {
16714 for (var i = 0; i < c.length; i++) {
16715 addChild(c[i], childNodes, tag, props);
16717 } else if (c === null || c === undefined) {
16720 throw UnexpectedVirtualElement({
16730 function transformProperties(props) {
16731 for (var propName in props) {
16732 if (props.hasOwnProperty(propName)) {
16733 var value = props[propName];
16735 if (isHook(value)) {
16739 if (propName.substr(0, 3) === 'ev-') {
16740 // add ev-foo support
16741 props[propName] = evHook(value);
16747 function isChild(x) {
16748 return isVNode(x) || isVText(x) || isWidget(x) || isVThunk(x);
16751 function isChildren(x) {
16752 return typeof x === 'string' || isArray(x) || isChild(x);
16755 function UnexpectedVirtualElement(data) {
16756 var err = new Error();
16758 err.type = 'virtual-hyperscript.unexpected.virtual-element';
16759 err.message = 'Unexpected virtual child passed to h().\n' +
16760 'Expected a VNode / Vthunk / VWidget / string but:\n' +
16762 errorString(data.foreignObject) +
16764 'The parent vnode is:\n' +
16765 errorString(data.parentVnode)
16767 'Suggested fix: change your `h(..., [ ... ])` callsite.';
16768 err.foreignObject = data.foreignObject;
16769 err.parentVnode = data.parentVnode;
16774 function errorString(obj) {
16776 return JSON.stringify(obj, null, ' ');
16778 return String(obj);
16782 },{"../vnode/is-thunk":195,"../vnode/is-vhook":196,"../vnode/is-vnode":197,"../vnode/is-vtext":198,"../vnode/is-widget":199,"../vnode/vnode.js":201,"../vnode/vtext.js":203,"./hooks/ev-hook.js":190,"./hooks/soft-set-hook.js":191,"./parse-tag.js":193,"x-is-array":224}],193:[function(require,module,exports){
16785 var split = require('browser-split');
16787 var classIdSplit = /([\.#]?[a-zA-Z0-9\u007F-\uFFFF_:-]+)/;
16788 var notClassId = /^\.|#/;
16790 module.exports = parseTag;
16792 function parseTag(tag, props) {
16797 var noId = !(props.hasOwnProperty('id'));
16799 var tagParts = split(tag, classIdSplit);
16800 var tagName = null;
16802 if (notClassId.test(tagParts[1])) {
16806 var classes, part, type, i;
16808 for (i = 0; i < tagParts.length; i++) {
16809 part = tagParts[i];
16815 type = part.charAt(0);
16819 } else if (type === '.') {
16820 classes = classes || [];
16821 classes.push(part.substring(1, part.length));
16822 } else if (type === '#' && noId) {
16823 props.id = part.substring(1, part.length);
16828 if (props.className) {
16829 classes.push(props.className);
16832 props.className = classes.join(' ');
16835 return props.namespace ? tagName : tagName.toUpperCase();
16838 },{"browser-split":5}],194:[function(require,module,exports){
16839 var isVNode = require("./is-vnode")
16840 var isVText = require("./is-vtext")
16841 var isWidget = require("./is-widget")
16842 var isThunk = require("./is-thunk")
16844 module.exports = handleThunk
16846 function handleThunk(a, b) {
16851 renderedB = renderThunk(b, a)
16855 renderedA = renderThunk(a, null)
16864 function renderThunk(thunk, previous) {
16865 var renderedThunk = thunk.vnode
16867 if (!renderedThunk) {
16868 renderedThunk = thunk.vnode = thunk.render(previous)
16871 if (!(isVNode(renderedThunk) ||
16872 isVText(renderedThunk) ||
16873 isWidget(renderedThunk))) {
16874 throw new Error("thunk did not return a valid node");
16877 return renderedThunk
16880 },{"./is-thunk":195,"./is-vnode":197,"./is-vtext":198,"./is-widget":199}],195:[function(require,module,exports){
16881 module.exports = isThunk
16883 function isThunk(t) {
16884 return t && t.type === "Thunk"
16887 },{}],196:[function(require,module,exports){
16888 module.exports = isHook
16890 function isHook(hook) {
16892 (typeof hook.hook === "function" && !hook.hasOwnProperty("hook") ||
16893 typeof hook.unhook === "function" && !hook.hasOwnProperty("unhook"))
16896 },{}],197:[function(require,module,exports){
16897 var version = require("./version")
16899 module.exports = isVirtualNode
16901 function isVirtualNode(x) {
16902 return x && x.type === "VirtualNode" && x.version === version
16905 },{"./version":200}],198:[function(require,module,exports){
16906 var version = require("./version")
16908 module.exports = isVirtualText
16910 function isVirtualText(x) {
16911 return x && x.type === "VirtualText" && x.version === version
16914 },{"./version":200}],199:[function(require,module,exports){
16915 module.exports = isWidget
16917 function isWidget(w) {
16918 return w && w.type === "Widget"
16921 },{}],200:[function(require,module,exports){
16922 module.exports = "2"
16924 },{}],201:[function(require,module,exports){
16925 var version = require("./version")
16926 var isVNode = require("./is-vnode")
16927 var isWidget = require("./is-widget")
16928 var isThunk = require("./is-thunk")
16929 var isVHook = require("./is-vhook")
16931 module.exports = VirtualNode
16933 var noProperties = {}
16934 var noChildren = []
16936 function VirtualNode(tagName, properties, children, key, namespace) {
16937 this.tagName = tagName
16938 this.properties = properties || noProperties
16939 this.children = children || noChildren
16940 this.key = key != null ? String(key) : undefined
16941 this.namespace = (typeof namespace === "string") ? namespace : null
16943 var count = (children && children.length) || 0
16944 var descendants = 0
16945 var hasWidgets = false
16946 var hasThunks = false
16947 var descendantHooks = false
16950 for (var propName in properties) {
16951 if (properties.hasOwnProperty(propName)) {
16952 var property = properties[propName]
16953 if (isVHook(property) && property.unhook) {
16958 hooks[propName] = property
16963 for (var i = 0; i < count; i++) {
16964 var child = children[i]
16965 if (isVNode(child)) {
16966 descendants += child.count || 0
16968 if (!hasWidgets && child.hasWidgets) {
16972 if (!hasThunks && child.hasThunks) {
16976 if (!descendantHooks && (child.hooks || child.descendantHooks)) {
16977 descendantHooks = true
16979 } else if (!hasWidgets && isWidget(child)) {
16980 if (typeof child.destroy === "function") {
16983 } else if (!hasThunks && isThunk(child)) {
16988 this.count = count + descendants
16989 this.hasWidgets = hasWidgets
16990 this.hasThunks = hasThunks
16992 this.descendantHooks = descendantHooks
16995 VirtualNode.prototype.version = version
16996 VirtualNode.prototype.type = "VirtualNode"
16998 },{"./is-thunk":195,"./is-vhook":196,"./is-vnode":197,"./is-widget":199,"./version":200}],202:[function(require,module,exports){
16999 var version = require("./version")
17001 VirtualPatch.NONE = 0
17002 VirtualPatch.VTEXT = 1
17003 VirtualPatch.VNODE = 2
17004 VirtualPatch.WIDGET = 3
17005 VirtualPatch.PROPS = 4
17006 VirtualPatch.ORDER = 5
17007 VirtualPatch.INSERT = 6
17008 VirtualPatch.REMOVE = 7
17009 VirtualPatch.THUNK = 8
17011 module.exports = VirtualPatch
17013 function VirtualPatch(type, vNode, patch) {
17014 this.type = Number(type)
17019 VirtualPatch.prototype.version = version
17020 VirtualPatch.prototype.type = "VirtualPatch"
17022 },{"./version":200}],203:[function(require,module,exports){
17023 var version = require("./version")
17025 module.exports = VirtualText
17027 function VirtualText(text) {
17028 this.text = String(text)
17031 VirtualText.prototype.version = version
17032 VirtualText.prototype.type = "VirtualText"
17034 },{"./version":200}],204:[function(require,module,exports){
17035 var isObject = require("is-object")
17036 var isHook = require("../vnode/is-vhook")
17038 module.exports = diffProps
17040 function diffProps(a, b) {
17043 for (var aKey in a) {
17044 if (!(aKey in b)) {
17046 diff[aKey] = undefined
17049 var aValue = a[aKey]
17050 var bValue = b[aKey]
17052 if (aValue === bValue) {
17054 } else if (isObject(aValue) && isObject(bValue)) {
17055 if (getPrototype(bValue) !== getPrototype(aValue)) {
17057 diff[aKey] = bValue
17058 } else if (isHook(bValue)) {
17060 diff[aKey] = bValue
17062 var objectDiff = diffProps(aValue, bValue)
17065 diff[aKey] = objectDiff
17070 diff[aKey] = bValue
17074 for (var bKey in b) {
17075 if (!(bKey in a)) {
17077 diff[bKey] = b[bKey]
17084 function getPrototype(value) {
17085 if (Object.getPrototypeOf) {
17086 return Object.getPrototypeOf(value)
17087 } else if (value.__proto__) {
17088 return value.__proto__
17089 } else if (value.constructor) {
17090 return value.constructor.prototype
17094 },{"../vnode/is-vhook":196,"is-object":20}],205:[function(require,module,exports){
17095 var isArray = require("x-is-array")
17097 var VPatch = require("../vnode/vpatch")
17098 var isVNode = require("../vnode/is-vnode")
17099 var isVText = require("../vnode/is-vtext")
17100 var isWidget = require("../vnode/is-widget")
17101 var isThunk = require("../vnode/is-thunk")
17102 var handleThunk = require("../vnode/handle-thunk")
17104 var diffProps = require("./diff-props")
17106 module.exports = diff
17108 function diff(a, b) {
17109 var patch = { a: a }
17110 walk(a, b, patch, 0)
17114 function walk(a, b, patch, index) {
17119 var apply = patch[index]
17120 var applyClear = false
17122 if (isThunk(a) || isThunk(b)) {
17123 thunks(a, b, patch, index)
17124 } else if (b == null) {
17126 // If a is a widget we will add a remove patch for it
17127 // Otherwise any child widgets/hooks must be destroyed.
17128 // This prevents adding two remove patches for a widget.
17129 if (!isWidget(a)) {
17130 clearState(a, patch, index)
17131 apply = patch[index]
17134 apply = appendPatch(apply, new VPatch(VPatch.REMOVE, a, b))
17135 } else if (isVNode(b)) {
17137 if (a.tagName === b.tagName &&
17138 a.namespace === b.namespace &&
17140 var propsPatch = diffProps(a.properties, b.properties)
17142 apply = appendPatch(apply,
17143 new VPatch(VPatch.PROPS, a, propsPatch))
17145 apply = diffChildren(a, b, patch, apply, index)
17147 apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
17151 apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
17154 } else if (isVText(b)) {
17156 apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
17158 } else if (a.text !== b.text) {
17159 apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
17161 } else if (isWidget(b)) {
17162 if (!isWidget(a)) {
17166 apply = appendPatch(apply, new VPatch(VPatch.WIDGET, a, b))
17170 patch[index] = apply
17174 clearState(a, patch, index)
17178 function diffChildren(a, b, patch, apply, index) {
17179 var aChildren = a.children
17180 var orderedSet = reorder(aChildren, b.children)
17181 var bChildren = orderedSet.children
17183 var aLen = aChildren.length
17184 var bLen = bChildren.length
17185 var len = aLen > bLen ? aLen : bLen
17187 for (var i = 0; i < len; i++) {
17188 var leftNode = aChildren[i]
17189 var rightNode = bChildren[i]
17194 // Excess nodes in b need to be added
17195 apply = appendPatch(apply,
17196 new VPatch(VPatch.INSERT, null, rightNode))
17199 walk(leftNode, rightNode, patch, index)
17202 if (isVNode(leftNode) && leftNode.count) {
17203 index += leftNode.count
17207 if (orderedSet.moves) {
17208 // Reorder nodes last
17209 apply = appendPatch(apply, new VPatch(
17219 function clearState(vNode, patch, index) {
17220 // TODO: Make this a single walk, not two
17221 unhook(vNode, patch, index)
17222 destroyWidgets(vNode, patch, index)
17225 // Patch records for all destroyed widgets must be added because we need
17226 // a DOM node reference for the destroy function
17227 function destroyWidgets(vNode, patch, index) {
17228 if (isWidget(vNode)) {
17229 if (typeof vNode.destroy === "function") {
17230 patch[index] = appendPatch(
17232 new VPatch(VPatch.REMOVE, vNode, null)
17235 } else if (isVNode(vNode) && (vNode.hasWidgets || vNode.hasThunks)) {
17236 var children = vNode.children
17237 var len = children.length
17238 for (var i = 0; i < len; i++) {
17239 var child = children[i]
17242 destroyWidgets(child, patch, index)
17244 if (isVNode(child) && child.count) {
17245 index += child.count
17248 } else if (isThunk(vNode)) {
17249 thunks(vNode, null, patch, index)
17253 // Create a sub-patch for thunks
17254 function thunks(a, b, patch, index) {
17255 var nodes = handleThunk(a, b)
17256 var thunkPatch = diff(nodes.a, nodes.b)
17257 if (hasPatches(thunkPatch)) {
17258 patch[index] = new VPatch(VPatch.THUNK, null, thunkPatch)
17262 function hasPatches(patch) {
17263 for (var index in patch) {
17264 if (index !== "a") {
17272 // Execute hooks when two nodes are identical
17273 function unhook(vNode, patch, index) {
17274 if (isVNode(vNode)) {
17276 patch[index] = appendPatch(
17281 undefinedKeys(vNode.hooks)
17286 if (vNode.descendantHooks || vNode.hasThunks) {
17287 var children = vNode.children
17288 var len = children.length
17289 for (var i = 0; i < len; i++) {
17290 var child = children[i]
17293 unhook(child, patch, index)
17295 if (isVNode(child) && child.count) {
17296 index += child.count
17300 } else if (isThunk(vNode)) {
17301 thunks(vNode, null, patch, index)
17305 function undefinedKeys(obj) {
17308 for (var key in obj) {
17309 result[key] = undefined
17315 // List diff, naive left to right reordering
17316 function reorder(aChildren, bChildren) {
17317 // O(M) time, O(M) memory
17318 var bChildIndex = keyIndex(bChildren)
17319 var bKeys = bChildIndex.keys
17320 var bFree = bChildIndex.free
17322 if (bFree.length === bChildren.length) {
17324 children: bChildren,
17329 // O(N) time, O(N) memory
17330 var aChildIndex = keyIndex(aChildren)
17331 var aKeys = aChildIndex.keys
17332 var aFree = aChildIndex.free
17334 if (aFree.length === aChildren.length) {
17336 children: bChildren,
17341 // O(MAX(N, M)) memory
17342 var newChildren = []
17345 var freeCount = bFree.length
17346 var deletedItems = 0
17348 // Iterate through a and match a node in b
17350 for (var i = 0 ; i < aChildren.length; i++) {
17351 var aItem = aChildren[i]
17355 if (bKeys.hasOwnProperty(aItem.key)) {
17356 // Match up the old keys
17357 itemIndex = bKeys[aItem.key]
17358 newChildren.push(bChildren[itemIndex])
17361 // Remove old keyed items
17362 itemIndex = i - deletedItems++
17363 newChildren.push(null)
17366 // Match the item in a with the next free item in b
17367 if (freeIndex < freeCount) {
17368 itemIndex = bFree[freeIndex++]
17369 newChildren.push(bChildren[itemIndex])
17371 // There are no free items in b to match with
17372 // the free items in a, so the extra free nodes
17374 itemIndex = i - deletedItems++
17375 newChildren.push(null)
17380 var lastFreeIndex = freeIndex >= bFree.length ?
17384 // Iterate through b and append any new keys
17386 for (var j = 0; j < bChildren.length; j++) {
17387 var newItem = bChildren[j]
17390 if (!aKeys.hasOwnProperty(newItem.key)) {
17391 // Add any new keyed items
17392 // We are adding new items to the end and then sorting them
17393 // in place. In future we should insert new items in place.
17394 newChildren.push(newItem)
17396 } else if (j >= lastFreeIndex) {
17397 // Add any leftover non-keyed items
17398 newChildren.push(newItem)
17402 var simulate = newChildren.slice()
17403 var simulateIndex = 0
17408 for (var k = 0; k < bChildren.length;) {
17409 var wantedItem = bChildren[k]
17410 simulateItem = simulate[simulateIndex]
17413 while (simulateItem === null && simulate.length) {
17414 removes.push(remove(simulate, simulateIndex, null))
17415 simulateItem = simulate[simulateIndex]
17418 if (!simulateItem || simulateItem.key !== wantedItem.key) {
17419 // if we need a key in this position...
17420 if (wantedItem.key) {
17421 if (simulateItem && simulateItem.key) {
17422 // if an insert doesn't put this key in place, it needs to move
17423 if (bKeys[simulateItem.key] !== k + 1) {
17424 removes.push(remove(simulate, simulateIndex, simulateItem.key))
17425 simulateItem = simulate[simulateIndex]
17426 // if the remove didn't put the wanted item in place, we need to insert it
17427 if (!simulateItem || simulateItem.key !== wantedItem.key) {
17428 inserts.push({key: wantedItem.key, to: k})
17430 // items are matching, so skip ahead
17436 inserts.push({key: wantedItem.key, to: k})
17440 inserts.push({key: wantedItem.key, to: k})
17444 // a key in simulate has no matching wanted key, remove it
17445 else if (simulateItem && simulateItem.key) {
17446 removes.push(remove(simulate, simulateIndex, simulateItem.key))
17455 // remove all the remaining nodes from simulate
17456 while(simulateIndex < simulate.length) {
17457 simulateItem = simulate[simulateIndex]
17458 removes.push(remove(simulate, simulateIndex, simulateItem && simulateItem.key))
17461 // If the only moves we have are deletes then we can just
17462 // let the delete patch remove these items.
17463 if (removes.length === deletedItems && !inserts.length) {
17465 children: newChildren,
17471 children: newChildren,
17479 function remove(arr, index, key) {
17480 arr.splice(index, 1)
17488 function keyIndex(children) {
17491 var length = children.length
17493 for (var i = 0; i < length; i++) {
17494 var child = children[i]
17497 keys[child.key] = i
17504 keys: keys, // A hash of key name to index
17505 free: free // An array of unkeyed item indices
17509 function appendPatch(apply, patch) {
17511 if (isArray(apply)) {
17514 apply = [apply, patch]
17523 },{"../vnode/handle-thunk":194,"../vnode/is-thunk":195,"../vnode/is-vnode":197,"../vnode/is-vtext":198,"../vnode/is-widget":199,"../vnode/vpatch":202,"./diff-props":204,"x-is-array":224}],206:[function(require,module,exports){
17524 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17525 /** @author Brian Cavalier */
17526 /** @author John Hann */
17528 (function(define) { 'use strict';
17529 define(function (require) {
17531 var makePromise = require('./makePromise');
17532 var Scheduler = require('./Scheduler');
17533 var async = require('./env').asap;
17535 return makePromise({
17536 scheduler: new Scheduler(async)
17540 })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
17542 },{"./Scheduler":207,"./env":219,"./makePromise":221}],207:[function(require,module,exports){
17543 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17544 /** @author Brian Cavalier */
17545 /** @author John Hann */
17547 (function(define) { 'use strict';
17548 define(function() {
17550 // Credit to Twisol (https://github.com/Twisol) for suggesting
17551 // this type of extensible queue + trampoline approach for next-tick conflation.
17554 * Async task scheduler
17555 * @param {function} async function to schedule a single async function
17558 function Scheduler(async) {
17559 this._async = async;
17560 this._running = false;
17562 this._queue = this;
17563 this._queueLen = 0;
17564 this._afterQueue = {};
17565 this._afterQueueLen = 0;
17568 this.drain = function() {
17575 * @param {{ run:function }} task
17577 Scheduler.prototype.enqueue = function(task) {
17578 this._queue[this._queueLen++] = task;
17583 * Enqueue a task to run after the main task queue
17584 * @param {{ run:function }} task
17586 Scheduler.prototype.afterQueue = function(task) {
17587 this._afterQueue[this._afterQueueLen++] = task;
17591 Scheduler.prototype.run = function() {
17592 if (!this._running) {
17593 this._running = true;
17594 this._async(this.drain);
17599 * Drain the handler queue entirely, and then the after queue
17601 Scheduler.prototype._drain = function() {
17603 for (; i < this._queueLen; ++i) {
17604 this._queue[i].run();
17605 this._queue[i] = void 0;
17608 this._queueLen = 0;
17609 this._running = false;
17611 for (i = 0; i < this._afterQueueLen; ++i) {
17612 this._afterQueue[i].run();
17613 this._afterQueue[i] = void 0;
17616 this._afterQueueLen = 0;
17622 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
17624 },{}],208:[function(require,module,exports){
17625 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17626 /** @author Brian Cavalier */
17627 /** @author John Hann */
17629 (function(define) { 'use strict';
17630 define(function() {
17633 * Custom error type for promises rejected by promise.timeout
17634 * @param {string} message
17637 function TimeoutError (message) {
17639 this.message = message;
17640 this.name = TimeoutError.name;
17641 if (typeof Error.captureStackTrace === 'function') {
17642 Error.captureStackTrace(this, TimeoutError);
17646 TimeoutError.prototype = Object.create(Error.prototype);
17647 TimeoutError.prototype.constructor = TimeoutError;
17649 return TimeoutError;
17651 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
17652 },{}],209:[function(require,module,exports){
17653 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17654 /** @author Brian Cavalier */
17655 /** @author John Hann */
17657 (function(define) { 'use strict';
17658 define(function() {
17660 makeApply.tryCatchResolve = tryCatchResolve;
17664 function makeApply(Promise, call) {
17665 if(arguments.length < 2) {
17666 call = tryCatchResolve;
17671 function apply(f, thisArg, args) {
17672 var p = Promise._defer();
17673 var l = args.length;
17674 var params = new Array(l);
17675 callAndResolve({ f:f, thisArg:thisArg, args:args, params:params, i:l-1, call:call }, p._handler);
17680 function callAndResolve(c, h) {
17682 return call(c.f, c.thisArg, c.params, h);
17685 var handler = Promise._handler(c.args[c.i]);
17686 handler.fold(callAndResolveNext, c, void 0, h);
17689 function callAndResolveNext(c, x, h) {
17692 callAndResolve(c, h);
17696 function tryCatchResolve(f, thisArg, args, resolver) {
17698 resolver.resolve(f.apply(thisArg, args));
17700 resolver.reject(e);
17705 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
17709 },{}],210:[function(require,module,exports){
17710 /** @license MIT License (c) copyright 2010-2014 original author or authors */
17711 /** @author Brian Cavalier */
17712 /** @author John Hann */
17714 (function(define) { 'use strict';
17715 define(function(require) {
17717 var state = require('../state');
17718 var applier = require('../apply');
17720 return function array(Promise) {
17722 var applyFold = applier(Promise);
17723 var toPromise = Promise.resolve;
17724 var all = Promise.all;
17726 var ar = Array.prototype.reduce;
17727 var arr = Array.prototype.reduceRight;
17728 var slice = Array.prototype.slice;
17730 // Additional array combinators
17733 Promise.some = some;
17734 Promise.settle = settle;
17737 Promise.filter = filter;
17738 Promise.reduce = reduce;
17739 Promise.reduceRight = reduceRight;
17742 * When this promise fulfills with an array, do
17743 * onFulfilled.apply(void 0, array)
17744 * @param {function} onFulfilled function to apply
17745 * @returns {Promise} promise for the result of applying onFulfilled
17747 Promise.prototype.spread = function(onFulfilled) {
17748 return this.then(all).then(function(array) {
17749 return onFulfilled.apply(this, array);
17756 * One-winner competitive race.
17757 * Return a promise that will fulfill when one of the promises
17758 * in the input array fulfills, or will reject when all promises
17760 * @param {array} promises
17761 * @returns {Promise} promise for the first fulfilled value
17763 function any(promises) {
17764 var p = Promise._defer();
17765 var resolver = p._handler;
17766 var l = promises.length>>>0;
17771 for (var h, x, i = 0; i < l; ++i) {
17773 if(x === void 0 && !(i in promises)) {
17778 h = Promise._handler(x);
17779 if(h.state() > 0) {
17780 resolver.become(h);
17781 Promise._visitRemaining(promises, i, h);
17784 h.visit(resolver, handleFulfill, handleReject);
17788 if(pending === 0) {
17789 resolver.reject(new RangeError('any(): array must not be empty'));
17794 function handleFulfill(x) {
17795 /*jshint validthis:true*/
17797 this.resolve(x); // this === resolver
17800 function handleReject(e) {
17801 /*jshint validthis:true*/
17802 if(this.resolved) { // this === resolver
17807 if(--pending === 0) {
17808 this.reject(errors);
17814 * N-winner competitive race
17815 * Return a promise that will fulfill when n input promises have
17816 * fulfilled, or will reject when it becomes impossible for n
17817 * input promises to fulfill (ie when promises.length - n + 1
17819 * @param {array} promises
17820 * @param {number} n
17821 * @returns {Promise} promise for the earliest n fulfillment values
17825 function some(promises, n) {
17826 /*jshint maxcomplexity:7*/
17827 var p = Promise._defer();
17828 var resolver = p._handler;
17833 var l = promises.length>>>0;
17836 var x, i; // reused in both for() loops
17838 // First pass: count actual array items
17839 for(i=0; i<l; ++i) {
17841 if(x === void 0 && !(i in promises)) {
17847 // Compute actual goals
17848 n = Math.max(n, 0);
17849 nReject = (nFulfill - n + 1);
17850 nFulfill = Math.min(n, nFulfill);
17853 resolver.reject(new RangeError('some(): array must contain at least '
17854 + n + ' item(s), but had ' + nFulfill));
17855 } else if(nFulfill === 0) {
17856 resolver.resolve(results);
17859 // Second pass: observe each array item, make progress toward goals
17860 for(i=0; i<l; ++i) {
17862 if(x === void 0 && !(i in promises)) {
17866 Promise._handler(x).visit(resolver, fulfill, reject, resolver.notify);
17871 function fulfill(x) {
17872 /*jshint validthis:true*/
17873 if(this.resolved) { // this === resolver
17878 if(--nFulfill === 0) {
17880 this.resolve(results);
17884 function reject(e) {
17885 /*jshint validthis:true*/
17886 if(this.resolved) { // this === resolver
17891 if(--nReject === 0) {
17893 this.reject(errors);
17899 * Apply f to the value of each promise in a list of promises
17900 * and return a new list containing the results.
17901 * @param {array} promises
17902 * @param {function(x:*, index:Number):*} f mapping function
17903 * @returns {Promise}
17905 function map(promises, f) {
17906 return Promise._traverse(f, promises);
17910 * Filter the provided array of promises using the provided predicate. Input may
17911 * contain promises and values
17912 * @param {Array} promises array of promises and values
17913 * @param {function(x:*, index:Number):boolean} predicate filtering predicate.
17914 * Must return truthy (or promise for truthy) for items to retain.
17915 * @returns {Promise} promise that will fulfill with an array containing all items
17916 * for which predicate returned truthy.
17918 function filter(promises, predicate) {
17919 var a = slice.call(promises);
17920 return Promise._traverse(predicate, a).then(function(keep) {
17921 return filterSync(a, keep);
17925 function filterSync(promises, keep) {
17926 // Safe because we know all promises have fulfilled if we've made it this far
17927 var l = keep.length;
17928 var filtered = new Array(l);
17929 for(var i=0, j=0; i<l; ++i) {
17931 filtered[j++] = Promise._handler(promises[i]).value;
17934 filtered.length = j;
17940 * Return a promise that will always fulfill with an array containing
17941 * the outcome states of all input promises. The returned promise
17942 * will never reject.
17943 * @param {Array} promises
17944 * @returns {Promise} promise for array of settled state descriptors
17946 function settle(promises) {
17947 return all(promises.map(settleOne));
17950 function settleOne(p) {
17951 // Optimize the case where we get an already-resolved when.js promise
17952 // by extracting its state:
17954 if (p instanceof Promise) {
17955 // This is our own Promise type and we can reach its handler internals:
17956 handler = p._handler.join();
17958 if((handler && handler.state() === 0) || !handler) {
17959 // Either still pending, or not a Promise at all:
17960 return toPromise(p).then(state.fulfilled, state.rejected);
17963 // The promise is our own, but it is already resolved. Take a shortcut.
17964 // Since we're not actually handling the resolution, we need to disable
17965 // rejection reporting.
17966 handler._unreport();
17967 return state.inspect(handler);
17971 * Traditional reduce function, similar to `Array.prototype.reduce()`, but
17972 * input may contain promises and/or values, and reduceFunc
17973 * may return either a value or a promise, *and* initialValue may
17974 * be a promise for the starting value.
17975 * @param {Array|Promise} promises array or promise for an array of anything,
17976 * may contain a mix of promises and values.
17977 * @param {function(accumulated:*, x:*, index:Number):*} f reduce function
17978 * @returns {Promise} that will resolve to the final reduced value
17980 function reduce(promises, f /*, initialValue */) {
17981 return arguments.length > 2 ? ar.call(promises, liftCombine(f), arguments[2])
17982 : ar.call(promises, liftCombine(f));
17986 * Traditional reduce function, similar to `Array.prototype.reduceRight()`, but
17987 * input may contain promises and/or values, and reduceFunc
17988 * may return either a value or a promise, *and* initialValue may
17989 * be a promise for the starting value.
17990 * @param {Array|Promise} promises array or promise for an array of anything,
17991 * may contain a mix of promises and values.
17992 * @param {function(accumulated:*, x:*, index:Number):*} f reduce function
17993 * @returns {Promise} that will resolve to the final reduced value
17995 function reduceRight(promises, f /*, initialValue */) {
17996 return arguments.length > 2 ? arr.call(promises, liftCombine(f), arguments[2])
17997 : arr.call(promises, liftCombine(f));
18000 function liftCombine(f) {
18001 return function(z, x, i) {
18002 return applyFold(f, void 0, [z,x,i]);
18008 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
18010 },{"../apply":209,"../state":222}],211:[function(require,module,exports){
18011 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18012 /** @author Brian Cavalier */
18013 /** @author John Hann */
18015 (function(define) { 'use strict';
18016 define(function() {
18018 return function flow(Promise) {
18020 var resolve = Promise.resolve;
18021 var reject = Promise.reject;
18022 var origCatch = Promise.prototype['catch'];
18025 * Handle the ultimate fulfillment value or rejection reason, and assume
18026 * responsibility for all errors. If an error propagates out of result
18027 * or handleFatalError, it will be rethrown to the host, resulting in a
18028 * loud stack track on most platforms and a crash on some.
18029 * @param {function?} onResult
18030 * @param {function?} onError
18031 * @returns {undefined}
18033 Promise.prototype.done = function(onResult, onError) {
18034 this._handler.visit(this._handler.receiver, onResult, onError);
18038 * Add Error-type and predicate matching to catch. Examples:
18039 * promise.catch(TypeError, handleTypeError)
18040 * .catch(predicate, handleMatchedErrors)
18041 * .catch(handleRemainingErrors)
18042 * @param onRejected
18045 Promise.prototype['catch'] = Promise.prototype.otherwise = function(onRejected) {
18046 if (arguments.length < 2) {
18047 return origCatch.call(this, onRejected);
18050 if(typeof onRejected !== 'function') {
18051 return this.ensure(rejectInvalidPredicate);
18054 return origCatch.call(this, createCatchFilter(arguments[1], onRejected));
18058 * Wraps the provided catch handler, so that it will only be called
18059 * if the predicate evaluates truthy
18060 * @param {?function} handler
18061 * @param {function} predicate
18062 * @returns {function} conditional catch handler
18064 function createCatchFilter(handler, predicate) {
18065 return function(e) {
18066 return evaluatePredicate(e, predicate)
18067 ? handler.call(this, e)
18073 * Ensures that onFulfilledOrRejected will be called regardless of whether
18074 * this promise is fulfilled or rejected. onFulfilledOrRejected WILL NOT
18075 * receive the promises' value or reason. Any returned value will be disregarded.
18076 * onFulfilledOrRejected may throw or return a rejected promise to signal
18077 * an additional error.
18078 * @param {function} handler handler to be called regardless of
18079 * fulfillment or rejection
18080 * @returns {Promise}
18082 Promise.prototype['finally'] = Promise.prototype.ensure = function(handler) {
18083 if(typeof handler !== 'function') {
18087 return this.then(function(x) {
18088 return runSideEffect(handler, this, identity, x);
18090 return runSideEffect(handler, this, reject, e);
18094 function runSideEffect (handler, thisArg, propagate, value) {
18095 var result = handler.call(thisArg);
18096 return maybeThenable(result)
18097 ? propagateValue(result, propagate, value)
18098 : propagate(value);
18101 function propagateValue (result, propagate, x) {
18102 return resolve(result).then(function () {
18103 return propagate(x);
18108 * Recover from a failure by returning a defaultValue. If defaultValue
18109 * is a promise, it's fulfillment value will be used. If defaultValue is
18110 * a promise that rejects, the returned promise will reject with the
18112 * @param {*} defaultValue
18113 * @returns {Promise} new promise
18115 Promise.prototype['else'] = Promise.prototype.orElse = function(defaultValue) {
18116 return this.then(void 0, function() {
18117 return defaultValue;
18122 * Shortcut for .then(function() { return value; })
18124 * @return {Promise} a promise that:
18125 * - is fulfilled if value is not a promise, or
18126 * - if value is a promise, will fulfill with its value, or reject
18129 Promise.prototype['yield'] = function(value) {
18130 return this.then(function() {
18136 * Runs a side effect when this promise fulfills, without changing the
18137 * fulfillment value.
18138 * @param {function} onFulfilledSideEffect
18139 * @returns {Promise}
18141 Promise.prototype.tap = function(onFulfilledSideEffect) {
18142 return this.then(onFulfilledSideEffect)['yield'](this);
18148 function rejectInvalidPredicate() {
18149 throw new TypeError('catch predicate must be a function');
18152 function evaluatePredicate(e, predicate) {
18153 return isError(predicate) ? e instanceof predicate : predicate(e);
18156 function isError(predicate) {
18157 return predicate === Error
18158 || (predicate != null && predicate.prototype instanceof Error);
18161 function maybeThenable(x) {
18162 return (typeof x === 'object' || typeof x === 'function') && x !== null;
18165 function identity(x) {
18170 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18172 },{}],212:[function(require,module,exports){
18173 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18174 /** @author Brian Cavalier */
18175 /** @author John Hann */
18176 /** @author Jeff Escalante */
18178 (function(define) { 'use strict';
18179 define(function() {
18181 return function fold(Promise) {
18183 Promise.prototype.fold = function(f, z) {
18184 var promise = this._beget();
18186 this._handler.fold(function(z, x, to) {
18187 Promise._handler(z).fold(function(x, z, to) {
18188 to.resolve(f.call(this, z, x));
18190 }, z, promise._handler.receiver, promise._handler);
18199 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18201 },{}],213:[function(require,module,exports){
18202 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18203 /** @author Brian Cavalier */
18204 /** @author John Hann */
18206 (function(define) { 'use strict';
18207 define(function(require) {
18209 var inspect = require('../state').inspect;
18211 return function inspection(Promise) {
18213 Promise.prototype.inspect = function() {
18214 return inspect(Promise._handler(this));
18221 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
18223 },{"../state":222}],214:[function(require,module,exports){
18224 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18225 /** @author Brian Cavalier */
18226 /** @author John Hann */
18228 (function(define) { 'use strict';
18229 define(function() {
18231 return function generate(Promise) {
18233 var resolve = Promise.resolve;
18235 Promise.iterate = iterate;
18236 Promise.unfold = unfold;
18241 * @deprecated Use github.com/cujojs/most streams and most.iterate
18242 * Generate a (potentially infinite) stream of promised values:
18243 * x, f(x), f(f(x)), etc. until condition(x) returns true
18244 * @param {function} f function to generate a new x from the previous x
18245 * @param {function} condition function that, given the current x, returns
18246 * truthy when the iterate should stop
18247 * @param {function} handler function to handle the value produced by f
18248 * @param {*|Promise} x starting value, may be a promise
18249 * @return {Promise} the result of the last call to f before
18250 * condition returns true
18252 function iterate(f, condition, handler, x) {
18253 return unfold(function(x) {
18255 }, condition, handler, x);
18259 * @deprecated Use github.com/cujojs/most streams and most.unfold
18260 * Generate a (potentially infinite) stream of promised values
18261 * by applying handler(generator(seed)) iteratively until
18262 * condition(seed) returns true.
18263 * @param {function} unspool function that generates a [value, newSeed]
18265 * @param {function} condition function that, given the current seed, returns
18266 * truthy when the unfold should stop
18267 * @param {function} handler function to handle the value produced by unspool
18268 * @param x {*|Promise} starting value, may be a promise
18269 * @return {Promise} the result of the last value produced by unspool before
18270 * condition returns true
18272 function unfold(unspool, condition, handler, x) {
18273 return resolve(x).then(function(seed) {
18274 return resolve(condition(seed)).then(function(done) {
18275 return done ? seed : resolve(unspool(seed)).spread(next);
18279 function next(item, newSeed) {
18280 return resolve(handler(item)).then(function() {
18281 return unfold(unspool, condition, handler, newSeed);
18288 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18290 },{}],215:[function(require,module,exports){
18291 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18292 /** @author Brian Cavalier */
18293 /** @author John Hann */
18295 (function(define) { 'use strict';
18296 define(function() {
18298 return function progress(Promise) {
18302 * Register a progress handler for this promise
18303 * @param {function} onProgress
18304 * @returns {Promise}
18306 Promise.prototype.progress = function(onProgress) {
18307 return this.then(void 0, void 0, onProgress);
18314 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18316 },{}],216:[function(require,module,exports){
18317 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18318 /** @author Brian Cavalier */
18319 /** @author John Hann */
18321 (function(define) { 'use strict';
18322 define(function(require) {
18324 var env = require('../env');
18325 var TimeoutError = require('../TimeoutError');
18327 function setTimeout(f, ms, x, y) {
18328 return env.setTimer(function() {
18333 return function timed(Promise) {
18335 * Return a new promise whose fulfillment value is revealed only
18336 * after ms milliseconds
18337 * @param {number} ms milliseconds
18338 * @returns {Promise}
18340 Promise.prototype.delay = function(ms) {
18341 var p = this._beget();
18342 this._handler.fold(handleDelay, ms, void 0, p._handler);
18346 function handleDelay(ms, x, h) {
18347 setTimeout(resolveDelay, ms, x, h);
18350 function resolveDelay(x, h) {
18355 * Return a new promise that rejects after ms milliseconds unless
18356 * this promise fulfills earlier, in which case the returned promise
18357 * fulfills with the same value.
18358 * @param {number} ms milliseconds
18359 * @param {Error|*=} reason optional rejection reason to use, defaults
18360 * to a TimeoutError if not provided
18361 * @returns {Promise}
18363 Promise.prototype.timeout = function(ms, reason) {
18364 var p = this._beget();
18365 var h = p._handler;
18367 var t = setTimeout(onTimeout, ms, reason, p._handler);
18369 this._handler.visit(h,
18370 function onFulfill(x) {
18372 this.resolve(x); // this = h
18374 function onReject(x) {
18376 this.reject(x); // this = h
18383 function onTimeout(reason, h, ms) {
18384 var e = typeof reason === 'undefined'
18385 ? new TimeoutError('timed out after ' + ms + 'ms')
18394 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
18396 },{"../TimeoutError":208,"../env":219}],217:[function(require,module,exports){
18397 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18398 /** @author Brian Cavalier */
18399 /** @author John Hann */
18401 (function(define) { 'use strict';
18402 define(function(require) {
18404 var setTimer = require('../env').setTimer;
18405 var format = require('../format');
18407 return function unhandledRejection(Promise) {
18409 var logError = noop;
18410 var logInfo = noop;
18413 if(typeof console !== 'undefined') {
18414 // Alias console to prevent things like uglify's drop_console option from
18415 // removing console.log/error. Unhandled rejections fall into the same
18416 // category as uncaught exceptions, and build tools shouldn't silence them.
18417 localConsole = console;
18418 logError = typeof localConsole.error !== 'undefined'
18419 ? function (e) { localConsole.error(e); }
18420 : function (e) { localConsole.log(e); };
18422 logInfo = typeof localConsole.info !== 'undefined'
18423 ? function (e) { localConsole.info(e); }
18424 : function (e) { localConsole.log(e); };
18427 Promise.onPotentiallyUnhandledRejection = function(rejection) {
18428 enqueue(report, rejection);
18431 Promise.onPotentiallyUnhandledRejectionHandled = function(rejection) {
18432 enqueue(unreport, rejection);
18435 Promise.onFatalRejection = function(rejection) {
18436 enqueue(throwit, rejection.value);
18441 var running = null;
18443 function report(r) {
18446 logError('Potentially unhandled rejection [' + r.id + '] ' + format.formatError(r.value));
18450 function unreport(r) {
18451 var i = reported.indexOf(r);
18453 reported.splice(i, 1);
18454 logInfo('Handled previous rejection [' + r.id + '] ' + format.formatObject(r.value));
18458 function enqueue(f, x) {
18460 if(running === null) {
18461 running = setTimer(flush, 0);
18467 while(tasks.length > 0) {
18468 tasks.shift()(tasks.shift());
18475 function throwit(e) {
18482 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
18484 },{"../env":219,"../format":220}],218:[function(require,module,exports){
18485 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18486 /** @author Brian Cavalier */
18487 /** @author John Hann */
18489 (function(define) { 'use strict';
18490 define(function() {
18492 return function addWith(Promise) {
18494 * Returns a promise whose handlers will be called with `this` set to
18495 * the supplied receiver. Subsequent promises derived from the
18496 * returned promise will also have their handlers called with receiver
18497 * as `this`. Calling `with` with undefined or no arguments will return
18498 * a promise whose handlers will again be called in the usual Promises/A+
18499 * way (no `this`) thus safely undoing any previous `with` in the
18502 * WARNING: Promises returned from `with`/`withThis` are NOT Promises/A+
18503 * compliant, specifically violating 2.2.5 (http://promisesaplus.com/#point-41)
18505 * @param {object} receiver `this` value for all handlers attached to
18506 * the returned promise.
18507 * @returns {Promise}
18509 Promise.prototype['with'] = Promise.prototype.withThis = function(receiver) {
18510 var p = this._beget();
18511 var child = p._handler;
18512 child.receiver = receiver;
18513 this._handler.chain(child, receiver);
18521 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18524 },{}],219:[function(require,module,exports){
18525 (function (process){
18526 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18527 /** @author Brian Cavalier */
18528 /** @author John Hann */
18530 /*global process,document,setTimeout,clearTimeout,MutationObserver,WebKitMutationObserver*/
18531 (function(define) { 'use strict';
18532 define(function(require) {
18533 /*jshint maxcomplexity:6*/
18535 // Sniff "best" async scheduling option
18536 // Prefer process.nextTick or MutationObserver, then check for
18537 // setTimeout, and finally vertx, since its the only env that doesn't
18541 var capturedSetTimeout = typeof setTimeout !== 'undefined' && setTimeout;
18544 var setTimer = function(f, ms) { return setTimeout(f, ms); };
18545 var clearTimer = function(t) { return clearTimeout(t); };
18546 var asap = function (f) { return capturedSetTimeout(f, 0); };
18548 // Detect specific env
18549 if (isNode()) { // Node
18550 asap = function (f) { return process.nextTick(f); };
18552 } else if (MutationObs = hasMutationObserver()) { // Modern browser
18553 asap = initMutationObserver(MutationObs);
18555 } else if (!capturedSetTimeout) { // vert.x
18556 var vertxRequire = require;
18557 var vertx = vertxRequire('vertx');
18558 setTimer = function (f, ms) { return vertx.setTimer(ms, f); };
18559 clearTimer = vertx.cancelTimer;
18560 asap = vertx.runOnLoop || vertx.runOnContext;
18564 setTimer: setTimer,
18565 clearTimer: clearTimer,
18569 function isNode () {
18570 return typeof process !== 'undefined' &&
18571 Object.prototype.toString.call(process) === '[object process]';
18574 function hasMutationObserver () {
18575 return (typeof MutationObserver !== 'undefined' && MutationObserver) ||
18576 (typeof WebKitMutationObserver !== 'undefined' && WebKitMutationObserver);
18579 function initMutationObserver(MutationObserver) {
18581 var node = document.createTextNode('');
18582 var o = new MutationObserver(run);
18583 o.observe(node, { characterData: true });
18587 scheduled = void 0;
18592 return function (f) {
18594 node.data = (i ^= 1);
18598 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
18600 }).call(this,require('_process'))
18602 },{"_process":6}],220:[function(require,module,exports){
18603 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18604 /** @author Brian Cavalier */
18605 /** @author John Hann */
18607 (function(define) { 'use strict';
18608 define(function() {
18611 formatError: formatError,
18612 formatObject: formatObject,
18613 tryStringify: tryStringify
18617 * Format an error into a string. If e is an Error and has a stack property,
18618 * it's returned. Otherwise, e is formatted using formatObject, with a
18619 * warning added about e not being a proper Error.
18621 * @returns {String} formatted string, suitable for output to developers
18623 function formatError(e) {
18624 var s = typeof e === 'object' && e !== null && (e.stack || e.message) ? e.stack || e.message : formatObject(e);
18625 return e instanceof Error ? s : s + ' (WARNING: non-Error used)';
18629 * Format an object, detecting "plain" objects and running them through
18630 * JSON.stringify if possible.
18631 * @param {Object} o
18632 * @returns {string}
18634 function formatObject(o) {
18636 if(s === '[object Object]' && typeof JSON !== 'undefined') {
18637 s = tryStringify(o, s);
18643 * Try to return the result of JSON.stringify(x). If that fails, return
18646 * @param {*} defaultValue
18647 * @returns {String|*} JSON.stringify(x) or defaultValue
18649 function tryStringify(x, defaultValue) {
18651 return JSON.stringify(x);
18653 return defaultValue;
18658 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
18660 },{}],221:[function(require,module,exports){
18661 (function (process){
18662 /** @license MIT License (c) copyright 2010-2014 original author or authors */
18663 /** @author Brian Cavalier */
18664 /** @author John Hann */
18666 (function(define) { 'use strict';
18667 define(function() {
18669 return function makePromise(environment) {
18671 var tasks = environment.scheduler;
18672 var emitRejection = initEmitRejection();
18674 var objectCreate = Object.create ||
18676 function Child() {}
18677 Child.prototype = proto;
18678 return new Child();
18682 * Create a promise whose fate is determined by resolver
18684 * @returns {Promise} promise
18687 function Promise(resolver, handler) {
18688 this._handler = resolver === Handler ? handler : init(resolver);
18692 * Run the supplied resolver
18694 * @returns {Pending}
18696 function init(resolver) {
18697 var handler = new Pending();
18700 resolver(promiseResolve, promiseReject, promiseNotify);
18708 * Transition from pre-resolution state to post-resolution state, notifying
18709 * all listeners of the ultimate fulfillment or rejection
18710 * @param {*} x resolution value
18712 function promiseResolve (x) {
18713 handler.resolve(x);
18716 * Reject this promise with reason, which will be used verbatim
18717 * @param {Error|*} reason rejection reason, strongly suggested
18718 * to be an Error type
18720 function promiseReject (reason) {
18721 handler.reject(reason);
18726 * Issue a progress event, notifying all progress listeners
18727 * @param {*} x progress event payload to pass to all listeners
18729 function promiseNotify (x) {
18736 Promise.resolve = resolve;
18737 Promise.reject = reject;
18738 Promise.never = never;
18740 Promise._defer = defer;
18741 Promise._handler = getHandler;
18744 * Returns a trusted promise. If x is already a trusted promise, it is
18745 * returned, otherwise returns a new trusted Promise which follows x.
18747 * @return {Promise} promise
18749 function resolve(x) {
18750 return isPromise(x) ? x
18751 : new Promise(Handler, new Async(getHandler(x)));
18755 * Return a reject promise with x as its reason (x is used verbatim)
18757 * @returns {Promise} rejected promise
18759 function reject(x) {
18760 return new Promise(Handler, new Async(new Rejected(x)));
18764 * Return a promise that remains pending forever
18765 * @returns {Promise} forever-pending promise.
18768 return foreverPendingPromise; // Should be frozen
18772 * Creates an internal {promise, resolver} pair
18774 * @returns {Promise}
18777 return new Promise(Handler, new Pending());
18780 // Transformation and flow control
18783 * Transform this promise's fulfillment value, returning a new Promise
18784 * for the transformed result. If the promise cannot be fulfilled, onRejected
18785 * is called with the reason. onProgress *may* be called with updates toward
18786 * this promise's fulfillment.
18787 * @param {function=} onFulfilled fulfillment handler
18788 * @param {function=} onRejected rejection handler
18789 * @param {function=} onProgress @deprecated progress handler
18790 * @return {Promise} new promise
18792 Promise.prototype.then = function(onFulfilled, onRejected, onProgress) {
18793 var parent = this._handler;
18794 var state = parent.join().state();
18796 if ((typeof onFulfilled !== 'function' && state > 0) ||
18797 (typeof onRejected !== 'function' && state < 0)) {
18798 // Short circuit: value will not change, simply share handler
18799 return new this.constructor(Handler, parent);
18802 var p = this._beget();
18803 var child = p._handler;
18805 parent.chain(child, parent.receiver, onFulfilled, onRejected, onProgress);
18811 * If this promise cannot be fulfilled due to an error, call onRejected to
18812 * handle the error. Shortcut for .then(undefined, onRejected)
18813 * @param {function?} onRejected
18814 * @return {Promise}
18816 Promise.prototype['catch'] = function(onRejected) {
18817 return this.then(void 0, onRejected);
18821 * Creates a new, pending promise of the same type as this promise
18823 * @returns {Promise}
18825 Promise.prototype._beget = function() {
18826 return begetFrom(this._handler, this.constructor);
18829 function begetFrom(parent, Promise) {
18830 var child = new Pending(parent.receiver, parent.join().context);
18831 return new Promise(Handler, child);
18834 // Array combinators
18837 Promise.race = race;
18838 Promise._traverse = traverse;
18841 * Return a promise that will fulfill when all promises in the
18842 * input array have fulfilled, or will reject when one of the
18843 * promises rejects.
18844 * @param {array} promises array of promises
18845 * @returns {Promise} promise for array of fulfillment values
18847 function all(promises) {
18848 return traverseWith(snd, null, promises);
18852 * Array<Promise<X>> -> Promise<Array<f(X)>>
18854 * @param {function} f function to apply to each promise's value
18855 * @param {Array} promises array of promises
18856 * @returns {Promise} promise for transformed values
18858 function traverse(f, promises) {
18859 return traverseWith(tryCatch2, f, promises);
18862 function traverseWith(tryMap, f, promises) {
18863 var handler = typeof f === 'function' ? mapAt : settleAt;
18865 var resolver = new Pending();
18866 var pending = promises.length >>> 0;
18867 var results = new Array(pending);
18869 for (var i = 0, x; i < promises.length && !resolver.resolved; ++i) {
18872 if (x === void 0 && !(i in promises)) {
18877 traverseAt(promises, handler, i, x, resolver);
18880 if(pending === 0) {
18881 resolver.become(new Fulfilled(results));
18884 return new Promise(Handler, resolver);
18886 function mapAt(i, x, resolver) {
18887 if(!resolver.resolved) {
18888 traverseAt(promises, settleAt, i, tryMap(f, x, i), resolver);
18892 function settleAt(i, x, resolver) {
18894 if(--pending === 0) {
18895 resolver.become(new Fulfilled(results));
18900 function traverseAt(promises, handler, i, x, resolver) {
18901 if (maybeThenable(x)) {
18902 var h = getHandlerMaybeThenable(x);
18906 h.fold(handler, i, void 0, resolver);
18907 } else if (s > 0) {
18908 handler(i, h.value, resolver);
18910 resolver.become(h);
18911 visitRemaining(promises, i+1, h);
18914 handler(i, x, resolver);
18918 Promise._visitRemaining = visitRemaining;
18919 function visitRemaining(promises, start, handler) {
18920 for(var i=start; i<promises.length; ++i) {
18921 markAsHandled(getHandler(promises[i]), handler);
18925 function markAsHandled(h, handler) {
18926 if(h === handler) {
18932 h.visit(h, void 0, h._unreport);
18939 * Fulfill-reject competitive race. Return a promise that will settle
18940 * to the same state as the earliest input promise to settle.
18942 * WARNING: The ES6 Promise spec requires that race()ing an empty array
18943 * must return a promise that is pending forever. This implementation
18944 * returns a singleton forever-pending promise, the same singleton that is
18945 * returned by Promise.never(), thus can be checked with ===
18947 * @param {array} promises array of promises to race
18948 * @returns {Promise} if input is non-empty, a promise that will settle
18949 * to the same outcome as the earliest input promise to settle. if empty
18950 * is empty, returns a promise that will never settle.
18952 function race(promises) {
18953 if(typeof promises !== 'object' || promises === null) {
18954 return reject(new TypeError('non-iterable passed to race()'));
18957 // Sigh, race([]) is untestable unless we return *something*
18958 // that is recognizable without calling .then() on it.
18959 return promises.length === 0 ? never()
18960 : promises.length === 1 ? resolve(promises[0])
18961 : runRace(promises);
18964 function runRace(promises) {
18965 var resolver = new Pending();
18967 for(i=0; i<promises.length; ++i) {
18969 if (x === void 0 && !(i in promises)) {
18974 if(h.state() !== 0) {
18975 resolver.become(h);
18976 visitRemaining(promises, i+1, h);
18979 h.visit(resolver, resolver.resolve, resolver.reject);
18982 return new Promise(Handler, resolver);
18985 // Promise internals
18986 // Below this, everything is @private
18989 * Get an appropriate handler for x, without checking for cycles
18991 * @returns {object} handler
18993 function getHandler(x) {
18995 return x._handler.join();
18997 return maybeThenable(x) ? getHandlerUntrusted(x) : new Fulfilled(x);
19001 * Get a handler for thenable x.
19002 * NOTE: You must only call this if maybeThenable(x) == true
19003 * @param {object|function|Promise} x
19004 * @returns {object} handler
19006 function getHandlerMaybeThenable(x) {
19007 return isPromise(x) ? x._handler.join() : getHandlerUntrusted(x);
19011 * Get a handler for potentially untrusted thenable x
19013 * @returns {object} handler
19015 function getHandlerUntrusted(x) {
19017 var untrustedThen = x.then;
19018 return typeof untrustedThen === 'function'
19019 ? new Thenable(untrustedThen, x)
19020 : new Fulfilled(x);
19022 return new Rejected(e);
19027 * Handler for a promise that is pending forever
19030 function Handler() {}
19032 Handler.prototype.when
19033 = Handler.prototype.become
19034 = Handler.prototype.notify // deprecated
19035 = Handler.prototype.fail
19036 = Handler.prototype._unreport
19037 = Handler.prototype._report
19040 Handler.prototype._state = 0;
19042 Handler.prototype.state = function() {
19043 return this._state;
19047 * Recursively collapse handler chain to find the handler
19048 * nearest to the fully resolved value.
19049 * @returns {object} handler nearest the fully resolved value
19051 Handler.prototype.join = function() {
19053 while(h.handler !== void 0) {
19059 Handler.prototype.chain = function(to, receiver, fulfilled, rejected, progress) {
19062 receiver: receiver,
19063 fulfilled: fulfilled,
19064 rejected: rejected,
19069 Handler.prototype.visit = function(receiver, fulfilled, rejected, progress) {
19070 this.chain(failIfRejected, receiver, fulfilled, rejected, progress);
19073 Handler.prototype.fold = function(f, z, c, to) {
19074 this.when(new Fold(f, z, c, to));
19078 * Handler that invokes fail() on any handler it becomes
19081 function FailIfRejected() {}
19083 inherit(Handler, FailIfRejected);
19085 FailIfRejected.prototype.become = function(h) {
19089 var failIfRejected = new FailIfRejected();
19092 * Handler that manages a queue of consumers waiting on a pending promise
19095 function Pending(receiver, inheritedContext) {
19096 Promise.createContext(this, inheritedContext);
19098 this.consumers = void 0;
19099 this.receiver = receiver;
19100 this.handler = void 0;
19101 this.resolved = false;
19104 inherit(Handler, Pending);
19106 Pending.prototype._state = 0;
19108 Pending.prototype.resolve = function(x) {
19109 this.become(getHandler(x));
19112 Pending.prototype.reject = function(x) {
19113 if(this.resolved) {
19117 this.become(new Rejected(x));
19120 Pending.prototype.join = function() {
19121 if (!this.resolved) {
19127 while (h.handler !== void 0) {
19130 return this.handler = cycle();
19137 Pending.prototype.run = function() {
19138 var q = this.consumers;
19139 var handler = this.handler;
19140 this.handler = this.handler.join();
19141 this.consumers = void 0;
19143 for (var i = 0; i < q.length; ++i) {
19144 handler.when(q[i]);
19148 Pending.prototype.become = function(handler) {
19149 if(this.resolved) {
19153 this.resolved = true;
19154 this.handler = handler;
19155 if(this.consumers !== void 0) {
19156 tasks.enqueue(this);
19159 if(this.context !== void 0) {
19160 handler._report(this.context);
19164 Pending.prototype.when = function(continuation) {
19165 if(this.resolved) {
19166 tasks.enqueue(new ContinuationTask(continuation, this.handler));
19168 if(this.consumers === void 0) {
19169 this.consumers = [continuation];
19171 this.consumers.push(continuation);
19179 Pending.prototype.notify = function(x) {
19180 if(!this.resolved) {
19181 tasks.enqueue(new ProgressTask(x, this));
19185 Pending.prototype.fail = function(context) {
19186 var c = typeof context === 'undefined' ? this.context : context;
19187 this.resolved && this.handler.join().fail(c);
19190 Pending.prototype._report = function(context) {
19191 this.resolved && this.handler.join()._report(context);
19194 Pending.prototype._unreport = function() {
19195 this.resolved && this.handler.join()._unreport();
19199 * Wrap another handler and force it into a future stack
19200 * @param {object} handler
19203 function Async(handler) {
19204 this.handler = handler;
19207 inherit(Handler, Async);
19209 Async.prototype.when = function(continuation) {
19210 tasks.enqueue(new ContinuationTask(continuation, this));
19213 Async.prototype._report = function(context) {
19214 this.join()._report(context);
19217 Async.prototype._unreport = function() {
19218 this.join()._unreport();
19222 * Handler that wraps an untrusted thenable and assimilates it in a future stack
19223 * @param {function} then
19224 * @param {{then: function}} thenable
19227 function Thenable(then, thenable) {
19228 Pending.call(this);
19229 tasks.enqueue(new AssimilateTask(then, thenable, this));
19232 inherit(Pending, Thenable);
19235 * Handler for a fulfilled promise
19236 * @param {*} x fulfillment value
19239 function Fulfilled(x) {
19240 Promise.createContext(this);
19244 inherit(Handler, Fulfilled);
19246 Fulfilled.prototype._state = 1;
19248 Fulfilled.prototype.fold = function(f, z, c, to) {
19249 runContinuation3(f, z, this, c, to);
19252 Fulfilled.prototype.when = function(cont) {
19253 runContinuation1(cont.fulfilled, this, cont.receiver, cont.resolver);
19259 * Handler for a rejected promise
19260 * @param {*} x rejection reason
19263 function Rejected(x) {
19264 Promise.createContext(this);
19266 this.id = ++errorId;
19268 this.handled = false;
19269 this.reported = false;
19274 inherit(Handler, Rejected);
19276 Rejected.prototype._state = -1;
19278 Rejected.prototype.fold = function(f, z, c, to) {
19282 Rejected.prototype.when = function(cont) {
19283 if(typeof cont.rejected === 'function') {
19286 runContinuation1(cont.rejected, this, cont.receiver, cont.resolver);
19289 Rejected.prototype._report = function(context) {
19290 tasks.afterQueue(new ReportTask(this, context));
19293 Rejected.prototype._unreport = function() {
19297 this.handled = true;
19298 tasks.afterQueue(new UnreportTask(this));
19301 Rejected.prototype.fail = function(context) {
19302 this.reported = true;
19303 emitRejection('unhandledRejection', this);
19304 Promise.onFatalRejection(this, context === void 0 ? this.context : context);
19307 function ReportTask(rejection, context) {
19308 this.rejection = rejection;
19309 this.context = context;
19312 ReportTask.prototype.run = function() {
19313 if(!this.rejection.handled && !this.rejection.reported) {
19314 this.rejection.reported = true;
19315 emitRejection('unhandledRejection', this.rejection) ||
19316 Promise.onPotentiallyUnhandledRejection(this.rejection, this.context);
19320 function UnreportTask(rejection) {
19321 this.rejection = rejection;
19324 UnreportTask.prototype.run = function() {
19325 if(this.rejection.reported) {
19326 emitRejection('rejectionHandled', this.rejection) ||
19327 Promise.onPotentiallyUnhandledRejectionHandled(this.rejection);
19331 // Unhandled rejection hooks
19332 // By default, everything is a noop
19334 Promise.createContext
19335 = Promise.enterContext
19336 = Promise.exitContext
19337 = Promise.onPotentiallyUnhandledRejection
19338 = Promise.onPotentiallyUnhandledRejectionHandled
19339 = Promise.onFatalRejection
19342 // Errors and singletons
19344 var foreverPendingHandler = new Handler();
19345 var foreverPendingPromise = new Promise(Handler, foreverPendingHandler);
19348 return new Rejected(new TypeError('Promise cycle'));
19354 * Run a single consumer
19357 function ContinuationTask(continuation, handler) {
19358 this.continuation = continuation;
19359 this.handler = handler;
19362 ContinuationTask.prototype.run = function() {
19363 this.handler.join().when(this.continuation);
19367 * Run a queue of progress handlers
19370 function ProgressTask(value, handler) {
19371 this.handler = handler;
19372 this.value = value;
19375 ProgressTask.prototype.run = function() {
19376 var q = this.handler.consumers;
19381 for (var c, i = 0; i < q.length; ++i) {
19383 runNotify(c.progress, this.value, this.handler, c.receiver, c.resolver);
19388 * Assimilate a thenable, sending it's value to resolver
19389 * @param {function} then
19390 * @param {object|function} thenable
19391 * @param {object} resolver
19394 function AssimilateTask(then, thenable, resolver) {
19396 this.thenable = thenable;
19397 this.resolver = resolver;
19400 AssimilateTask.prototype.run = function() {
19401 var h = this.resolver;
19402 tryAssimilate(this._then, this.thenable, _resolve, _reject, _notify);
19404 function _resolve(x) { h.resolve(x); }
19405 function _reject(x) { h.reject(x); }
19406 function _notify(x) { h.notify(x); }
19409 function tryAssimilate(then, thenable, resolve, reject, notify) {
19411 then.call(thenable, resolve, reject, notify);
19418 * Fold a handler value with z
19421 function Fold(f, z, c, to) {
19422 this.f = f; this.z = z; this.c = c; this.to = to;
19423 this.resolver = failIfRejected;
19424 this.receiver = this;
19427 Fold.prototype.fulfilled = function(x) {
19428 this.f.call(this.c, this.z, x, this.to);
19431 Fold.prototype.rejected = function(x) {
19435 Fold.prototype.progress = function(x) {
19443 * @returns {boolean} true iff x is a trusted Promise
19445 function isPromise(x) {
19446 return x instanceof Promise;
19450 * Test just enough to rule out primitives, in order to take faster
19451 * paths in some code
19453 * @returns {boolean} false iff x is guaranteed *not* to be a thenable
19455 function maybeThenable(x) {
19456 return (typeof x === 'object' || typeof x === 'function') && x !== null;
19459 function runContinuation1(f, h, receiver, next) {
19460 if(typeof f !== 'function') {
19461 return next.become(h);
19464 Promise.enterContext(h);
19465 tryCatchReject(f, h.value, receiver, next);
19466 Promise.exitContext();
19469 function runContinuation3(f, x, h, receiver, next) {
19470 if(typeof f !== 'function') {
19471 return next.become(h);
19474 Promise.enterContext(h);
19475 tryCatchReject3(f, x, h.value, receiver, next);
19476 Promise.exitContext();
19482 function runNotify(f, x, h, receiver, next) {
19483 if(typeof f !== 'function') {
19484 return next.notify(x);
19487 Promise.enterContext(h);
19488 tryCatchReturn(f, x, receiver, next);
19489 Promise.exitContext();
19492 function tryCatch2(f, a, b) {
19501 * Return f.call(thisArg, x), or if it throws return a rejected promise for
19502 * the thrown exception
19504 function tryCatchReject(f, x, thisArg, next) {
19506 next.become(getHandler(f.call(thisArg, x)));
19508 next.become(new Rejected(e));
19513 * Same as above, but includes the extra argument parameter.
19515 function tryCatchReject3(f, x, y, thisArg, next) {
19517 f.call(thisArg, x, y, next);
19519 next.become(new Rejected(e));
19525 * Return f.call(thisArg, x), or if it throws, *return* the exception
19527 function tryCatchReturn(f, x, thisArg, next) {
19529 next.notify(f.call(thisArg, x));
19535 function inherit(Parent, Child) {
19536 Child.prototype = objectCreate(Parent.prototype);
19537 Child.prototype.constructor = Child;
19540 function snd(x, y) {
19546 function hasCustomEvent() {
19547 if(typeof CustomEvent === 'function') {
19549 var ev = new CustomEvent('unhandledRejection');
19550 return ev instanceof CustomEvent;
19551 } catch (ignoredException) {}
19556 function hasInternetExplorerCustomEvent() {
19557 if(typeof document !== 'undefined' && typeof document.createEvent === 'function') {
19559 // Try to create one event to make sure it's supported
19560 var ev = document.createEvent('CustomEvent');
19561 ev.initCustomEvent('eventType', false, true, {});
19563 } catch (ignoredException) {}
19568 function initEmitRejection() {
19569 /*global process, self, CustomEvent*/
19570 if(typeof process !== 'undefined' && process !== null
19571 && typeof process.emit === 'function') {
19572 // Returning falsy here means to call the default
19573 // onPotentiallyUnhandledRejection API. This is safe even in
19574 // browserify since process.emit always returns falsy in browserify:
19575 // https://github.com/defunctzombie/node-process/blob/master/browser.js#L40-L46
19576 return function(type, rejection) {
19577 return type === 'unhandledRejection'
19578 ? process.emit(type, rejection.value, rejection)
19579 : process.emit(type, rejection);
19581 } else if(typeof self !== 'undefined' && hasCustomEvent()) {
19582 return (function (self, CustomEvent) {
19583 return function (type, rejection) {
19584 var ev = new CustomEvent(type, {
19586 reason: rejection.value,
19593 return !self.dispatchEvent(ev);
19595 }(self, CustomEvent));
19596 } else if(typeof self !== 'undefined' && hasInternetExplorerCustomEvent()) {
19597 return (function(self, document) {
19598 return function(type, rejection) {
19599 var ev = document.createEvent('CustomEvent');
19600 ev.initCustomEvent(type, false, true, {
19601 reason: rejection.value,
19605 return !self.dispatchEvent(ev);
19607 }(self, document));
19616 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
19618 }).call(this,require('_process'))
19620 },{"_process":6}],222:[function(require,module,exports){
19621 /** @license MIT License (c) copyright 2010-2014 original author or authors */
19622 /** @author Brian Cavalier */
19623 /** @author John Hann */
19625 (function(define) { 'use strict';
19626 define(function() {
19629 pending: toPendingState,
19630 fulfilled: toFulfilledState,
19631 rejected: toRejectedState,
19635 function toPendingState() {
19636 return { state: 'pending' };
19639 function toRejectedState(e) {
19640 return { state: 'rejected', reason: e };
19643 function toFulfilledState(x) {
19644 return { state: 'fulfilled', value: x };
19647 function inspect(handler) {
19648 var state = handler.state();
19649 return state === 0 ? toPendingState()
19650 : state > 0 ? toFulfilledState(handler.value)
19651 : toRejectedState(handler.value);
19655 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
19657 },{}],223:[function(require,module,exports){
19658 /** @license MIT License (c) copyright 2010-2014 original author or authors */
19661 * Promises/A+ and when() implementation
19662 * when is part of the cujoJS family of libraries (http://cujojs.com/)
19663 * @author Brian Cavalier
19664 * @author John Hann
19666 (function(define) { 'use strict';
19667 define(function (require) {
19669 var timed = require('./lib/decorators/timed');
19670 var array = require('./lib/decorators/array');
19671 var flow = require('./lib/decorators/flow');
19672 var fold = require('./lib/decorators/fold');
19673 var inspect = require('./lib/decorators/inspect');
19674 var generate = require('./lib/decorators/iterate');
19675 var progress = require('./lib/decorators/progress');
19676 var withThis = require('./lib/decorators/with');
19677 var unhandledRejection = require('./lib/decorators/unhandledRejection');
19678 var TimeoutError = require('./lib/TimeoutError');
19680 var Promise = [array, flow, fold, generate, progress,
19681 inspect, withThis, timed, unhandledRejection]
19682 .reduce(function(Promise, feature) {
19683 return feature(Promise);
19684 }, require('./lib/Promise'));
19686 var apply = require('./lib/apply')(Promise);
19690 when.promise = promise; // Create a pending promise
19691 when.resolve = Promise.resolve; // Create a resolved promise
19692 when.reject = Promise.reject; // Create a rejected promise
19694 when.lift = lift; // lift a function to return promises
19695 when['try'] = attempt; // call a function and return a promise
19696 when.attempt = attempt; // alias for when.try
19698 when.iterate = Promise.iterate; // DEPRECATED (use cujojs/most streams) Generate a stream of promises
19699 when.unfold = Promise.unfold; // DEPRECATED (use cujojs/most streams) Generate a stream of promises
19701 when.join = join; // Join 2 or more promises
19703 when.all = all; // Resolve a list of promises
19704 when.settle = settle; // Settle a list of promises
19706 when.any = lift(Promise.any); // One-winner race
19707 when.some = lift(Promise.some); // Multi-winner race
19708 when.race = lift(Promise.race); // First-to-settle race
19710 when.map = map; // Array.map() for promises
19711 when.filter = filter; // Array.filter() for promises
19712 when.reduce = lift(Promise.reduce); // Array.reduce() for promises
19713 when.reduceRight = lift(Promise.reduceRight); // Array.reduceRight() for promises
19715 when.isPromiseLike = isPromiseLike; // Is something promise-like, aka thenable
19717 when.Promise = Promise; // Promise constructor
19718 when.defer = defer; // Create a {promise, resolve, reject} tuple
19722 when.TimeoutError = TimeoutError;
19725 * Get a trusted promise for x, or by transforming x with onFulfilled
19728 * @param {function?} onFulfilled callback to be called when x is
19729 * successfully fulfilled. If promiseOrValue is an immediate value, callback
19730 * will be invoked immediately.
19731 * @param {function?} onRejected callback to be called when x is
19733 * @param {function?} onProgress callback to be called when progress updates
19734 * are issued for x. @deprecated
19735 * @returns {Promise} a new promise that will fulfill with the return
19736 * value of callback or errback or the completion value of promiseOrValue if
19737 * callback and/or errback is not supplied.
19739 function when(x, onFulfilled, onRejected, onProgress) {
19740 var p = Promise.resolve(x);
19741 if (arguments.length < 2) {
19745 return p.then(onFulfilled, onRejected, onProgress);
19749 * Creates a new promise whose fate is determined by resolver.
19750 * @param {function} resolver function(resolve, reject, notify)
19751 * @returns {Promise} promise whose fate is determine by resolver
19753 function promise(resolver) {
19754 return new Promise(resolver);
19758 * Lift the supplied function, creating a version of f that returns
19759 * promises, and accepts promises as arguments.
19760 * @param {function} f
19761 * @returns {Function} version of f that returns promises
19764 return function() {
19765 for(var i=0, l=arguments.length, a=new Array(l); i<l; ++i) {
19766 a[i] = arguments[i];
19768 return apply(f, this, a);
19773 * Call f in a future turn, with the supplied args, and return a promise
19775 * @param {function} f
19776 * @returns {Promise}
19778 function attempt(f /*, args... */) {
19779 /*jshint validthis:true */
19780 for(var i=0, l=arguments.length-1, a=new Array(l); i<l; ++i) {
19781 a[i] = arguments[i+1];
19783 return apply(f, this, a);
19787 * Creates a {promise, resolver} pair, either or both of which
19788 * may be given out safely to consumers.
19789 * @return {{promise: Promise, resolve: function, reject: function, notify: function}}
19792 return new Deferred();
19795 function Deferred() {
19796 var p = Promise._defer();
19798 function resolve(x) { p._handler.resolve(x); }
19799 function reject(x) { p._handler.reject(x); }
19800 function notify(x) { p._handler.notify(x); }
19803 this.resolve = resolve;
19804 this.reject = reject;
19805 this.notify = notify;
19806 this.resolver = { resolve: resolve, reject: reject, notify: notify };
19810 * Determines if x is promise-like, i.e. a thenable object
19811 * NOTE: Will return true for *any thenable object*, and isn't truly
19812 * safe, since it may attempt to access the `then` property of x (i.e.
19813 * clever/malicious getters may do weird things)
19814 * @param {*} x anything
19815 * @returns {boolean} true if x is promise-like
19817 function isPromiseLike(x) {
19818 return x && typeof x.then === 'function';
19822 * Return a promise that will resolve only once all the supplied arguments
19823 * have resolved. The resolution value of the returned promise will be an array
19824 * containing the resolution values of each of the arguments.
19825 * @param {...*} arguments may be a mix of promises and values
19826 * @returns {Promise}
19828 function join(/* ...promises */) {
19829 return Promise.all(arguments);
19833 * Return a promise that will fulfill once all input promises have
19834 * fulfilled, or reject when any one input promise rejects.
19835 * @param {array|Promise} promises array (or promise for an array) of promises
19836 * @returns {Promise}
19838 function all(promises) {
19839 return when(promises, Promise.all);
19843 * Return a promise that will always fulfill with an array containing
19844 * the outcome states of all input promises. The returned promise
19845 * will only reject if `promises` itself is a rejected promise.
19846 * @param {array|Promise} promises array (or promise for an array) of promises
19847 * @returns {Promise} promise for array of settled state descriptors
19849 function settle(promises) {
19850 return when(promises, Promise.settle);
19854 * Promise-aware array map function, similar to `Array.prototype.map()`,
19855 * but input array may contain promises or values.
19856 * @param {Array|Promise} promises array of anything, may contain promises and values
19857 * @param {function(x:*, index:Number):*} mapFunc map function which may
19858 * return a promise or value
19859 * @returns {Promise} promise that will fulfill with an array of mapped values
19860 * or reject if any input promise rejects.
19862 function map(promises, mapFunc) {
19863 return when(promises, function(promises) {
19864 return Promise.map(promises, mapFunc);
19869 * Filter the provided array of promises using the provided predicate. Input may
19870 * contain promises and values
19871 * @param {Array|Promise} promises array of promises and values
19872 * @param {function(x:*, index:Number):boolean} predicate filtering predicate.
19873 * Must return truthy (or promise for truthy) for items to retain.
19874 * @returns {Promise} promise that will fulfill with an array containing all items
19875 * for which predicate returned truthy.
19877 function filter(promises, predicate) {
19878 return when(promises, function(promises) {
19879 return Promise.filter(promises, predicate);
19885 })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
19887 },{"./lib/Promise":206,"./lib/TimeoutError":208,"./lib/apply":209,"./lib/decorators/array":210,"./lib/decorators/flow":211,"./lib/decorators/fold":212,"./lib/decorators/inspect":213,"./lib/decorators/iterate":214,"./lib/decorators/progress":215,"./lib/decorators/timed":216,"./lib/decorators/unhandledRejection":217,"./lib/decorators/with":218}],224:[function(require,module,exports){
19888 var nativeIsArray = Array.isArray
19889 var toString = Object.prototype.toString
19891 module.exports = nativeIsArray || isArray
19893 function isArray(obj) {
19894 return toString.call(obj) === "[object Array]"
19897 },{}],225:[function(require,module,exports){
19899 Object.defineProperty(exports, "__esModule", { value: true });
19900 var APIv3_1 = require("./api/APIv3");
19901 exports.APIv3 = APIv3_1.APIv3;
19902 var ModelCreator_1 = require("./api/ModelCreator");
19903 exports.ModelCreator = ModelCreator_1.ModelCreator;
19905 },{"./api/APIv3":238,"./api/ModelCreator":239}],226:[function(require,module,exports){
19907 function __export(m) {
19908 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
19910 Object.defineProperty(exports, "__esModule", { value: true });
19911 var Component_1 = require("./component/Component");
19912 exports.Component = Component_1.Component;
19913 var ComponentService_1 = require("./component/ComponentService");
19914 exports.ComponentService = ComponentService_1.ComponentService;
19915 var HandlerBase_1 = require("./component/utils/HandlerBase");
19916 exports.HandlerBase = HandlerBase_1.HandlerBase;
19917 var AttributionComponent_1 = require("./component/AttributionComponent");
19918 exports.AttributionComponent = AttributionComponent_1.AttributionComponent;
19919 var BackgroundComponent_1 = require("./component/BackgroundComponent");
19920 exports.BackgroundComponent = BackgroundComponent_1.BackgroundComponent;
19921 var BearingComponent_1 = require("./component/BearingComponent");
19922 exports.BearingComponent = BearingComponent_1.BearingComponent;
19923 var CacheComponent_1 = require("./component/CacheComponent");
19924 exports.CacheComponent = CacheComponent_1.CacheComponent;
19925 var CoverComponent_1 = require("./component/CoverComponent");
19926 exports.CoverComponent = CoverComponent_1.CoverComponent;
19927 var DebugComponent_1 = require("./component/DebugComponent");
19928 exports.DebugComponent = DebugComponent_1.DebugComponent;
19929 var DirectionComponent_1 = require("./component/direction/DirectionComponent");
19930 exports.DirectionComponent = DirectionComponent_1.DirectionComponent;
19931 var DirectionDOMCalculator_1 = require("./component/direction/DirectionDOMCalculator");
19932 exports.DirectionDOMCalculator = DirectionDOMCalculator_1.DirectionDOMCalculator;
19933 var DirectionDOMRenderer_1 = require("./component/direction/DirectionDOMRenderer");
19934 exports.DirectionDOMRenderer = DirectionDOMRenderer_1.DirectionDOMRenderer;
19935 var ImageComponent_1 = require("./component/ImageComponent");
19936 exports.ImageComponent = ImageComponent_1.ImageComponent;
19937 var KeyboardComponent_1 = require("./component/keyboard/KeyboardComponent");
19938 exports.KeyboardComponent = KeyboardComponent_1.KeyboardComponent;
19939 var KeyZoomHandler_1 = require("./component/keyboard/KeyZoomHandler");
19940 exports.KeyZoomHandler = KeyZoomHandler_1.KeyZoomHandler;
19941 var KeySequenceNavigationHandler_1 = require("./component/keyboard/KeySequenceNavigationHandler");
19942 exports.KeySequenceNavigationHandler = KeySequenceNavigationHandler_1.KeySequenceNavigationHandler;
19943 var KeySpatialNavigationHandler_1 = require("./component/keyboard/KeySpatialNavigationHandler");
19944 exports.KeySpatialNavigationHandler = KeySpatialNavigationHandler_1.KeySpatialNavigationHandler;
19945 var LoadingComponent_1 = require("./component/LoadingComponent");
19946 exports.LoadingComponent = LoadingComponent_1.LoadingComponent;
19947 var Marker_1 = require("./component/marker/marker/Marker");
19948 exports.Marker = Marker_1.Marker;
19949 var MarkerComponent_1 = require("./component/marker/MarkerComponent");
19950 exports.MarkerComponent = MarkerComponent_1.MarkerComponent;
19951 var MarkerScene_1 = require("./component/marker/MarkerScene");
19952 exports.MarkerScene = MarkerScene_1.MarkerScene;
19953 var MarkerSet_1 = require("./component/marker/MarkerSet");
19954 exports.MarkerSet = MarkerSet_1.MarkerSet;
19955 var MouseComponent_1 = require("./component/mouse/MouseComponent");
19956 exports.MouseComponent = MouseComponent_1.MouseComponent;
19957 var BounceHandler_1 = require("./component/mouse/BounceHandler");
19958 exports.BounceHandler = BounceHandler_1.BounceHandler;
19959 var DragPanHandler_1 = require("./component/mouse/DragPanHandler");
19960 exports.DragPanHandler = DragPanHandler_1.DragPanHandler;
19961 var DoubleClickZoomHandler_1 = require("./component/mouse/DoubleClickZoomHandler");
19962 exports.DoubleClickZoomHandler = DoubleClickZoomHandler_1.DoubleClickZoomHandler;
19963 var ScrollZoomHandler_1 = require("./component/mouse/ScrollZoomHandler");
19964 exports.ScrollZoomHandler = ScrollZoomHandler_1.ScrollZoomHandler;
19965 var TouchZoomHandler_1 = require("./component/mouse/TouchZoomHandler");
19966 exports.TouchZoomHandler = TouchZoomHandler_1.TouchZoomHandler;
19967 var Popup_1 = require("./component/popup/popup/Popup");
19968 exports.Popup = Popup_1.Popup;
19969 var PopupComponent_1 = require("./component/popup/PopupComponent");
19970 exports.PopupComponent = PopupComponent_1.PopupComponent;
19971 var NavigationComponent_1 = require("./component/NavigationComponent");
19972 exports.NavigationComponent = NavigationComponent_1.NavigationComponent;
19973 var RouteComponent_1 = require("./component/RouteComponent");
19974 exports.RouteComponent = RouteComponent_1.RouteComponent;
19975 var SequenceComponent_1 = require("./component/sequence/SequenceComponent");
19976 exports.SequenceComponent = SequenceComponent_1.SequenceComponent;
19977 var SequenceDOMRenderer_1 = require("./component/sequence/SequenceDOMRenderer");
19978 exports.SequenceDOMRenderer = SequenceDOMRenderer_1.SequenceDOMRenderer;
19979 var SequenceDOMInteraction_1 = require("./component/sequence/SequenceDOMInteraction");
19980 exports.SequenceDOMInteraction = SequenceDOMInteraction_1.SequenceDOMInteraction;
19981 var ImagePlaneComponent_1 = require("./component/imageplane/ImagePlaneComponent");
19982 exports.ImagePlaneComponent = ImagePlaneComponent_1.ImagePlaneComponent;
19983 var ImagePlaneFactory_1 = require("./component/imageplane/ImagePlaneFactory");
19984 exports.ImagePlaneFactory = ImagePlaneFactory_1.ImagePlaneFactory;
19985 var ImagePlaneGLRenderer_1 = require("./component/imageplane/ImagePlaneGLRenderer");
19986 exports.ImagePlaneGLRenderer = ImagePlaneGLRenderer_1.ImagePlaneGLRenderer;
19987 var ImagePlaneScene_1 = require("./component/imageplane/ImagePlaneScene");
19988 exports.ImagePlaneScene = ImagePlaneScene_1.ImagePlaneScene;
19989 var ImagePlaneShaders_1 = require("./component/imageplane/ImagePlaneShaders");
19990 exports.ImagePlaneShaders = ImagePlaneShaders_1.ImagePlaneShaders;
19991 var SimpleMarker_1 = require("./component/marker/marker/SimpleMarker");
19992 exports.SimpleMarker = SimpleMarker_1.SimpleMarker;
19993 var CircleMarker_1 = require("./component/marker/marker/CircleMarker");
19994 exports.CircleMarker = CircleMarker_1.CircleMarker;
19995 var SliderComponent_1 = require("./component/imageplane/SliderComponent");
19996 exports.SliderComponent = SliderComponent_1.SliderComponent;
19997 var StatsComponent_1 = require("./component/StatsComponent");
19998 exports.StatsComponent = StatsComponent_1.StatsComponent;
19999 var Tag_1 = require("./component/tag/tag/Tag");
20000 exports.Tag = Tag_1.Tag;
20001 var OutlineTag_1 = require("./component/tag/tag/OutlineTag");
20002 exports.OutlineTag = OutlineTag_1.OutlineTag;
20003 var RenderTag_1 = require("./component/tag/tag/RenderTag");
20004 exports.RenderTag = RenderTag_1.RenderTag;
20005 var OutlineRenderTag_1 = require("./component/tag/tag/OutlineRenderTag");
20006 exports.OutlineRenderTag = OutlineRenderTag_1.OutlineRenderTag;
20007 var OutlineCreateTag_1 = require("./component/tag/tag/OutlineCreateTag");
20008 exports.OutlineCreateTag = OutlineCreateTag_1.OutlineCreateTag;
20009 var SpotTag_1 = require("./component/tag/tag/SpotTag");
20010 exports.SpotTag = SpotTag_1.SpotTag;
20011 var SpotRenderTag_1 = require("./component/tag/tag/SpotRenderTag");
20012 exports.SpotRenderTag = SpotRenderTag_1.SpotRenderTag;
20013 var TagComponent_1 = require("./component/tag/TagComponent");
20014 exports.TagComponent = TagComponent_1.TagComponent;
20015 var TagCreator_1 = require("./component/tag/TagCreator");
20016 exports.TagCreator = TagCreator_1.TagCreator;
20017 var TagDOMRenderer_1 = require("./component/tag/TagDOMRenderer");
20018 exports.TagDOMRenderer = TagDOMRenderer_1.TagDOMRenderer;
20019 var TagMode_1 = require("./component/tag/TagMode");
20020 exports.TagMode = TagMode_1.TagMode;
20021 var TagOperation_1 = require("./component/tag/TagOperation");
20022 exports.TagOperation = TagOperation_1.TagOperation;
20023 var TagScene_1 = require("./component/tag/TagScene");
20024 exports.TagScene = TagScene_1.TagScene;
20025 var TagSet_1 = require("./component/tag/TagSet");
20026 exports.TagSet = TagSet_1.TagSet;
20027 var Geometry_1 = require("./component/tag/geometry/Geometry");
20028 exports.Geometry = Geometry_1.Geometry;
20029 var VertexGeometry_1 = require("./component/tag/geometry/VertexGeometry");
20030 exports.VertexGeometry = VertexGeometry_1.VertexGeometry;
20031 var RectGeometry_1 = require("./component/tag/geometry/RectGeometry");
20032 exports.RectGeometry = RectGeometry_1.RectGeometry;
20033 var PointGeometry_1 = require("./component/tag/geometry/PointGeometry");
20034 exports.PointGeometry = PointGeometry_1.PointGeometry;
20035 var PolygonGeometry_1 = require("./component/tag/geometry/PolygonGeometry");
20036 exports.PolygonGeometry = PolygonGeometry_1.PolygonGeometry;
20037 var GeometryTagError_1 = require("./component/tag/error/GeometryTagError");
20038 exports.GeometryTagError = GeometryTagError_1.GeometryTagError;
20039 __export(require("./component/interfaces/interfaces"));
20041 },{"./component/AttributionComponent":240,"./component/BackgroundComponent":241,"./component/BearingComponent":242,"./component/CacheComponent":243,"./component/Component":244,"./component/ComponentService":245,"./component/CoverComponent":246,"./component/DebugComponent":247,"./component/ImageComponent":248,"./component/LoadingComponent":249,"./component/NavigationComponent":250,"./component/RouteComponent":251,"./component/StatsComponent":252,"./component/direction/DirectionComponent":253,"./component/direction/DirectionDOMCalculator":254,"./component/direction/DirectionDOMRenderer":255,"./component/imageplane/ImagePlaneComponent":256,"./component/imageplane/ImagePlaneFactory":257,"./component/imageplane/ImagePlaneGLRenderer":258,"./component/imageplane/ImagePlaneScene":259,"./component/imageplane/ImagePlaneShaders":260,"./component/imageplane/SliderComponent":261,"./component/interfaces/interfaces":263,"./component/keyboard/KeySequenceNavigationHandler":264,"./component/keyboard/KeySpatialNavigationHandler":265,"./component/keyboard/KeyZoomHandler":266,"./component/keyboard/KeyboardComponent":267,"./component/marker/MarkerComponent":269,"./component/marker/MarkerScene":270,"./component/marker/MarkerSet":271,"./component/marker/marker/CircleMarker":272,"./component/marker/marker/Marker":273,"./component/marker/marker/SimpleMarker":274,"./component/mouse/BounceHandler":275,"./component/mouse/DoubleClickZoomHandler":276,"./component/mouse/DragPanHandler":277,"./component/mouse/MouseComponent":278,"./component/mouse/ScrollZoomHandler":279,"./component/mouse/TouchZoomHandler":280,"./component/popup/PopupComponent":282,"./component/popup/popup/Popup":283,"./component/sequence/SequenceComponent":284,"./component/sequence/SequenceDOMInteraction":285,"./component/sequence/SequenceDOMRenderer":286,"./component/tag/TagComponent":288,"./component/tag/TagCreator":289,"./component/tag/TagDOMRenderer":290,"./component/tag/TagMode":291,"./component/tag/TagOperation":292,"./component/tag/TagScene":293,"./component/tag/TagSet":294,"./component/tag/error/GeometryTagError":295,"./component/tag/geometry/Geometry":296,"./component/tag/geometry/PointGeometry":297,"./component/tag/geometry/PolygonGeometry":298,"./component/tag/geometry/RectGeometry":299,"./component/tag/geometry/VertexGeometry":300,"./component/tag/tag/OutlineCreateTag":301,"./component/tag/tag/OutlineRenderTag":302,"./component/tag/tag/OutlineTag":303,"./component/tag/tag/RenderTag":304,"./component/tag/tag/SpotRenderTag":305,"./component/tag/tag/SpotTag":306,"./component/tag/tag/Tag":307,"./component/utils/HandlerBase":308}],227:[function(require,module,exports){
20043 Object.defineProperty(exports, "__esModule", { value: true });
20044 var EdgeDirection_1 = require("./graph/edge/EdgeDirection");
20045 exports.EdgeDirection = EdgeDirection_1.EdgeDirection;
20046 var EdgeCalculatorSettings_1 = require("./graph/edge/EdgeCalculatorSettings");
20047 exports.EdgeCalculatorSettings = EdgeCalculatorSettings_1.EdgeCalculatorSettings;
20048 var EdgeCalculatorDirections_1 = require("./graph/edge/EdgeCalculatorDirections");
20049 exports.EdgeCalculatorDirections = EdgeCalculatorDirections_1.EdgeCalculatorDirections;
20050 var EdgeCalculatorCoefficients_1 = require("./graph/edge/EdgeCalculatorCoefficients");
20051 exports.EdgeCalculatorCoefficients = EdgeCalculatorCoefficients_1.EdgeCalculatorCoefficients;
20052 var EdgeCalculator_1 = require("./graph/edge/EdgeCalculator");
20053 exports.EdgeCalculator = EdgeCalculator_1.EdgeCalculator;
20055 },{"./graph/edge/EdgeCalculator":326,"./graph/edge/EdgeCalculatorCoefficients":327,"./graph/edge/EdgeCalculatorDirections":328,"./graph/edge/EdgeCalculatorSettings":329,"./graph/edge/EdgeDirection":330}],228:[function(require,module,exports){
20057 Object.defineProperty(exports, "__esModule", { value: true });
20058 var ArgumentMapillaryError_1 = require("./error/ArgumentMapillaryError");
20059 exports.ArgumentMapillaryError = ArgumentMapillaryError_1.ArgumentMapillaryError;
20060 var GraphMapillaryError_1 = require("./error/GraphMapillaryError");
20061 exports.GraphMapillaryError = GraphMapillaryError_1.GraphMapillaryError;
20062 var MapillaryError_1 = require("./error/MapillaryError");
20063 exports.MapillaryError = MapillaryError_1.MapillaryError;
20065 },{"./error/ArgumentMapillaryError":309,"./error/GraphMapillaryError":310,"./error/MapillaryError":311}],229:[function(require,module,exports){
20067 Object.defineProperty(exports, "__esModule", { value: true });
20068 var Camera_1 = require("./geo/Camera");
20069 exports.Camera = Camera_1.Camera;
20070 var GeoCoords_1 = require("./geo/GeoCoords");
20071 exports.GeoCoords = GeoCoords_1.GeoCoords;
20072 var ViewportCoords_1 = require("./geo/ViewportCoords");
20073 exports.ViewportCoords = ViewportCoords_1.ViewportCoords;
20074 var Spatial_1 = require("./geo/Spatial");
20075 exports.Spatial = Spatial_1.Spatial;
20076 var Transform_1 = require("./geo/Transform");
20077 exports.Transform = Transform_1.Transform;
20079 },{"./geo/Camera":312,"./geo/GeoCoords":313,"./geo/Spatial":314,"./geo/Transform":315,"./geo/ViewportCoords":316}],230:[function(require,module,exports){
20081 Object.defineProperty(exports, "__esModule", { value: true });
20082 var FilterCreator_1 = require("./graph/FilterCreator");
20083 exports.FilterCreator = FilterCreator_1.FilterCreator;
20084 var Graph_1 = require("./graph/Graph");
20085 exports.Graph = Graph_1.Graph;
20086 var GraphCalculator_1 = require("./graph/GraphCalculator");
20087 exports.GraphCalculator = GraphCalculator_1.GraphCalculator;
20088 var GraphService_1 = require("./graph/GraphService");
20089 exports.GraphService = GraphService_1.GraphService;
20090 var ImageLoadingService_1 = require("./graph/ImageLoadingService");
20091 exports.ImageLoadingService = ImageLoadingService_1.ImageLoadingService;
20092 var MeshReader_1 = require("./graph/MeshReader");
20093 exports.MeshReader = MeshReader_1.MeshReader;
20094 var Node_1 = require("./graph/Node");
20095 exports.Node = Node_1.Node;
20096 var NodeCache_1 = require("./graph/NodeCache");
20097 exports.NodeCache = NodeCache_1.NodeCache;
20098 var Sequence_1 = require("./graph/Sequence");
20099 exports.Sequence = Sequence_1.Sequence;
20101 },{"./graph/FilterCreator":317,"./graph/Graph":318,"./graph/GraphCalculator":319,"./graph/GraphService":320,"./graph/ImageLoadingService":321,"./graph/MeshReader":322,"./graph/Node":323,"./graph/NodeCache":324,"./graph/Sequence":325}],231:[function(require,module,exports){
20104 * MapillaryJS is a WebGL JavaScript library for exploring street level imagery
20107 function __export(m) {
20108 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
20110 Object.defineProperty(exports, "__esModule", { value: true });
20111 __export(require("./Support"));
20112 var Edge_1 = require("./Edge");
20113 exports.EdgeDirection = Edge_1.EdgeDirection;
20114 var Render_1 = require("./Render");
20115 exports.RenderMode = Render_1.RenderMode;
20116 var Viewer_1 = require("./Viewer");
20117 exports.Alignment = Viewer_1.Alignment;
20118 exports.ImageSize = Viewer_1.ImageSize;
20119 exports.Viewer = Viewer_1.Viewer;
20120 var TagComponent = require("./component/tag/Tag");
20121 exports.TagComponent = TagComponent;
20122 var MarkerComponent = require("./component/marker/Marker");
20123 exports.MarkerComponent = MarkerComponent;
20124 var PopupComponent = require("./component/popup/Popup");
20125 exports.PopupComponent = PopupComponent;
20127 },{"./Edge":227,"./Render":232,"./Support":234,"./Viewer":237,"./component/marker/Marker":268,"./component/popup/Popup":281,"./component/tag/Tag":287}],232:[function(require,module,exports){
20129 Object.defineProperty(exports, "__esModule", { value: true });
20130 var DOMRenderer_1 = require("./render/DOMRenderer");
20131 exports.DOMRenderer = DOMRenderer_1.DOMRenderer;
20132 var GLRenderer_1 = require("./render/GLRenderer");
20133 exports.GLRenderer = GLRenderer_1.GLRenderer;
20134 var GLRenderStage_1 = require("./render/GLRenderStage");
20135 exports.GLRenderStage = GLRenderStage_1.GLRenderStage;
20136 var RenderCamera_1 = require("./render/RenderCamera");
20137 exports.RenderCamera = RenderCamera_1.RenderCamera;
20138 var RenderMode_1 = require("./render/RenderMode");
20139 exports.RenderMode = RenderMode_1.RenderMode;
20140 var RenderService_1 = require("./render/RenderService");
20141 exports.RenderService = RenderService_1.RenderService;
20143 },{"./render/DOMRenderer":331,"./render/GLRenderStage":332,"./render/GLRenderer":333,"./render/RenderCamera":334,"./render/RenderMode":335,"./render/RenderService":336}],233:[function(require,module,exports){
20145 Object.defineProperty(exports, "__esModule", { value: true });
20146 var State_1 = require("./state/State");
20147 exports.State = State_1.State;
20148 var StateBase_1 = require("./state/states/StateBase");
20149 exports.StateBase = StateBase_1.StateBase;
20150 var StateContext_1 = require("./state/StateContext");
20151 exports.StateContext = StateContext_1.StateContext;
20152 var StateService_1 = require("./state/StateService");
20153 exports.StateService = StateService_1.StateService;
20154 var TraversingState_1 = require("./state/states/TraversingState");
20155 exports.TraversingState = TraversingState_1.TraversingState;
20156 var WaitingState_1 = require("./state/states/WaitingState");
20157 exports.WaitingState = WaitingState_1.WaitingState;
20159 },{"./state/State":337,"./state/StateContext":338,"./state/StateService":339,"./state/states/StateBase":340,"./state/states/TraversingState":341,"./state/states/WaitingState":342}],234:[function(require,module,exports){
20161 Object.defineProperty(exports, "__esModule", { value: true });
20162 var support = require("./utils/Support");
20164 * Test whether the current browser supports the full
20165 * functionality of MapillaryJS.
20167 * @description The full functionality includes WebGL rendering.
20169 * @return {boolean}
20171 * @example `var supported = Mapillary.isSupported();`
20173 function isSupported() {
20174 return isFallbackSupported() &&
20175 support.isWebGLSupportedCached();
20177 exports.isSupported = isSupported;
20179 * Test whether the current browser supports the fallback
20180 * functionality of MapillaryJS.
20182 * @description The fallback functionality does not include WebGL
20183 * rendering, only 2D canvas rendering.
20185 * @return {boolean}
20187 * @example `var fallbackSupported = Mapillary.isFallbackSupported();`
20189 function isFallbackSupported() {
20190 return support.isBrowser() &&
20191 support.isArraySupported() &&
20192 support.isFunctionSupported() &&
20193 support.isJSONSupported() &&
20194 support.isObjectSupported();
20196 exports.isFallbackSupported = isFallbackSupported;
20198 },{"./utils/Support":349}],235:[function(require,module,exports){
20200 Object.defineProperty(exports, "__esModule", { value: true });
20201 var ImageTileLoader_1 = require("./tiles/ImageTileLoader");
20202 exports.ImageTileLoader = ImageTileLoader_1.ImageTileLoader;
20203 var ImageTileStore_1 = require("./tiles/ImageTileStore");
20204 exports.ImageTileStore = ImageTileStore_1.ImageTileStore;
20205 var TextureProvider_1 = require("./tiles/TextureProvider");
20206 exports.TextureProvider = TextureProvider_1.TextureProvider;
20207 var RegionOfInterestCalculator_1 = require("./tiles/RegionOfInterestCalculator");
20208 exports.RegionOfInterestCalculator = RegionOfInterestCalculator_1.RegionOfInterestCalculator;
20210 },{"./tiles/ImageTileLoader":343,"./tiles/ImageTileStore":344,"./tiles/RegionOfInterestCalculator":345,"./tiles/TextureProvider":346}],236:[function(require,module,exports){
20212 function __export(m) {
20213 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
20215 Object.defineProperty(exports, "__esModule", { value: true });
20216 var EventEmitter_1 = require("./utils/EventEmitter");
20217 exports.EventEmitter = EventEmitter_1.EventEmitter;
20218 var Settings_1 = require("./utils/Settings");
20219 exports.Settings = Settings_1.Settings;
20220 __export(require("./utils/Support"));
20221 var Urls_1 = require("./utils/Urls");
20222 exports.Urls = Urls_1.Urls;
20224 },{"./utils/EventEmitter":347,"./utils/Settings":348,"./utils/Support":349,"./utils/Urls":350}],237:[function(require,module,exports){
20226 Object.defineProperty(exports, "__esModule", { value: true });
20227 var Alignment_1 = require("./viewer/Alignment");
20228 exports.Alignment = Alignment_1.Alignment;
20229 var CacheService_1 = require("./viewer/CacheService");
20230 exports.CacheService = CacheService_1.CacheService;
20231 var ComponentController_1 = require("./viewer/ComponentController");
20232 exports.ComponentController = ComponentController_1.ComponentController;
20233 var Container_1 = require("./viewer/Container");
20234 exports.Container = Container_1.Container;
20235 var Observer_1 = require("./viewer/Observer");
20236 exports.Observer = Observer_1.Observer;
20237 var ImageSize_1 = require("./viewer/ImageSize");
20238 exports.ImageSize = ImageSize_1.ImageSize;
20239 var KeyboardService_1 = require("./viewer/KeyboardService");
20240 exports.KeyboardService = KeyboardService_1.KeyboardService;
20241 var LoadingService_1 = require("./viewer/LoadingService");
20242 exports.LoadingService = LoadingService_1.LoadingService;
20243 var MouseService_1 = require("./viewer/MouseService");
20244 exports.MouseService = MouseService_1.MouseService;
20245 var Navigator_1 = require("./viewer/Navigator");
20246 exports.Navigator = Navigator_1.Navigator;
20247 var Projection_1 = require("./viewer/Projection");
20248 exports.Projection = Projection_1.Projection;
20249 var SpriteService_1 = require("./viewer/SpriteService");
20250 exports.SpriteService = SpriteService_1.SpriteService;
20251 var TouchService_1 = require("./viewer/TouchService");
20252 exports.TouchService = TouchService_1.TouchService;
20253 var Viewer_1 = require("./viewer/Viewer");
20254 exports.Viewer = Viewer_1.Viewer;
20256 },{"./viewer/Alignment":351,"./viewer/CacheService":352,"./viewer/ComponentController":353,"./viewer/Container":354,"./viewer/ImageSize":355,"./viewer/KeyboardService":356,"./viewer/LoadingService":357,"./viewer/MouseService":358,"./viewer/Navigator":359,"./viewer/Observer":360,"./viewer/Projection":361,"./viewer/SpriteService":362,"./viewer/TouchService":363,"./viewer/Viewer":364}],238:[function(require,module,exports){
20258 /// <reference path="../../typings/index.d.ts" />
20259 Object.defineProperty(exports, "__esModule", { value: true });
20260 var Observable_1 = require("rxjs/Observable");
20261 require("rxjs/add/observable/defer");
20262 require("rxjs/add/observable/fromPromise");
20263 require("rxjs/add/operator/catch");
20264 require("rxjs/add/operator/map");
20265 var API_1 = require("../API");
20269 * @classdesc Provides methods for access of API v3.
20271 var APIv3 = (function () {
20273 * Create a new api v3 instance.
20275 * @param {number} clientId - Client id for API requests.
20276 * @param {number} [token] - Optional bearer token for API requests of
20277 * protected resources.
20278 * @param {ModelCreator} [creator] - Optional model creator instance.
20280 function APIv3(clientId, token, creator) {
20281 this._clientId = clientId;
20282 this._modelCreator = creator != null ? creator : new API_1.ModelCreator();
20283 this._model = this._modelCreator.createModel(clientId, token);
20284 this._pageCount = 999;
20285 this._pathImageByKey = "imageByKey";
20286 this._pathImageCloseTo = "imageCloseTo";
20287 this._pathImagesByH = "imagesByH";
20288 this._pathImageViewAdd = "imageViewAdd";
20289 this._pathSequenceByKey = "sequenceByKey";
20290 this._pathSequenceViewAdd = "sequenceViewAdd";
20291 this._propertiesCore = [
20296 this._propertiesFill = [
20301 this._propertiesKey = [
20304 this._propertiesSequence = [
20307 this._propertiesSpatial = [
20321 this._propertiesUser = [
20325 APIv3.prototype.imageByKeyFill$ = function (keys) {
20326 return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
20327 this._pathImageByKey,
20329 this._propertiesKey
20330 .concat(this._propertiesFill)
20331 .concat(this._propertiesSpatial),
20332 this._propertiesKey
20333 .concat(this._propertiesUser)
20335 .map(function (value) {
20337 throw new Error("Images (" + keys.join(", ") + ") could not be found.");
20339 return value.json.imageByKey;
20340 }), this._pathImageByKey, keys);
20342 APIv3.prototype.imageByKeyFull$ = function (keys) {
20343 return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
20344 this._pathImageByKey,
20346 this._propertiesKey
20347 .concat(this._propertiesCore)
20348 .concat(this._propertiesFill)
20349 .concat(this._propertiesSpatial),
20350 this._propertiesKey
20351 .concat(this._propertiesUser)
20353 .map(function (value) {
20355 throw new Error("Images (" + keys.join(", ") + ") could not be found.");
20357 return value.json.imageByKey;
20358 }), this._pathImageByKey, keys);
20360 APIv3.prototype.imageCloseTo$ = function (lat, lon) {
20361 var lonLat = lon + ":" + lat;
20362 return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
20363 this._pathImageCloseTo,
20365 this._propertiesKey
20366 .concat(this._propertiesCore)
20367 .concat(this._propertiesFill)
20368 .concat(this._propertiesSpatial),
20369 this._propertiesKey
20370 .concat(this._propertiesUser)
20372 .map(function (value) {
20373 return value != null ? value.json.imageCloseTo[lonLat] : null;
20374 }), this._pathImageCloseTo, [lonLat]);
20376 APIv3.prototype.imagesByH$ = function (hs) {
20378 return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
20379 this._pathImagesByH,
20381 { from: 0, to: this._pageCount },
20382 this._propertiesKey
20383 .concat(this._propertiesCore),
20384 this._propertiesKey
20386 .map(function (value) {
20387 if (value == null) {
20388 value = { json: { imagesByH: {} } };
20389 for (var _i = 0, hs_1 = hs; _i < hs_1.length; _i++) {
20391 value.json.imagesByH[h] = {};
20392 for (var i = 0; i <= _this._pageCount; i++) {
20393 value.json.imagesByH[h][i] = null;
20397 return value.json.imagesByH;
20398 }), this._pathImagesByH, hs);
20400 APIv3.prototype.imageViewAdd$ = function (keys) {
20401 return this._catchInvalidateCall$(this._wrapPromise$(this._model.call([this._pathImageViewAdd], [keys])), this._pathImageViewAdd, keys);
20403 APIv3.prototype.invalidateImageByKey = function (keys) {
20404 this._invalidateGet(this._pathImageByKey, keys);
20406 APIv3.prototype.invalidateImagesByH = function (hs) {
20407 this._invalidateGet(this._pathImagesByH, hs);
20409 APIv3.prototype.invalidateSequenceByKey = function (sKeys) {
20410 this._invalidateGet(this._pathSequenceByKey, sKeys);
20412 APIv3.prototype.setToken = function (token) {
20413 this._model.invalidate([]);
20414 this._model = null;
20415 this._model = this._modelCreator.createModel(this._clientId, token);
20417 APIv3.prototype.sequenceByKey$ = function (sequenceKeys) {
20418 return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
20419 this._pathSequenceByKey,
20421 this._propertiesKey
20422 .concat(this._propertiesSequence)
20424 .map(function (value) {
20425 return value.json.sequenceByKey;
20426 }), this._pathSequenceByKey, sequenceKeys);
20428 APIv3.prototype.sequenceViewAdd$ = function (sequenceKeys) {
20429 return this._catchInvalidateCall$(this._wrapPromise$(this._model.call([this._pathSequenceViewAdd], [sequenceKeys])), this._pathSequenceViewAdd, sequenceKeys);
20431 Object.defineProperty(APIv3.prototype, "clientId", {
20433 return this._clientId;
20438 APIv3.prototype._catchInvalidateGet$ = function (observable, path, paths) {
20441 .catch(function (error) {
20442 _this._invalidateGet(path, paths);
20446 APIv3.prototype._catchInvalidateCall$ = function (observable, path, paths) {
20449 .catch(function (error) {
20450 _this._invalidateCall(path, paths);
20454 APIv3.prototype._invalidateGet = function (path, paths) {
20455 this._model.invalidate([path, paths]);
20457 APIv3.prototype._invalidateCall = function (path, paths) {
20458 this._model.invalidate([path], [paths]);
20460 APIv3.prototype._wrapPromise$ = function (promise) {
20461 return Observable_1.Observable.defer(function () { return Observable_1.Observable.fromPromise(promise); });
20465 exports.APIv3 = APIv3;
20466 exports.default = APIv3;
20468 },{"../API":225,"rxjs/Observable":29,"rxjs/add/observable/defer":39,"rxjs/add/observable/fromPromise":43,"rxjs/add/operator/catch":52,"rxjs/add/operator/map":65}],239:[function(require,module,exports){
20470 /// <reference path="../../typings/index.d.ts" />
20471 Object.defineProperty(exports, "__esModule", { value: true });
20472 var falcor = require("falcor");
20473 var HttpDataSource = require("falcor-http-datasource");
20474 var Utils_1 = require("../Utils");
20476 * @class ModelCreator
20478 * @classdesc Creates API models.
20480 var ModelCreator = (function () {
20481 function ModelCreator() {
20484 * Creates a Falcor model.
20486 * @description Max cache size will be set to 16 MB. Authorization
20487 * header will be added if bearer token is supplied.
20489 * @param {number} clientId - Client id for API requests.
20490 * @param {number} [token] - Optional bearer token for API requests of
20491 * protected resources.
20492 * @returns {falcor.Model} Falcor model for HTTP requests.
20494 ModelCreator.prototype.createModel = function (clientId, token) {
20495 var configuration = {
20497 withCredentials: false,
20499 if (token != null) {
20500 configuration.headers = { "Authorization": "Bearer " + token };
20502 return new falcor.Model({
20503 maxSize: 16 * 1024 * 1024,
20504 source: new HttpDataSource(Utils_1.Urls.falcorModel(clientId), configuration),
20507 return ModelCreator;
20509 exports.ModelCreator = ModelCreator;
20510 exports.default = ModelCreator;
20512 },{"../Utils":236,"falcor":15,"falcor-http-datasource":10}],240:[function(require,module,exports){
20514 /// <reference path="../../typings/index.d.ts" />
20515 var __extends = (this && this.__extends) || (function () {
20516 var extendStatics = Object.setPrototypeOf ||
20517 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20518 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
20519 return function (d, b) {
20520 extendStatics(d, b);
20521 function __() { this.constructor = d; }
20522 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20525 Object.defineProperty(exports, "__esModule", { value: true });
20526 var vd = require("virtual-dom");
20527 var Component_1 = require("../Component");
20528 var AttributionComponent = (function (_super) {
20529 __extends(AttributionComponent, _super);
20530 function AttributionComponent(name, container, navigator) {
20531 return _super.call(this, name, container, navigator) || this;
20533 AttributionComponent.prototype._activate = function () {
20535 this._disposable = this._navigator.stateService.currentNode$
20536 .map(function (node) {
20537 return { name: _this._name, vnode: _this._getAttributionNode(node.username, node.key) };
20539 .subscribe(this._container.domRenderer.render$);
20541 AttributionComponent.prototype._deactivate = function () {
20542 this._disposable.unsubscribe();
20544 AttributionComponent.prototype._getDefaultConfiguration = function () {
20547 AttributionComponent.prototype._getAttributionNode = function (username, photoId) {
20548 return vd.h("div.Attribution", {}, [
20549 vd.h("a", { href: "https://www.mapillary.com/app/user/" + username,
20551 textContent: "@" + username,
20553 vd.h("span", { textContent: "|" }, []),
20554 vd.h("a", { href: "https://www.mapillary.com/app/?pKey=" + photoId + "&focus=photo",
20556 textContent: "mapillary.com",
20560 AttributionComponent.componentName = "attribution";
20561 return AttributionComponent;
20562 }(Component_1.Component));
20563 exports.AttributionComponent = AttributionComponent;
20564 Component_1.ComponentService.register(AttributionComponent);
20565 exports.default = AttributionComponent;
20567 },{"../Component":226,"virtual-dom":182}],241:[function(require,module,exports){
20569 /// <reference path="../../typings/index.d.ts" />
20570 var __extends = (this && this.__extends) || (function () {
20571 var extendStatics = Object.setPrototypeOf ||
20572 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20573 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
20574 return function (d, b) {
20575 extendStatics(d, b);
20576 function __() { this.constructor = d; }
20577 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20580 Object.defineProperty(exports, "__esModule", { value: true });
20581 var vd = require("virtual-dom");
20582 var Component_1 = require("../Component");
20583 var BackgroundComponent = (function (_super) {
20584 __extends(BackgroundComponent, _super);
20585 function BackgroundComponent(name, container, navigator) {
20586 return _super.call(this, name, container, navigator) || this;
20588 BackgroundComponent.prototype._activate = function () {
20589 this._container.domRenderer.render$
20590 .next({ name: this._name, vnode: this._getBackgroundNode("The viewer can't display the given photo.") });
20592 BackgroundComponent.prototype._deactivate = function () {
20595 BackgroundComponent.prototype._getDefaultConfiguration = function () {
20598 BackgroundComponent.prototype._getBackgroundNode = function (notice) {
20599 // todo: add condition for when to display the DOM node
20600 return vd.h("div.BackgroundWrapper", {}, [
20601 vd.h("p", { textContent: notice }, []),
20604 BackgroundComponent.componentName = "background";
20605 return BackgroundComponent;
20606 }(Component_1.Component));
20607 exports.BackgroundComponent = BackgroundComponent;
20608 Component_1.ComponentService.register(BackgroundComponent);
20609 exports.default = BackgroundComponent;
20611 },{"../Component":226,"virtual-dom":182}],242:[function(require,module,exports){
20613 /// <reference path="../../typings/index.d.ts" />
20614 var __extends = (this && this.__extends) || (function () {
20615 var extendStatics = Object.setPrototypeOf ||
20616 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20617 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
20618 return function (d, b) {
20619 extendStatics(d, b);
20620 function __() { this.constructor = d; }
20621 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20624 Object.defineProperty(exports, "__esModule", { value: true });
20625 var vd = require("virtual-dom");
20626 var Observable_1 = require("rxjs/Observable");
20627 var Component_1 = require("../Component");
20628 var Geo_1 = require("../Geo");
20629 var BearingComponent = (function (_super) {
20630 __extends(BearingComponent, _super);
20631 function BearingComponent(name, container, navigator) {
20632 var _this = _super.call(this, name, container, navigator) || this;
20633 _this._spatial = new Geo_1.Spatial();
20634 _this._svgNamespace = "http://www.w3.org/2000/svg";
20635 _this._distinctThreshold = Math.PI / 90;
20638 BearingComponent.prototype._activate = function () {
20640 var nodeBearingFov$ = this._navigator.stateService.currentState$
20641 .distinctUntilChanged(undefined, function (frame) {
20642 return frame.state.currentNode.key;
20644 .map(function (frame) {
20645 var node = frame.state.currentNode;
20646 var transform = frame.state.currentTransform;
20648 var hFov_1 = 2 * Math.PI * node.gpano.CroppedAreaImageWidthPixels / node.gpano.FullPanoWidthPixels;
20649 return [_this._spatial.degToRad(node.ca), hFov_1];
20651 var size = Math.max(transform.basicWidth, transform.basicHeight);
20653 console.warn("Original image size (" + transform.basicWidth + ", " + transform.basicHeight + ") is invalid (" + node.key + ". " +
20654 "Not showing available fov.");
20656 var hFov = size > 0 ?
20657 2 * Math.atan(0.5 * transform.basicWidth / (size * transform.focal)) :
20659 return [_this._spatial.degToRad(node.ca), hFov];
20661 .distinctUntilChanged(function (a1, a2) {
20662 return Math.abs(a2[0] - a1[0]) < _this._distinctThreshold &&
20663 Math.abs(a2[1] - a1[1]) < _this._distinctThreshold;
20665 var cameraBearingFov$ = this._container.renderService.renderCamera$
20666 .map(function (rc) {
20667 var vFov = _this._spatial.degToRad(rc.perspective.fov);
20668 var hFov = rc.perspective.aspect === Number.POSITIVE_INFINITY ?
20670 Math.atan(rc.perspective.aspect * Math.tan(0.5 * vFov)) * 2;
20671 return [_this._spatial.azimuthalToBearing(rc.rotation.phi), hFov];
20673 .distinctUntilChanged(function (a1, a2) {
20674 return Math.abs(a2[0] - a1[0]) < _this._distinctThreshold &&
20675 Math.abs(a2[1] - a1[1]) < _this._distinctThreshold;
20677 this._renderSubscription = Observable_1.Observable
20678 .combineLatest(nodeBearingFov$, cameraBearingFov$)
20679 .map(function (args) {
20680 var background = vd.h("div.BearingIndicatorBackground", { oncontextmenu: function (event) { event.preventDefault(); } }, [
20681 vd.h("div.BearingIndicatorBackgroundRectangle", {}, []),
20682 vd.h("div.BearingIndicatorBackgroundCircle", {}, []),
20684 var north = vd.h("div.BearingIndicatorNorth", {}, []);
20685 var nodeSector = _this._createCircleSector(args[0][0], args[0][1], "#000");
20686 var cameraSector = _this._createCircleSector(args[1][0], args[1][1], "#fff");
20687 var compass = _this._createCircleSectorCompass(nodeSector, cameraSector);
20690 vnode: vd.h("div.BearingIndicator", {}, [
20697 .subscribe(this._container.domRenderer.render$);
20699 BearingComponent.prototype._deactivate = function () {
20700 this._renderSubscription.unsubscribe();
20702 BearingComponent.prototype._getDefaultConfiguration = function () {
20705 BearingComponent.prototype._createCircleSectorCompass = function (nodeSector, cameraSector) {
20706 var group = vd.h("g", {
20707 attributes: { transform: "translate(1,1)" },
20708 namespace: this._svgNamespace,
20709 }, [nodeSector, cameraSector]);
20710 var centerCircle = vd.h("circle", {
20717 "stroke-width": "0.0833333",
20719 namespace: this._svgNamespace,
20721 var svg = vd.h("svg", {
20722 attributes: { viewBox: "0 0 2 2" },
20723 namespace: this._svgNamespace,
20728 position: "absolute",
20731 }, [group, centerCircle]);
20734 BearingComponent.prototype._createCircleSector = function (bearing, fov, fill) {
20735 if (fov > 2 * Math.PI - Math.PI / 90) {
20736 return vd.h("circle", {
20737 attributes: { cx: "0", cy: "0", fill: fill, r: "1" },
20738 namespace: this._svgNamespace,
20741 var arcStart = bearing - fov / 2 - Math.PI / 2;
20742 var arcEnd = arcStart + fov;
20743 var startX = Math.cos(arcStart);
20744 var startY = Math.sin(arcStart);
20745 var endX = Math.cos(arcEnd);
20746 var endY = Math.sin(arcEnd);
20747 var largeArc = fov >= Math.PI ? 1 : 0;
20748 var description = "M 0 0 " + startX + " " + startY + " A 1 1 0 " + largeArc + " 1 " + endX + " " + endY;
20749 return vd.h("path", {
20750 attributes: { d: description, fill: fill },
20751 namespace: this._svgNamespace,
20754 BearingComponent.componentName = "bearing";
20755 return BearingComponent;
20756 }(Component_1.Component));
20757 exports.BearingComponent = BearingComponent;
20758 Component_1.ComponentService.register(BearingComponent);
20759 exports.default = BearingComponent;
20761 },{"../Component":226,"../Geo":229,"rxjs/Observable":29,"virtual-dom":182}],243:[function(require,module,exports){
20763 var __extends = (this && this.__extends) || (function () {
20764 var extendStatics = Object.setPrototypeOf ||
20765 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20766 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
20767 return function (d, b) {
20768 extendStatics(d, b);
20769 function __() { this.constructor = d; }
20770 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20773 Object.defineProperty(exports, "__esModule", { value: true });
20774 var Observable_1 = require("rxjs/Observable");
20775 require("rxjs/add/observable/combineLatest");
20776 require("rxjs/add/observable/from");
20777 require("rxjs/add/observable/merge");
20778 require("rxjs/add/observable/of");
20779 require("rxjs/add/observable/zip");
20780 require("rxjs/add/operator/catch");
20781 require("rxjs/add/operator/combineLatest");
20782 require("rxjs/add/operator/distinct");
20783 require("rxjs/add/operator/expand");
20784 require("rxjs/add/operator/filter");
20785 require("rxjs/add/operator/map");
20786 require("rxjs/add/operator/merge");
20787 require("rxjs/add/operator/mergeMap");
20788 require("rxjs/add/operator/mergeAll");
20789 require("rxjs/add/operator/skip");
20790 require("rxjs/add/operator/switchMap");
20791 var Edge_1 = require("../Edge");
20792 var Component_1 = require("../Component");
20793 var CacheComponent = (function (_super) {
20794 __extends(CacheComponent, _super);
20795 function CacheComponent(name, container, navigator) {
20796 return _super.call(this, name, container, navigator) || this;
20799 * Set the cache depth.
20801 * Configures the cache depth. The cache depth can be different for
20802 * different edge direction types.
20804 * @param {ICacheDepth} depth - Cache depth structure.
20806 CacheComponent.prototype.setDepth = function (depth) {
20807 this.configure({ depth: depth });
20809 CacheComponent.prototype._activate = function () {
20811 this._sequenceSubscription = Observable_1.Observable
20812 .combineLatest(this._navigator.stateService.currentNode$
20813 .switchMap(function (node) {
20814 return node.sequenceEdges$;
20816 .filter(function (status) {
20817 return status.cached;
20818 }), this._configuration$)
20819 .switchMap(function (nc) {
20820 var status = nc[0];
20821 var configuration = nc[1];
20822 var sequenceDepth = Math.max(0, Math.min(4, configuration.depth.sequence));
20823 var next$ = _this._cache$(status.edges, Edge_1.EdgeDirection.Next, sequenceDepth);
20824 var prev$ = _this._cache$(status.edges, Edge_1.EdgeDirection.Prev, sequenceDepth);
20825 return Observable_1.Observable
20826 .merge(next$, prev$)
20827 .catch(function (error, caught) {
20828 console.error("Failed to cache sequence edges.", error);
20829 return Observable_1.Observable.empty();
20832 .subscribe(function () { });
20833 this._spatialSubscription = this._navigator.stateService.currentNode$
20834 .switchMap(function (node) {
20835 return Observable_1.Observable
20836 .combineLatest(Observable_1.Observable.of(node), node.spatialEdges$
20837 .filter(function (status) {
20838 return status.cached;
20841 .combineLatest(this._configuration$, function (ns, configuration) {
20842 return [ns[0], ns[1], configuration];
20844 .switchMap(function (args) {
20845 var node = args[0];
20846 var edges = args[1].edges;
20847 var depth = args[2].depth;
20848 var panoDepth = Math.max(0, Math.min(2, depth.pano));
20849 var stepDepth = node.pano ? 0 : Math.max(0, Math.min(3, depth.step));
20850 var turnDepth = node.pano ? 0 : Math.max(0, Math.min(1, depth.turn));
20851 var pano$ = _this._cache$(edges, Edge_1.EdgeDirection.Pano, panoDepth);
20852 var forward$ = _this._cache$(edges, Edge_1.EdgeDirection.StepForward, stepDepth);
20853 var backward$ = _this._cache$(edges, Edge_1.EdgeDirection.StepBackward, stepDepth);
20854 var left$ = _this._cache$(edges, Edge_1.EdgeDirection.StepLeft, stepDepth);
20855 var right$ = _this._cache$(edges, Edge_1.EdgeDirection.StepRight, stepDepth);
20856 var turnLeft$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnLeft, turnDepth);
20857 var turnRight$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnRight, turnDepth);
20858 var turnU$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnU, turnDepth);
20859 return Observable_1.Observable
20860 .merge(forward$, backward$, left$, right$, pano$, turnLeft$, turnRight$, turnU$)
20861 .catch(function (error, caught) {
20862 console.error("Failed to cache spatial edges.", error);
20863 return Observable_1.Observable.empty();
20866 .subscribe(function () { });
20868 CacheComponent.prototype._deactivate = function () {
20869 this._sequenceSubscription.unsubscribe();
20870 this._spatialSubscription.unsubscribe();
20872 CacheComponent.prototype._getDefaultConfiguration = function () {
20873 return { depth: { pano: 1, sequence: 2, step: 1, turn: 0 } };
20875 CacheComponent.prototype._cache$ = function (edges, direction, depth) {
20877 return Observable_1.Observable
20878 .zip(Observable_1.Observable.of(edges), Observable_1.Observable.of(depth))
20879 .expand(function (ed) {
20882 var edgesDepths$ = [];
20884 for (var _i = 0, es_1 = es; _i < es_1.length; _i++) {
20885 var edge = es_1[_i];
20886 if (edge.data.direction === direction) {
20887 edgesDepths$.push(Observable_1.Observable
20888 .zip(_this._navigator.graphService.cacheNode$(edge.to)
20889 .mergeMap(function (n) {
20890 return _this._nodeToEdges$(n, direction);
20891 }), Observable_1.Observable.of(d - 1)));
20895 return Observable_1.Observable
20896 .from(edgesDepths$)
20901 CacheComponent.prototype._nodeToEdges$ = function (node, direction) {
20902 return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
20903 node.sequenceEdges$ :
20904 node.spatialEdges$)
20905 .first(function (status) {
20906 return status.cached;
20908 .map(function (status) {
20909 return status.edges;
20912 CacheComponent.componentName = "cache";
20913 return CacheComponent;
20914 }(Component_1.Component));
20915 exports.CacheComponent = CacheComponent;
20916 Component_1.ComponentService.register(CacheComponent);
20917 exports.default = CacheComponent;
20919 },{"../Component":226,"../Edge":227,"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":75,"rxjs/add/operator/switchMap":79}],244:[function(require,module,exports){
20921 var __extends = (this && this.__extends) || (function () {
20922 var extendStatics = Object.setPrototypeOf ||
20923 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20924 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
20925 return function (d, b) {
20926 extendStatics(d, b);
20927 function __() { this.constructor = d; }
20928 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20931 Object.defineProperty(exports, "__esModule", { value: true });
20932 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
20933 var Subject_1 = require("rxjs/Subject");
20934 require("rxjs/add/operator/publishReplay");
20935 require("rxjs/add/operator/scan");
20936 require("rxjs/add/operator/startWith");
20937 var Utils_1 = require("../Utils");
20938 var Component = (function (_super) {
20939 __extends(Component, _super);
20940 function Component(name, container, navigator) {
20941 var _this = _super.call(this) || this;
20942 _this._activated$ = new BehaviorSubject_1.BehaviorSubject(false);
20943 _this._configurationSubject$ = new Subject_1.Subject();
20944 _this._activated = false;
20945 _this._container = container;
20946 _this._name = name;
20947 _this._navigator = navigator;
20948 _this._configuration$ =
20949 _this._configurationSubject$
20950 .startWith(_this.defaultConfiguration)
20951 .scan(function (conf, newConf) {
20952 for (var key in newConf) {
20953 if (newConf.hasOwnProperty(key)) {
20954 conf[key] = newConf[key];
20961 _this._configuration$.subscribe(function () { });
20964 Object.defineProperty(Component.prototype, "activated", {
20966 return this._activated;
20971 Object.defineProperty(Component.prototype, "activated$", {
20973 return this._activated$;
20978 Object.defineProperty(Component.prototype, "defaultConfiguration", {
20980 * Get default configuration.
20982 * @returns {TConfiguration} Default configuration for component.
20985 return this._getDefaultConfiguration();
20990 Object.defineProperty(Component.prototype, "configuration$", {
20992 return this._configuration$;
20997 Object.defineProperty(Component.prototype, "name", {
21004 Component.prototype.activate = function (conf) {
21005 if (this._activated) {
21008 if (conf !== undefined) {
21009 this._configurationSubject$.next(conf);
21011 this._activated = true;
21013 this._activated$.next(true);
21015 Component.prototype.configure = function (conf) {
21016 this._configurationSubject$.next(conf);
21018 Component.prototype.deactivate = function () {
21019 if (!this._activated) {
21022 this._activated = false;
21023 this._deactivate();
21024 this._container.domRenderer.clear(this._name);
21025 this._container.glRenderer.clear(this._name);
21026 this._activated$.next(false);
21029 * Detect the viewer's new width and height and resize the component's
21030 * rendered elements accordingly if applicable.
21032 Component.prototype.resize = function () { return; };
21034 * Component name. Used when interacting with component through the Viewer's API.
21036 Component.componentName = "not_worthy";
21038 }(Utils_1.EventEmitter));
21039 exports.Component = Component;
21040 exports.default = Component;
21042 },{"../Utils":236,"rxjs/BehaviorSubject":26,"rxjs/Subject":34,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":73,"rxjs/add/operator/startWith":78}],245:[function(require,module,exports){
21044 /// <reference path="../../typings/index.d.ts" />
21045 Object.defineProperty(exports, "__esModule", { value: true });
21046 var _ = require("underscore");
21047 var Error_1 = require("../Error");
21048 var ComponentService = (function () {
21049 function ComponentService(container, navigator) {
21050 this._components = {};
21051 this._container = container;
21052 this._navigator = navigator;
21053 for (var _i = 0, _a = _.values(ComponentService.registeredComponents); _i < _a.length; _i++) {
21054 var component = _a[_i];
21055 this._components[component.componentName] = {
21057 component: new component(component.componentName, container, navigator),
21060 this._coverComponent = new ComponentService.registeredCoverComponent("cover", container, navigator);
21061 this._coverComponent.activate();
21062 this._coverActivated = true;
21064 ComponentService.register = function (component) {
21065 if (ComponentService.registeredComponents[component.componentName] === undefined) {
21066 ComponentService.registeredComponents[component.componentName] = component;
21069 ComponentService.registerCover = function (coverComponent) {
21070 ComponentService.registeredCoverComponent = coverComponent;
21072 Object.defineProperty(ComponentService.prototype, "coverActivated", {
21074 return this._coverActivated;
21079 ComponentService.prototype.activateCover = function () {
21080 if (this._coverActivated) {
21083 this._coverActivated = true;
21084 for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
21085 var component = _a[_i];
21086 if (component.active) {
21087 component.component.deactivate();
21092 ComponentService.prototype.deactivateCover = function () {
21093 if (!this._coverActivated) {
21096 this._coverActivated = false;
21097 for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
21098 var component = _a[_i];
21099 if (component.active) {
21100 component.component.activate();
21105 ComponentService.prototype.activate = function (name) {
21106 this._checkName(name);
21107 this._components[name].active = true;
21108 if (!this._coverActivated) {
21109 this.get(name).activate();
21112 ComponentService.prototype.configure = function (name, conf) {
21113 this._checkName(name);
21114 this.get(name).configure(conf);
21116 ComponentService.prototype.deactivate = function (name) {
21117 this._checkName(name);
21118 this._components[name].active = false;
21119 if (!this._coverActivated) {
21120 this.get(name).deactivate();
21123 ComponentService.prototype.resize = function () {
21124 for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
21125 var component = _a[_i];
21126 component.component.resize();
21129 ComponentService.prototype.get = function (name) {
21130 return this._components[name].component;
21132 ComponentService.prototype.getCover = function () {
21133 return this._coverComponent;
21135 ComponentService.prototype._checkName = function (name) {
21136 if (!(name in this._components)) {
21137 throw new Error_1.ArgumentMapillaryError("Component does not exist: " + name);
21140 ComponentService.registeredComponents = {};
21141 return ComponentService;
21143 exports.ComponentService = ComponentService;
21144 exports.default = ComponentService;
21146 },{"../Error":228,"underscore":178}],246:[function(require,module,exports){
21148 /// <reference path="../../typings/index.d.ts" />
21149 var __extends = (this && this.__extends) || (function () {
21150 var extendStatics = Object.setPrototypeOf ||
21151 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21152 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21153 return function (d, b) {
21154 extendStatics(d, b);
21155 function __() { this.constructor = d; }
21156 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21159 Object.defineProperty(exports, "__esModule", { value: true });
21160 var vd = require("virtual-dom");
21161 require("rxjs/add/operator/filter");
21162 require("rxjs/add/operator/map");
21163 require("rxjs/add/operator/withLatestFrom");
21164 var Component_1 = require("../Component");
21165 var CoverComponent = (function (_super) {
21166 __extends(CoverComponent, _super);
21167 function CoverComponent(name, container, navigator) {
21168 return _super.call(this, name, container, navigator) || this;
21170 CoverComponent.prototype._activate = function () {
21172 this._keyDisposable = this._navigator.stateService.currentNode$
21173 .withLatestFrom(this._configuration$, function (node, configuration) {
21174 return [node, configuration];
21176 .filter(function (_a) {
21177 var node = _a[0], configuration = _a[1];
21178 return node.key !== configuration.key;
21180 .map(function (_a) {
21181 var node = _a[0], configuration = _a[1];
21184 .map(function (node) {
21185 return { key: node.key, src: node.image.src };
21187 .subscribe(this._configurationSubject$);
21188 this._disposable = this._configuration$
21189 .map(function (conf) {
21191 return { name: _this._name, vnode: vd.h("div", []) };
21193 if (conf.state === Component_1.CoverState.Hidden) {
21194 return { name: _this._name, vnode: vd.h("div.Cover.CoverDone", [_this._getCoverBackgroundVNode(conf)]) };
21196 return { name: _this._name, vnode: _this._getCoverButtonVNode(conf) };
21198 .subscribe(this._container.domRenderer.render$);
21200 CoverComponent.prototype._deactivate = function () {
21201 this._disposable.unsubscribe();
21202 this._keyDisposable.unsubscribe();
21204 CoverComponent.prototype._getDefaultConfiguration = function () {
21205 return { state: Component_1.CoverState.Visible };
21207 CoverComponent.prototype._getCoverButtonVNode = function (conf) {
21209 var cover = conf.state === Component_1.CoverState.Loading ? "div.Cover.CoverLoading" : "div.Cover";
21210 return vd.h(cover, [
21211 this._getCoverBackgroundVNode(conf),
21212 vd.h("button.CoverButton", { onclick: function () { _this.configure({ state: Component_1.CoverState.Loading }); } }, ["Explore"]),
21213 vd.h("a.CoverLogo", { href: "https://www.mapillary.com", target: "_blank" }, []),
21216 CoverComponent.prototype._getCoverBackgroundVNode = function (conf) {
21217 var url = conf.src != null ?
21218 "url(" + conf.src + ")" :
21219 "url(https://d1cuyjsrcm0gby.cloudfront.net/" + conf.key + "/thumb-640.jpg)";
21220 var properties = { style: { backgroundImage: url } };
21222 if (conf.state === Component_1.CoverState.Loading) {
21223 children.push(vd.h("div.Spinner", {}, []));
21225 children.push(vd.h("div.CoverBackgroundGradient", {}, []));
21226 return vd.h("div.CoverBackground", properties, children);
21228 CoverComponent.componentName = "cover";
21229 return CoverComponent;
21230 }(Component_1.Component));
21231 exports.CoverComponent = CoverComponent;
21232 Component_1.ComponentService.registerCover(CoverComponent);
21233 exports.default = CoverComponent;
21235 },{"../Component":226,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/withLatestFrom":83,"virtual-dom":182}],247:[function(require,module,exports){
21237 /// <reference path="../../typings/index.d.ts" />
21238 var __extends = (this && this.__extends) || (function () {
21239 var extendStatics = Object.setPrototypeOf ||
21240 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21241 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21242 return function (d, b) {
21243 extendStatics(d, b);
21244 function __() { this.constructor = d; }
21245 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21248 Object.defineProperty(exports, "__esModule", { value: true });
21249 var _ = require("underscore");
21250 var vd = require("virtual-dom");
21251 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
21252 require("rxjs/add/operator/combineLatest");
21253 var Component_1 = require("../Component");
21254 var DebugComponent = (function (_super) {
21255 __extends(DebugComponent, _super);
21256 function DebugComponent(name, container, navigator) {
21257 var _this = _super.call(this, name, container, navigator) || this;
21258 _this._open$ = new BehaviorSubject_1.BehaviorSubject(false);
21259 _this._displaying = false;
21262 DebugComponent.prototype._activate = function () {
21264 this._disposable = this._navigator.stateService.currentState$
21265 .combineLatest(this._open$, this._navigator.imageLoadingService.loadstatus$, function (frame, open, loadStatus) {
21266 return { name: _this._name, vnode: _this._getDebugVNode(open, _this._getDebugInfo(frame, loadStatus)) };
21268 .subscribe(this._container.domRenderer.render$);
21270 DebugComponent.prototype._deactivate = function () {
21271 this._disposable.unsubscribe();
21273 DebugComponent.prototype._getDefaultConfiguration = function () {
21276 DebugComponent.prototype._getDebugInfo = function (frame, loadStatus) {
21278 ret.push(vd.h("h2", "Node"));
21279 if (frame.state.currentNode) {
21280 ret.push(vd.h("p", "currentNode: " + frame.state.currentNode.key));
21282 if (frame.state.previousNode) {
21283 ret.push(vd.h("p", "previousNode: " + frame.state.previousNode.key));
21285 ret.push(vd.h("h2", "Loading"));
21289 for (var _i = 0, _a = _.values(loadStatus); _i < _a.length; _i++) {
21290 var loadStat = _a[_i];
21291 total += loadStat.loaded;
21292 if (loadStat.loaded !== loadStat.total) {
21299 ret.push(vd.h("p", "Loaded Images: " + loaded));
21300 ret.push(vd.h("p", "Loading Images: " + loading));
21301 ret.push(vd.h("p", "Total bytes loaded: " + total));
21302 ret.push(vd.h("h2", "Camera"));
21303 ret.push(vd.h("p", "camera.position.x: " + frame.state.camera.position.x));
21304 ret.push(vd.h("p", "camera.position.y: " + frame.state.camera.position.y));
21305 ret.push(vd.h("p", "camera.position.z: " + frame.state.camera.position.z));
21306 ret.push(vd.h("p", "camera.lookat.x: " + frame.state.camera.lookat.x));
21307 ret.push(vd.h("p", "camera.lookat.y: " + frame.state.camera.lookat.y));
21308 ret.push(vd.h("p", "camera.lookat.z: " + frame.state.camera.lookat.z));
21309 ret.push(vd.h("p", "camera.up.x: " + frame.state.camera.up.x));
21310 ret.push(vd.h("p", "camera.up.y: " + frame.state.camera.up.y));
21311 ret.push(vd.h("p", "camera.up.z: " + frame.state.camera.up.z));
21314 DebugComponent.prototype._getDebugVNode = function (open, info) {
21316 return vd.h("div.Debug", {}, [
21317 vd.h("h2", {}, ["Debug"]),
21318 this._getDebugVNodeButton(open),
21319 vd.h("pre", {}, info),
21323 return this._getDebugVNodeButton(open);
21326 DebugComponent.prototype._getDebugVNodeButton = function (open) {
21327 var buttonText = open ? "Disable Debug" : "D";
21328 var buttonCssClass = open ? "" : ".DebugButtonFixed";
21330 return vd.h("button.DebugButton" + buttonCssClass, { onclick: this._closeDebugElement.bind(this) }, [buttonText]);
21333 return vd.h("button.DebugButton" + buttonCssClass, { onclick: this._openDebugElement.bind(this) }, [buttonText]);
21336 DebugComponent.prototype._closeDebugElement = function (open) {
21337 this._open$.next(false);
21339 DebugComponent.prototype._openDebugElement = function () {
21340 this._open$.next(true);
21342 DebugComponent.componentName = "debug";
21343 return DebugComponent;
21344 }(Component_1.Component));
21345 exports.DebugComponent = DebugComponent;
21346 Component_1.ComponentService.register(DebugComponent);
21347 exports.default = DebugComponent;
21349 },{"../Component":226,"rxjs/BehaviorSubject":26,"rxjs/add/operator/combineLatest":53,"underscore":178,"virtual-dom":182}],248:[function(require,module,exports){
21351 /// <reference path="../../typings/index.d.ts" />
21352 var __extends = (this && this.__extends) || (function () {
21353 var extendStatics = Object.setPrototypeOf ||
21354 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21355 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21356 return function (d, b) {
21357 extendStatics(d, b);
21358 function __() { this.constructor = d; }
21359 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21362 Object.defineProperty(exports, "__esModule", { value: true });
21363 var vd = require("virtual-dom");
21364 var Observable_1 = require("rxjs/Observable");
21365 require("rxjs/add/operator/combineLatest");
21366 var Component_1 = require("../Component");
21367 var ImageComponent = (function (_super) {
21368 __extends(ImageComponent, _super);
21369 function ImageComponent(name, container, navigator) {
21370 var _this = _super.call(this, name, container, navigator) || this;
21371 _this._canvasId = container.id + "-" + _this._name;
21374 ImageComponent.prototype._activate = function () {
21376 var canvasSize$ = this._container.domRenderer.element$
21377 .map(function (element) {
21378 return document.getElementById(_this._canvasId);
21380 .filter(function (canvas) {
21383 .map(function (canvas) {
21384 var adaptableDomRenderer = canvas.parentElement;
21385 var width = adaptableDomRenderer.offsetWidth;
21386 var height = adaptableDomRenderer.offsetHeight;
21387 return [canvas, { height: height, width: width }];
21389 .distinctUntilChanged(function (s1, s2) {
21390 return s1.height === s2.height && s1.width === s2.width;
21392 var canvas = _a[0], size = _a[1];
21395 this.drawSubscription = Observable_1.Observable
21396 .combineLatest(canvasSize$, this._navigator.stateService.currentNode$)
21397 .subscribe(function (_a) {
21398 var _b = _a[0], canvas = _b[0], size = _b[1], node = _a[1];
21399 canvas.width = size.width;
21400 canvas.height = size.height;
21403 .drawImage(node.image, 0, 0, size.width, size.height);
21405 this._container.domRenderer.renderAdaptive$.next({ name: this._name, vnode: vd.h("canvas#" + this._canvasId, []) });
21407 ImageComponent.prototype._deactivate = function () {
21408 this.drawSubscription.unsubscribe();
21410 ImageComponent.prototype._getDefaultConfiguration = function () {
21413 ImageComponent.componentName = "image";
21414 return ImageComponent;
21415 }(Component_1.Component));
21416 exports.ImageComponent = ImageComponent;
21417 Component_1.ComponentService.register(ImageComponent);
21418 exports.default = ImageComponent;
21420 },{"../Component":226,"rxjs/Observable":29,"rxjs/add/operator/combineLatest":53,"virtual-dom":182}],249:[function(require,module,exports){
21422 /// <reference path="../../typings/index.d.ts" />
21423 var __extends = (this && this.__extends) || (function () {
21424 var extendStatics = Object.setPrototypeOf ||
21425 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21426 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21427 return function (d, b) {
21428 extendStatics(d, b);
21429 function __() { this.constructor = d; }
21430 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21433 Object.defineProperty(exports, "__esModule", { value: true });
21434 var _ = require("underscore");
21435 var vd = require("virtual-dom");
21436 require("rxjs/add/operator/combineLatest");
21437 var Component_1 = require("../Component");
21438 var LoadingComponent = (function (_super) {
21439 __extends(LoadingComponent, _super);
21440 function LoadingComponent(name, container, navigator) {
21441 return _super.call(this, name, container, navigator) || this;
21443 LoadingComponent.prototype._activate = function () {
21445 this._loadingSubscription = this._navigator.loadingService.loading$
21446 .combineLatest(this._navigator.imageLoadingService.loadstatus$, function (loading, loadStatus) {
21448 return { name: "loading", vnode: _this._getBarVNode(100) };
21452 for (var _i = 0, _a = _.values(loadStatus); _i < _a.length; _i++) {
21453 var loadStat = _a[_i];
21454 if (loadStat.loaded !== loadStat.total) {
21455 loaded += loadStat.loaded;
21456 total += loadStat.total;
21459 var percentage = 100;
21461 percentage = (loaded / total) * 100;
21463 return { name: _this._name, vnode: _this._getBarVNode(percentage) };
21465 .subscribe(this._container.domRenderer.render$);
21467 LoadingComponent.prototype._deactivate = function () {
21468 this._loadingSubscription.unsubscribe();
21470 LoadingComponent.prototype._getDefaultConfiguration = function () {
21473 LoadingComponent.prototype._getBarVNode = function (percentage) {
21474 var loadingBarStyle = {};
21475 var loadingContainerStyle = {};
21476 if (percentage !== 100) {
21477 loadingBarStyle.width = percentage.toFixed(0) + "%";
21478 loadingBarStyle.opacity = "1";
21481 loadingBarStyle.width = "100%";
21482 loadingBarStyle.opacity = "0";
21484 return vd.h("div.Loading", { style: loadingContainerStyle }, [vd.h("div.LoadingBar", { style: loadingBarStyle }, [])]);
21486 LoadingComponent.componentName = "loading";
21487 return LoadingComponent;
21488 }(Component_1.Component));
21489 exports.LoadingComponent = LoadingComponent;
21490 Component_1.ComponentService.register(LoadingComponent);
21491 exports.default = LoadingComponent;
21493 },{"../Component":226,"rxjs/add/operator/combineLatest":53,"underscore":178,"virtual-dom":182}],250:[function(require,module,exports){
21495 /// <reference path="../../typings/index.d.ts" />
21496 var __extends = (this && this.__extends) || (function () {
21497 var extendStatics = Object.setPrototypeOf ||
21498 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21499 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21500 return function (d, b) {
21501 extendStatics(d, b);
21502 function __() { this.constructor = d; }
21503 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21506 Object.defineProperty(exports, "__esModule", { value: true });
21507 var vd = require("virtual-dom");
21508 var Observable_1 = require("rxjs/Observable");
21509 require("rxjs/add/operator/map");
21510 require("rxjs/add/operator/first");
21511 var Edge_1 = require("../Edge");
21512 var Component_1 = require("../Component");
21514 * @class NavigationComponent
21516 * @classdesc Fallback navigation component for environments without WebGL support.
21518 * Replaces the functionality in the Direction and Sequence components.
21520 var NavigationComponent = (function (_super) {
21521 __extends(NavigationComponent, _super);
21522 function NavigationComponent(name, container, navigator) {
21523 var _this = _super.call(this, name, container, navigator) || this;
21524 _this._seqNames = {};
21525 _this._seqNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.Prev]] = "Prev";
21526 _this._seqNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.Next]] = "Next";
21527 _this._spaTopNames = {};
21528 _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.TurnLeft]] = "Turnleft";
21529 _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepLeft]] = "Left";
21530 _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepForward]] = "Forward";
21531 _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepRight]] = "Right";
21532 _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.TurnRight]] = "Turnright";
21533 _this._spaBottomNames = {};
21534 _this._spaBottomNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.TurnU]] = "Turnaround";
21535 _this._spaBottomNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepBackward]] = "Backward";
21538 NavigationComponent.prototype._activate = function () {
21540 this._renderSubscription = Observable_1.Observable
21541 .combineLatest(this._navigator.stateService.currentNode$, this._configuration$)
21542 .switchMap(function (_a) {
21543 var node = _a[0], configuration = _a[1];
21544 var sequenceEdges$ = configuration.sequence ?
21545 node.sequenceEdges$
21546 .map(function (status) {
21547 return status.edges
21548 .map(function (edge) {
21549 return edge.data.direction;
21552 Observable_1.Observable.of([]);
21553 var spatialEdges$ = !node.pano && configuration.spatial ?
21555 .map(function (status) {
21556 return status.edges
21557 .map(function (edge) {
21558 return edge.data.direction;
21561 Observable_1.Observable.of([]);
21562 return Observable_1.Observable
21563 .combineLatest(sequenceEdges$, spatialEdges$)
21564 .map(function (_a) {
21565 var seq = _a[0], spa = _a[1];
21566 return seq.concat(spa);
21569 .map(function (edgeDirections) {
21570 var seqs = _this._createArrowRow(_this._seqNames, edgeDirections);
21571 var spaTops = _this._createArrowRow(_this._spaTopNames, edgeDirections);
21572 var spaBottoms = _this._createArrowRow(_this._spaBottomNames, edgeDirections);
21573 var seqContainer = vd.h("div.NavigationSequence", seqs);
21574 var spaTopContainer = vd.h("div.NavigationSpatialTop", spaTops);
21575 var spaBottomContainer = vd.h("div.NavigationSpatialBottom", spaBottoms);
21576 var spaContainer = vd.h("div.NavigationSpatial", [spaTopContainer, spaBottomContainer]);
21577 return { name: _this._name, vnode: vd.h("div.NavigationContainer", [seqContainer, spaContainer]) };
21579 .subscribe(this._container.domRenderer.render$);
21581 NavigationComponent.prototype._deactivate = function () {
21582 this._renderSubscription.unsubscribe();
21584 NavigationComponent.prototype._getDefaultConfiguration = function () {
21585 return { sequence: true, spatial: true };
21587 NavigationComponent.prototype._createArrowRow = function (arrowNames, edgeDirections) {
21589 for (var arrowName in arrowNames) {
21590 if (!(arrowNames.hasOwnProperty(arrowName))) {
21593 var direction = Edge_1.EdgeDirection[arrowName];
21594 if (edgeDirections.indexOf(direction) !== -1) {
21595 arrows.push(this._createVNode(direction, arrowNames[arrowName], "visible"));
21598 arrows.push(this._createVNode(direction, arrowNames[arrowName], "hidden"));
21603 NavigationComponent.prototype._createVNode = function (direction, name, visibility) {
21605 return vd.h("span.Direction.Direction" + name, {
21606 onclick: function (ev) {
21607 _this._navigator.moveDir$(direction)
21608 .subscribe(function (node) { return; }, function (error) { console.error(error); });
21611 visibility: visibility,
21615 NavigationComponent.componentName = "navigation";
21616 return NavigationComponent;
21617 }(Component_1.Component));
21618 exports.NavigationComponent = NavigationComponent;
21619 Component_1.ComponentService.register(NavigationComponent);
21620 exports.default = NavigationComponent;
21622 },{"../Component":226,"../Edge":227,"rxjs/Observable":29,"rxjs/add/operator/first":63,"rxjs/add/operator/map":65,"virtual-dom":182}],251:[function(require,module,exports){
21624 /// <reference path="../../typings/index.d.ts" />
21625 var __extends = (this && this.__extends) || (function () {
21626 var extendStatics = Object.setPrototypeOf ||
21627 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21628 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21629 return function (d, b) {
21630 extendStatics(d, b);
21631 function __() { this.constructor = d; }
21632 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21635 Object.defineProperty(exports, "__esModule", { value: true });
21636 var _ = require("underscore");
21637 var vd = require("virtual-dom");
21638 var Observable_1 = require("rxjs/Observable");
21639 require("rxjs/add/observable/fromPromise");
21640 require("rxjs/add/observable/of");
21641 require("rxjs/add/operator/combineLatest");
21642 require("rxjs/add/operator/distinct");
21643 require("rxjs/add/operator/distinctUntilChanged");
21644 require("rxjs/add/operator/filter");
21645 require("rxjs/add/operator/map");
21646 require("rxjs/add/operator/mergeMap");
21647 require("rxjs/add/operator/pluck");
21648 require("rxjs/add/operator/scan");
21649 var Component_1 = require("../Component");
21650 var DescriptionState = (function () {
21651 function DescriptionState() {
21653 return DescriptionState;
21655 var RouteState = (function () {
21656 function RouteState() {
21660 var RouteTrack = (function () {
21661 function RouteTrack() {
21662 this.nodeInstructions = [];
21663 this.nodeInstructionsOrdered = [];
21667 var RouteComponent = (function (_super) {
21668 __extends(RouteComponent, _super);
21669 function RouteComponent(name, container, navigator) {
21670 return _super.call(this, name, container, navigator) || this;
21672 RouteComponent.prototype._activate = function () {
21674 var _slowedStream$;
21675 _slowedStream$ = this._navigator.stateService.currentState$.filter(function (frame) {
21676 return (frame.id % 2) === 0;
21677 }).filter(function (frame) {
21678 return frame.state.nodesAhead < 15;
21679 }).distinctUntilChanged(undefined, function (frame) {
21680 return frame.state.lastNode.key;
21683 _routeTrack$ = this.configuration$.mergeMap(function (conf) {
21684 return Observable_1.Observable.from(conf.paths);
21685 }).distinct(function (p) {
21686 return p.sequenceKey;
21687 }).mergeMap(function (path) {
21688 return _this._navigator.apiV3.sequenceByKey$([path.sequenceKey])
21689 .map(function (sequenceByKey) {
21690 return sequenceByKey[path.sequenceKey];
21692 }).combineLatest(this.configuration$, function (sequence, conf) {
21694 var instructionPlaces = [];
21695 for (var _i = 0, _a = conf.paths; _i < _a.length; _i++) {
21697 if (path.sequenceKey === sequence.key) {
21698 var nodeInstructions = [];
21699 var saveKey = false;
21700 for (var _b = 0, _c = sequence.keys; _b < _c.length; _b++) {
21702 if (path.startKey === key) {
21706 var description = null;
21707 for (var _d = 0, _e = path.infoKeys; _d < _e.length; _d++) {
21708 var infoKey = _e[_d];
21709 if (infoKey.key === key) {
21710 description = infoKey.description;
21713 nodeInstructions.push({ description: description, key: key });
21715 if (path.stopKey === key) {
21719 instructionPlaces.push({ nodeInstructions: nodeInstructions, place: i });
21723 return instructionPlaces;
21724 }).scan(function (routeTrack, instructionPlaces) {
21725 for (var _i = 0, instructionPlaces_1 = instructionPlaces; _i < instructionPlaces_1.length; _i++) {
21726 var instructionPlace = instructionPlaces_1[_i];
21727 routeTrack.nodeInstructionsOrdered[instructionPlace.place] = instructionPlace.nodeInstructions;
21729 routeTrack.nodeInstructions = _.flatten(routeTrack.nodeInstructionsOrdered);
21731 }, new RouteTrack());
21732 this._disposable = _slowedStream$
21733 .combineLatest(_routeTrack$, this.configuration$, function (frame, routeTrack, conf) {
21734 return { conf: conf, frame: frame, routeTrack: routeTrack };
21735 }).scan(function (routeState, rtAndFrame) {
21736 if (rtAndFrame.conf.playing === undefined || rtAndFrame.conf.playing) {
21737 routeState.routeTrack = rtAndFrame.routeTrack;
21738 routeState.currentNode = rtAndFrame.frame.state.currentNode;
21739 routeState.lastNode = rtAndFrame.frame.state.lastNode;
21740 routeState.playing = true;
21743 _this._navigator.stateService.cutNodes();
21744 routeState.playing = false;
21747 }, new RouteState())
21748 .filter(function (routeState) {
21749 return routeState.playing;
21750 }).filter(function (routeState) {
21751 for (var _i = 0, _a = routeState.routeTrack.nodeInstructions; _i < _a.length; _i++) {
21752 var nodeInstruction = _a[_i];
21753 if (!nodeInstruction) {
21756 if (nodeInstruction.key === routeState.lastNode.key) {
21761 }).distinctUntilChanged(undefined, function (routeState) {
21762 return routeState.lastNode.key;
21763 }).mergeMap(function (routeState) {
21765 for (var _i = 0, _a = routeState.routeTrack.nodeInstructions; _i < _a.length; _i++) {
21766 var nodeInstruction = _a[_i];
21767 if (nodeInstruction.key === routeState.lastNode.key) {
21772 var nextInstruction = routeState.routeTrack.nodeInstructions[i + 1];
21773 if (!nextInstruction) {
21774 return Observable_1.Observable.of(null);
21776 return _this._navigator.graphService.cacheNode$(nextInstruction.key);
21777 }).combineLatest(this.configuration$, function (node, conf) {
21778 return { conf: conf, node: node };
21779 }).filter(function (cAN) {
21780 return cAN.node !== null && cAN.conf.playing;
21781 }).pluck("node").subscribe(this._navigator.stateService.appendNode$);
21782 this._disposableDescription = this._navigator.stateService.currentNode$
21783 .combineLatest(_routeTrack$, this.configuration$, function (node, routeTrack, conf) {
21784 if (conf.playing !== undefined && !conf.playing) {
21787 var description = null;
21788 for (var _i = 0, _a = routeTrack.nodeInstructions; _i < _a.length; _i++) {
21789 var nodeInstruction = _a[_i];
21790 if (nodeInstruction.key === node.key) {
21791 description = nodeInstruction.description;
21795 return description;
21796 }).scan(function (descriptionState, description) {
21797 if (description !== descriptionState.description && description !== null) {
21798 descriptionState.description = description;
21799 descriptionState.showsLeft = 6;
21802 descriptionState.showsLeft--;
21804 if (description === "quit") {
21805 descriptionState.description = null;
21807 return descriptionState;
21808 }, new DescriptionState()).map(function (descriptionState) {
21809 if (descriptionState.showsLeft > 0 && descriptionState.description) {
21810 return { name: _this._name, vnode: _this._getRouteAnnotationNode(descriptionState.description) };
21813 return { name: _this._name, vnode: vd.h("div", []) };
21815 }).subscribe(this._container.domRenderer.render$);
21817 RouteComponent.prototype._deactivate = function () {
21818 this._disposable.unsubscribe();
21819 this._disposableDescription.unsubscribe();
21821 RouteComponent.prototype._getDefaultConfiguration = function () {
21824 RouteComponent.prototype.play = function () {
21825 this.configure({ playing: true });
21827 RouteComponent.prototype.stop = function () {
21828 this.configure({ playing: false });
21830 RouteComponent.prototype._getRouteAnnotationNode = function (description) {
21831 return vd.h("div.RouteFrame", {}, [
21832 vd.h("p", { textContent: description }, []),
21835 RouteComponent.componentName = "route";
21836 return RouteComponent;
21837 }(Component_1.Component));
21838 exports.RouteComponent = RouteComponent;
21839 Component_1.ComponentService.register(RouteComponent);
21840 exports.default = RouteComponent;
21842 },{"../Component":226,"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":73,"underscore":178,"virtual-dom":182}],252:[function(require,module,exports){
21844 var __extends = (this && this.__extends) || (function () {
21845 var extendStatics = Object.setPrototypeOf ||
21846 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21847 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21848 return function (d, b) {
21849 extendStatics(d, b);
21850 function __() { this.constructor = d; }
21851 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21854 Object.defineProperty(exports, "__esModule", { value: true });
21855 var Observable_1 = require("rxjs/Observable");
21856 require("rxjs/add/operator/buffer");
21857 require("rxjs/add/operator/debounceTime");
21858 require("rxjs/add/operator/filter");
21859 require("rxjs/add/operator/map");
21860 require("rxjs/add/operator/scan");
21861 var Component_1 = require("../Component");
21862 var StatsComponent = (function (_super) {
21863 __extends(StatsComponent, _super);
21864 function StatsComponent(name, container, navigator) {
21865 return _super.call(this, name, container, navigator) || this;
21867 StatsComponent.prototype._activate = function () {
21869 this._sequenceSubscription = this._navigator.stateService.currentNode$
21870 .scan(function (keys, node) {
21871 var sKey = node.sequenceKey;
21873 if (!(sKey in keys.reported)) {
21874 keys.report = [sKey];
21875 keys.reported[sKey] = true;
21878 }, { report: [], reported: {} })
21879 .filter(function (keys) {
21880 return keys.report.length > 0;
21882 .mergeMap(function (keys) {
21883 return _this._navigator.apiV3.sequenceViewAdd$(keys.report)
21884 .catch(function (error, caught) {
21885 console.error("Failed to report sequence stats (" + keys.report + ")", error);
21886 return Observable_1.Observable.empty();
21889 .subscribe(function () { });
21890 this._imageSubscription = this._navigator.stateService.currentNode$
21891 .map(function (node) {
21894 .buffer(this._navigator.stateService.currentNode$.debounceTime(5000))
21895 .scan(function (keys, newKeys) {
21897 for (var _i = 0, newKeys_1 = newKeys; _i < newKeys_1.length; _i++) {
21898 var key = newKeys_1[_i];
21899 if (!(key in keys.reported)) {
21900 keys.report.push(key);
21901 keys.reported[key] = true;
21905 }, { report: [], reported: {} })
21906 .filter(function (keys) {
21907 return keys.report.length > 0;
21909 .mergeMap(function (keys) {
21910 return _this._navigator.apiV3.imageViewAdd$(keys.report)
21911 .catch(function (error, caught) {
21912 console.error("Failed to report image stats (" + keys.report + ")", error);
21913 return Observable_1.Observable.empty();
21916 .subscribe(function () { });
21918 StatsComponent.prototype._deactivate = function () {
21919 this._sequenceSubscription.unsubscribe();
21920 this._imageSubscription.unsubscribe();
21922 StatsComponent.prototype._getDefaultConfiguration = function () {
21925 StatsComponent.componentName = "stats";
21926 return StatsComponent;
21927 }(Component_1.Component));
21928 exports.StatsComponent = StatsComponent;
21929 Component_1.ComponentService.register(StatsComponent);
21930 exports.default = StatsComponent;
21932 },{"../Component":226,"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":73}],253:[function(require,module,exports){
21934 /// <reference path="../../../typings/index.d.ts" />
21935 var __extends = (this && this.__extends) || (function () {
21936 var extendStatics = Object.setPrototypeOf ||
21937 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21938 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21939 return function (d, b) {
21940 extendStatics(d, b);
21941 function __() { this.constructor = d; }
21942 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21945 Object.defineProperty(exports, "__esModule", { value: true });
21946 var vd = require("virtual-dom");
21947 var Observable_1 = require("rxjs/Observable");
21948 var Subject_1 = require("rxjs/Subject");
21949 require("rxjs/add/observable/combineLatest");
21950 require("rxjs/add/operator/do");
21951 require("rxjs/add/operator/distinctUntilChanged");
21952 require("rxjs/add/operator/filter");
21953 require("rxjs/add/operator/map");
21954 require("rxjs/add/operator/share");
21955 var Component_1 = require("../../Component");
21957 * @class DirectionComponent
21958 * @classdesc Component showing navigation arrows for steps and turns.
21960 var DirectionComponent = (function (_super) {
21961 __extends(DirectionComponent, _super);
21962 function DirectionComponent(name, container, navigator, directionDOMRenderer) {
21963 var _this = _super.call(this, name, container, navigator) || this;
21964 _this._renderer = !!directionDOMRenderer ?
21965 directionDOMRenderer :
21966 new Component_1.DirectionDOMRenderer(_this.defaultConfiguration, container.element);
21967 _this._hoveredKeySubject$ = new Subject_1.Subject();
21968 _this._hoveredKey$ = _this._hoveredKeySubject$.share();
21971 Object.defineProperty(DirectionComponent.prototype, "hoveredKey$", {
21973 * Get hovered key observable.
21975 * @description An observable emitting the key of the node for the direction
21976 * arrow that is being hovered. When the mouse leaves a direction arrow null
21979 * @returns {Observable<string>}
21982 return this._hoveredKey$;
21988 * Set highlight key.
21990 * @description The arrow pointing towards the node corresponding to the
21991 * highlight key will be highlighted.
21993 * @param {string} highlightKey Key of node to be highlighted if existing
21996 DirectionComponent.prototype.setHighlightKey = function (highlightKey) {
21997 this.configure({ highlightKey: highlightKey });
22000 * Set min width of container element.
22002 * @description Set min width of the non transformed container element holding
22003 * the navigation arrows. If the min width is larger than the max width the
22004 * min width value will be used.
22006 * The container element is automatically resized when the resize
22007 * method on the Viewer class is called.
22009 * @param {number} minWidth
22011 DirectionComponent.prototype.setMinWidth = function (minWidth) {
22012 this.configure({ minWidth: minWidth });
22015 * Set max width of container element.
22017 * @description Set max width of the non transformed container element holding
22018 * the navigation arrows. If the min width is larger than the max width the
22019 * min width value will be used.
22021 * The container element is automatically resized when the resize
22022 * method on the Viewer class is called.
22024 * @param {number} minWidth
22026 DirectionComponent.prototype.setMaxWidth = function (maxWidth) {
22027 this.configure({ maxWidth: maxWidth });
22030 DirectionComponent.prototype.resize = function () {
22031 this._renderer.resize(this._container.element);
22033 DirectionComponent.prototype._activate = function () {
22035 this._configurationSubscription = this._configuration$
22036 .subscribe(function (configuration) {
22037 _this._renderer.setConfiguration(configuration);
22039 this._nodeSubscription = this._navigator.stateService.currentNode$
22040 .do(function (node) {
22041 _this._container.domRenderer.render$.next({ name: _this._name, vnode: vd.h("div", {}, []) });
22042 _this._renderer.setNode(node);
22044 .withLatestFrom(this._configuration$)
22045 .switchMap(function (_a) {
22046 var node = _a[0], configuration = _a[1];
22047 return Observable_1.Observable
22048 .combineLatest(node.spatialEdges$, configuration.distinguishSequence ?
22049 _this._navigator.graphService
22050 .cacheSequence$(node.sequenceKey)
22051 .catch(function (error, caught) {
22052 console.error("Failed to cache sequence (" + node.sequenceKey + ")", error);
22053 return Observable_1.Observable.of(null);
22055 Observable_1.Observable.of(null));
22057 .subscribe(function (_a) {
22058 var edgeStatus = _a[0], sequence = _a[1];
22059 _this._renderer.setEdges(edgeStatus, sequence);
22061 this._renderCameraSubscription = this._container.renderService.renderCameraFrame$
22062 .do(function (renderCamera) {
22063 _this._renderer.setRenderCamera(renderCamera);
22065 .map(function (renderCamera) {
22066 return _this._renderer;
22068 .filter(function (renderer) {
22069 return renderer.needsRender;
22071 .map(function (renderer) {
22072 return { name: _this._name, vnode: renderer.render(_this._navigator) };
22074 .subscribe(this._container.domRenderer.render$);
22075 this._hoveredKeySubscription = Observable_1.Observable
22077 this._container.domRenderer.element$,
22078 this._container.renderService.renderCamera$,
22079 this._container.mouseService.mouseMove$.startWith(null),
22080 this._container.mouseService.mouseUp$.startWith(null),
22081 ], function (e, rc, mm, mu) {
22084 .map(function (element) {
22085 var elements = element.getElementsByClassName("DirectionsPerspective");
22086 for (var i = 0; i < elements.length; i++) {
22087 var hovered = elements.item(i).querySelector(":hover");
22088 if (hovered != null && hovered.hasAttribute("data-key")) {
22089 return hovered.getAttribute("data-key");
22094 .distinctUntilChanged()
22095 .subscribe(this._hoveredKeySubject$);
22097 DirectionComponent.prototype._deactivate = function () {
22098 this._configurationSubscription.unsubscribe();
22099 this._nodeSubscription.unsubscribe();
22100 this._renderCameraSubscription.unsubscribe();
22101 this._hoveredKeySubscription.unsubscribe();
22103 DirectionComponent.prototype._getDefaultConfiguration = function () {
22105 distinguishSequence: false,
22111 DirectionComponent.componentName = "direction";
22112 return DirectionComponent;
22113 }(Component_1.Component));
22114 exports.DirectionComponent = DirectionComponent;
22115 Component_1.ComponentService.register(DirectionComponent);
22116 exports.default = DirectionComponent;
22118 },{"../../Component":226,"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":74,"virtual-dom":182}],254:[function(require,module,exports){
22120 Object.defineProperty(exports, "__esModule", { value: true });
22121 var Geo_1 = require("../../Geo");
22123 * @class DirectionDOMCalculator
22124 * @classdesc Helper class for calculating DOM CSS properties.
22126 var DirectionDOMCalculator = (function () {
22127 function DirectionDOMCalculator(configuration, element) {
22128 this._spatial = new Geo_1.Spatial();
22129 this._minThresholdWidth = 320;
22130 this._maxThresholdWidth = 1480;
22131 this._minThresholdHeight = 240;
22132 this._maxThresholdHeight = 820;
22133 this._configure(configuration);
22134 this._resize(element);
22137 Object.defineProperty(DirectionDOMCalculator.prototype, "minWidth", {
22139 return this._minWidth;
22144 Object.defineProperty(DirectionDOMCalculator.prototype, "maxWidth", {
22146 return this._maxWidth;
22151 Object.defineProperty(DirectionDOMCalculator.prototype, "containerWidth", {
22153 return this._containerWidth;
22158 Object.defineProperty(DirectionDOMCalculator.prototype, "containerWidthCss", {
22160 return this._containerWidthCss;
22165 Object.defineProperty(DirectionDOMCalculator.prototype, "containerMarginCss", {
22167 return this._containerMarginCss;
22172 Object.defineProperty(DirectionDOMCalculator.prototype, "containerLeftCss", {
22174 return this._containerLeftCss;
22179 Object.defineProperty(DirectionDOMCalculator.prototype, "containerHeight", {
22181 return this._containerHeight;
22186 Object.defineProperty(DirectionDOMCalculator.prototype, "containerHeightCss", {
22188 return this._containerHeightCss;
22193 Object.defineProperty(DirectionDOMCalculator.prototype, "containerBottomCss", {
22195 return this._containerBottomCss;
22200 Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleSize", {
22202 return this._stepCircleSize;
22207 Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleSizeCss", {
22209 return this._stepCircleSizeCss;
22214 Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleMarginCss", {
22216 return this._stepCircleMarginCss;
22221 Object.defineProperty(DirectionDOMCalculator.prototype, "turnCircleSize", {
22223 return this._turnCircleSize;
22228 Object.defineProperty(DirectionDOMCalculator.prototype, "turnCircleSizeCss", {
22230 return this._turnCircleSizeCss;
22235 Object.defineProperty(DirectionDOMCalculator.prototype, "outerRadius", {
22237 return this._outerRadius;
22242 Object.defineProperty(DirectionDOMCalculator.prototype, "innerRadius", {
22244 return this._innerRadius;
22249 Object.defineProperty(DirectionDOMCalculator.prototype, "shadowOffset", {
22251 return this._shadowOffset;
22257 * Configures the min and max width values.
22259 * @param {IDirectionConfiguration} configuration Configuration
22260 * with min and max width values.
22262 DirectionDOMCalculator.prototype.configure = function (configuration) {
22263 this._configure(configuration);
22267 * Resizes all properties according to the width and height
22270 * @param {HTMLElement} element The container element from which to extract
22271 * the width and height.
22273 DirectionDOMCalculator.prototype.resize = function (element) {
22274 this._resize(element);
22278 * Calculates the coordinates on the unit circle for an angle.
22280 * @param {number} angle Angle in radians.
22281 * @returns {Array<number>} The x and y coordinates on the unit circle.
22283 DirectionDOMCalculator.prototype.angleToCoordinates = function (angle) {
22284 return [Math.cos(angle), Math.sin(angle)];
22287 * Calculates the coordinates on the unit circle for the
22288 * relative angle between the first and second angle.
22290 * @param {number} first Angle in radians.
22291 * @param {number} second Angle in radians.
22292 * @returns {Array<number>} The x and y coordinates on the unit circle
22293 * for the relative angle between the first and second angle.
22295 DirectionDOMCalculator.prototype.relativeAngleToCoordiantes = function (first, second) {
22296 var relativeAngle = this._spatial.wrapAngle(first - second);
22297 return this.angleToCoordinates(relativeAngle);
22299 DirectionDOMCalculator.prototype._configure = function (configuration) {
22300 this._minWidth = configuration.minWidth;
22301 this._maxWidth = this._getMaxWidth(configuration.minWidth, configuration.maxWidth);
22303 DirectionDOMCalculator.prototype._resize = function (element) {
22304 this._elementWidth = element.offsetWidth;
22305 this._elementHeight = element.offsetHeight;
22307 DirectionDOMCalculator.prototype._reset = function () {
22308 this._containerWidth = this._getContainerWidth(this._elementWidth, this._elementHeight);
22309 this._containerHeight = this._getContainerHeight(this.containerWidth);
22310 this._stepCircleSize = this._getStepCircleDiameter(this._containerHeight);
22311 this._turnCircleSize = this._getTurnCircleDiameter(this.containerHeight);
22312 this._outerRadius = this._getOuterRadius(this._containerHeight);
22313 this._innerRadius = this._getInnerRadius(this._containerHeight);
22314 this._shadowOffset = 3;
22315 this._containerWidthCss = this._numberToCssPixels(this._containerWidth);
22316 this._containerMarginCss = this._numberToCssPixels(-0.5 * this._containerWidth);
22317 this._containerLeftCss = this._numberToCssPixels(Math.floor(0.5 * this._elementWidth));
22318 this._containerHeightCss = this._numberToCssPixels(this._containerHeight);
22319 this._containerBottomCss = this._numberToCssPixels(Math.floor(-0.08 * this._containerHeight));
22320 this._stepCircleSizeCss = this._numberToCssPixels(this._stepCircleSize);
22321 this._stepCircleMarginCss = this._numberToCssPixels(-0.5 * this._stepCircleSize);
22322 this._turnCircleSizeCss = this._numberToCssPixels(this._turnCircleSize);
22324 DirectionDOMCalculator.prototype._getContainerWidth = function (elementWidth, elementHeight) {
22325 var relativeWidth = (elementWidth - this._minThresholdWidth) / (this._maxThresholdWidth - this._minThresholdWidth);
22326 var relativeHeight = (elementHeight - this._minThresholdHeight) / (this._maxThresholdHeight - this._minThresholdHeight);
22327 var coeff = Math.max(0, Math.min(1, Math.min(relativeWidth, relativeHeight)));
22328 coeff = 0.04 * Math.round(25 * coeff);
22329 return this._minWidth + coeff * (this._maxWidth - this._minWidth);
22331 DirectionDOMCalculator.prototype._getContainerHeight = function (containerWidth) {
22332 return 0.77 * containerWidth;
22334 DirectionDOMCalculator.prototype._getStepCircleDiameter = function (containerHeight) {
22335 return 0.34 * containerHeight;
22337 DirectionDOMCalculator.prototype._getTurnCircleDiameter = function (containerHeight) {
22338 return 0.3 * containerHeight;
22340 DirectionDOMCalculator.prototype._getOuterRadius = function (containerHeight) {
22341 return 0.31 * containerHeight;
22343 DirectionDOMCalculator.prototype._getInnerRadius = function (containerHeight) {
22344 return 0.125 * containerHeight;
22346 DirectionDOMCalculator.prototype._numberToCssPixels = function (value) {
22347 return value + "px";
22349 DirectionDOMCalculator.prototype._getMaxWidth = function (value, minWidth) {
22350 return value > minWidth ? value : minWidth;
22352 return DirectionDOMCalculator;
22354 exports.DirectionDOMCalculator = DirectionDOMCalculator;
22355 exports.default = DirectionDOMCalculator;
22357 },{"../../Geo":229}],255:[function(require,module,exports){
22359 /// <reference path="../../../typings/index.d.ts" />
22360 Object.defineProperty(exports, "__esModule", { value: true });
22361 var vd = require("virtual-dom");
22362 var Component_1 = require("../../Component");
22363 var Edge_1 = require("../../Edge");
22364 var Geo_1 = require("../../Geo");
22366 * @class DirectionDOMRenderer
22367 * @classdesc DOM renderer for direction arrows.
22369 var DirectionDOMRenderer = (function () {
22370 function DirectionDOMRenderer(configuration, element) {
22371 this._isEdge = false;
22372 this._spatial = new Geo_1.Spatial();
22373 this._calculator = new Component_1.DirectionDOMCalculator(configuration, element);
22375 this._rotation = { phi: 0, theta: 0 };
22376 this._epsilon = 0.5 * Math.PI / 180;
22377 this._highlightKey = null;
22378 this._distinguishSequence = false;
22379 this._needsRender = false;
22380 this._stepEdges = [];
22381 this._turnEdges = [];
22382 this._panoEdges = [];
22383 this._sequenceEdgeKeys = [];
22384 this._stepDirections = [
22385 Edge_1.EdgeDirection.StepForward,
22386 Edge_1.EdgeDirection.StepBackward,
22387 Edge_1.EdgeDirection.StepLeft,
22388 Edge_1.EdgeDirection.StepRight,
22390 this._turnDirections = [
22391 Edge_1.EdgeDirection.TurnLeft,
22392 Edge_1.EdgeDirection.TurnRight,
22393 Edge_1.EdgeDirection.TurnU,
22395 this._turnNames = {};
22396 this._turnNames[Edge_1.EdgeDirection.TurnLeft] = "TurnLeft";
22397 this._turnNames[Edge_1.EdgeDirection.TurnRight] = "TurnRight";
22398 this._turnNames[Edge_1.EdgeDirection.TurnU] = "TurnAround";
22399 // detects IE 8-11, then Edge 20+.
22400 var isIE = !!document.documentMode;
22401 this._isEdge = !isIE && !!window.StyleMedia;
22403 Object.defineProperty(DirectionDOMRenderer.prototype, "needsRender", {
22405 * Get needs render.
22407 * @returns {boolean} Value indicating whether render should be called.
22410 return this._needsRender;
22416 * Renders virtual DOM elements.
22418 * @description Calling render resets the needs render property.
22420 DirectionDOMRenderer.prototype.render = function (navigator) {
22421 this._needsRender = false;
22422 var rotation = this._rotation;
22425 if (this._node.pano) {
22426 steps = steps.concat(this._createPanoArrows(navigator, rotation));
22429 steps = steps.concat(this._createPerspectiveToPanoArrows(navigator, rotation));
22430 steps = steps.concat(this._createStepArrows(navigator, rotation));
22431 turns = turns.concat(this._createTurnArrows(navigator));
22433 return this._getContainer(steps, turns, rotation);
22435 DirectionDOMRenderer.prototype.setEdges = function (edgeStatus, sequence) {
22436 this._setEdges(edgeStatus, sequence);
22437 this._setNeedsRender();
22440 * Set node for which to show edges.
22442 * @param {Node} node
22444 DirectionDOMRenderer.prototype.setNode = function (node) {
22446 this._clearEdges();
22447 this._setNeedsRender();
22450 * Set the render camera to use for calculating rotations.
22452 * @param {RenderCamera} renderCamera
22454 DirectionDOMRenderer.prototype.setRenderCamera = function (renderCamera) {
22455 var rotation = renderCamera.rotation;
22456 if (Math.abs(rotation.phi - this._rotation.phi) < this._epsilon) {
22459 this._rotation = rotation;
22460 this._setNeedsRender();
22463 * Set configuration values.
22465 * @param {IDirectionConfiguration} configuration
22467 DirectionDOMRenderer.prototype.setConfiguration = function (configuration) {
22468 var needsRender = false;
22469 if (this._highlightKey !== configuration.highlightKey ||
22470 this._distinguishSequence !== configuration.distinguishSequence) {
22471 this._highlightKey = configuration.highlightKey;
22472 this._distinguishSequence = configuration.distinguishSequence;
22473 needsRender = true;
22475 if (this._calculator.minWidth !== configuration.minWidth ||
22476 this._calculator.maxWidth !== configuration.maxWidth) {
22477 this._calculator.configure(configuration);
22478 needsRender = true;
22481 this._setNeedsRender();
22485 * Detect the element's width and height and resize
22486 * elements accordingly.
22488 * @param {HTMLElement} element Viewer container element.
22490 DirectionDOMRenderer.prototype.resize = function (element) {
22491 this._calculator.resize(element);
22492 this._setNeedsRender();
22494 DirectionDOMRenderer.prototype._setNeedsRender = function () {
22495 if (this._node != null) {
22496 this._needsRender = true;
22499 DirectionDOMRenderer.prototype._clearEdges = function () {
22500 this._stepEdges = [];
22501 this._turnEdges = [];
22502 this._panoEdges = [];
22503 this._sequenceEdgeKeys = [];
22505 DirectionDOMRenderer.prototype._setEdges = function (edgeStatus, sequence) {
22506 this._stepEdges = [];
22507 this._turnEdges = [];
22508 this._panoEdges = [];
22509 this._sequenceEdgeKeys = [];
22510 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
22512 var direction = edge.data.direction;
22513 if (this._stepDirections.indexOf(direction) > -1) {
22514 this._stepEdges.push(edge);
22517 if (this._turnDirections.indexOf(direction) > -1) {
22518 this._turnEdges.push(edge);
22521 if (edge.data.direction === Edge_1.EdgeDirection.Pano) {
22522 this._panoEdges.push(edge);
22525 if (this._distinguishSequence && sequence != null) {
22526 var edges = this._panoEdges
22527 .concat(this._stepEdges)
22528 .concat(this._turnEdges);
22529 for (var _b = 0, edges_1 = edges; _b < edges_1.length; _b++) {
22530 var edge = edges_1[_b];
22531 var edgeKey = edge.to;
22532 for (var _c = 0, _d = sequence.keys; _c < _d.length; _c++) {
22533 var sequenceKey = _d[_c];
22534 if (sequenceKey === edgeKey) {
22535 this._sequenceEdgeKeys.push(edgeKey);
22542 DirectionDOMRenderer.prototype._createPanoArrows = function (navigator, rotation) {
22544 for (var _i = 0, _a = this._panoEdges; _i < _a.length; _i++) {
22545 var panoEdge = _a[_i];
22546 arrows.push(this._createVNodeByKey(navigator, panoEdge.to, panoEdge.data.worldMotionAzimuth, rotation, this._calculator.outerRadius, "DirectionsArrowPano"));
22548 for (var _b = 0, _c = this._stepEdges; _b < _c.length; _b++) {
22549 var stepEdge = _c[_b];
22550 arrows.push(this._createPanoToPerspectiveArrow(navigator, stepEdge.to, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction));
22554 DirectionDOMRenderer.prototype._createPanoToPerspectiveArrow = function (navigator, key, azimuth, rotation, direction) {
22555 var threshold = Math.PI / 8;
22556 var relativePhi = rotation.phi;
22557 switch (direction) {
22558 case Edge_1.EdgeDirection.StepBackward:
22559 relativePhi = rotation.phi - Math.PI;
22561 case Edge_1.EdgeDirection.StepLeft:
22562 relativePhi = rotation.phi + Math.PI / 2;
22564 case Edge_1.EdgeDirection.StepRight:
22565 relativePhi = rotation.phi - Math.PI / 2;
22570 if (Math.abs(this._spatial.wrapAngle(azimuth - relativePhi)) < threshold) {
22571 return this._createVNodeByKey(navigator, key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowStep");
22573 return this._createVNodeDisabled(key, azimuth, rotation);
22575 DirectionDOMRenderer.prototype._createPerspectiveToPanoArrows = function (navigator, rotation) {
22577 for (var _i = 0, _a = this._panoEdges; _i < _a.length; _i++) {
22578 var panoEdge = _a[_i];
22579 arrows.push(this._createVNodeByKey(navigator, panoEdge.to, panoEdge.data.worldMotionAzimuth, rotation, this._calculator.innerRadius, "DirectionsArrowPano", true));
22583 DirectionDOMRenderer.prototype._createStepArrows = function (navigator, rotation) {
22585 for (var _i = 0, _a = this._stepEdges; _i < _a.length; _i++) {
22586 var stepEdge = _a[_i];
22587 arrows.push(this._createVNodeByDirection(navigator, stepEdge.to, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction));
22591 DirectionDOMRenderer.prototype._createTurnArrows = function (navigator) {
22593 for (var _i = 0, _a = this._turnEdges; _i < _a.length; _i++) {
22594 var turnEdge = _a[_i];
22595 var direction = turnEdge.data.direction;
22596 var name_1 = this._turnNames[direction];
22597 turns.push(this._createVNodeByTurn(navigator, turnEdge.to, name_1, direction));
22601 DirectionDOMRenderer.prototype._createVNodeByKey = function (navigator, key, azimuth, rotation, offset, className, shiftVertically) {
22602 var onClick = function (e) {
22603 navigator.moveToKey$(key)
22604 .subscribe(function (node) { return; }, function (error) { console.error(error); });
22606 return this._createVNode(key, azimuth, rotation, offset, className, "DirectionsCircle", onClick, shiftVertically);
22608 DirectionDOMRenderer.prototype._createVNodeByDirection = function (navigator, key, azimuth, rotation, direction) {
22609 var onClick = function (e) {
22610 navigator.moveDir$(direction)
22611 .subscribe(function (node) { return; }, function (error) { console.error(error); });
22613 return this._createVNode(key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowStep", "DirectionsCircle", onClick);
22615 DirectionDOMRenderer.prototype._createVNodeByTurn = function (navigator, key, className, direction) {
22616 var onClick = function (e) {
22617 navigator.moveDir$(direction)
22618 .subscribe(function (node) { return; }, function (error) { console.error(error); });
22621 height: this._calculator.turnCircleSizeCss,
22622 transform: "rotate(0)",
22623 width: this._calculator.turnCircleSizeCss,
22625 switch (direction) {
22626 case Edge_1.EdgeDirection.TurnLeft:
22627 style.left = "5px";
22630 case Edge_1.EdgeDirection.TurnRight:
22631 style.right = "5px";
22634 case Edge_1.EdgeDirection.TurnU:
22635 style.left = "5px";
22636 style.bottom = "5px";
22641 var circleProperties = {
22648 var circleClassName = "TurnCircle";
22649 if (this._sequenceEdgeKeys.indexOf(key) > -1) {
22650 circleClassName += "Sequence";
22652 if (this._highlightKey === key) {
22653 circleClassName += "Highlight";
22655 var turn = vd.h("div." + className, {}, []);
22656 return vd.h("div." + circleClassName, circleProperties, [turn]);
22658 DirectionDOMRenderer.prototype._createVNodeDisabled = function (key, azimuth, rotation) {
22659 return this._createVNode(key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowDisabled", "DirectionsCircleDisabled");
22661 DirectionDOMRenderer.prototype._createVNode = function (key, azimuth, rotation, radius, className, circleClassName, onClick, shiftVertically) {
22662 var translation = this._calculator.angleToCoordinates(azimuth - rotation.phi);
22663 // rotate 90 degrees clockwise and flip over X-axis
22664 var translationX = Math.round(-radius * translation[1] + 0.5 * this._calculator.containerWidth);
22665 var translationY = Math.round(-radius * translation[0] + 0.5 * this._calculator.containerHeight);
22666 var shadowTranslation = this._calculator.relativeAngleToCoordiantes(azimuth, rotation.phi);
22667 var shadowOffset = this._calculator.shadowOffset;
22668 var shadowTranslationX = -shadowOffset * shadowTranslation[1];
22669 var shadowTranslationY = shadowOffset * shadowTranslation[0];
22670 var filter = "drop-shadow(" + shadowTranslationX + "px " + shadowTranslationY + "px 1px rgba(0,0,0,0.8))";
22673 "-webkit-filter": filter,
22677 var chevron = vd.h("div." + className, properties, []);
22678 var azimuthDeg = -this._spatial.radToDeg(azimuth - rotation.phi);
22679 var circleTransform = shiftVertically ?
22680 "translate(" + translationX + "px, " + translationY + "px) rotate(" + azimuthDeg + "deg) translateZ(-0.01px)" :
22681 "translate(" + translationX + "px, " + translationY + "px) rotate(" + azimuthDeg + "deg)";
22682 var circleProperties = {
22683 attributes: { "data-key": key },
22686 height: this._calculator.stepCircleSizeCss,
22687 marginLeft: this._calculator.stepCircleMarginCss,
22688 marginTop: this._calculator.stepCircleMarginCss,
22689 transform: circleTransform,
22690 width: this._calculator.stepCircleSizeCss,
22693 if (this._sequenceEdgeKeys.indexOf(key) > -1) {
22694 circleClassName += "Sequence";
22696 if (this._highlightKey === key) {
22697 circleClassName += "Highlight";
22699 return vd.h("div." + circleClassName, circleProperties, [chevron]);
22701 DirectionDOMRenderer.prototype._getContainer = function (steps, turns, rotation) {
22702 // edge does not handle hover on perspective transforms.
22703 var transform = this._isEdge ?
22705 "perspective(" + this._calculator.containerWidthCss + ") rotateX(60deg)";
22707 oncontextmenu: function (event) { event.preventDefault(); },
22709 bottom: this._calculator.containerBottomCss,
22710 height: this._calculator.containerHeightCss,
22711 left: this._calculator.containerLeftCss,
22712 marginLeft: this._calculator.containerMarginCss,
22713 transform: transform,
22714 width: this._calculator.containerWidthCss,
22717 return vd.h("div.DirectionsPerspective", properties, turns.concat(steps));
22719 return DirectionDOMRenderer;
22721 exports.DirectionDOMRenderer = DirectionDOMRenderer;
22722 exports.default = DirectionDOMRenderer;
22724 },{"../../Component":226,"../../Edge":227,"../../Geo":229,"virtual-dom":182}],256:[function(require,module,exports){
22726 var __extends = (this && this.__extends) || (function () {
22727 var extendStatics = Object.setPrototypeOf ||
22728 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
22729 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
22730 return function (d, b) {
22731 extendStatics(d, b);
22732 function __() { this.constructor = d; }
22733 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22736 Object.defineProperty(exports, "__esModule", { value: true });
22737 var Observable_1 = require("rxjs/Observable");
22738 var Subject_1 = require("rxjs/Subject");
22739 require("rxjs/add/operator/catch");
22740 require("rxjs/add/operator/combineLatest");
22741 require("rxjs/add/operator/debounceTime");
22742 require("rxjs/add/operator/distinctUntilChanged");
22743 require("rxjs/add/operator/filter");
22744 require("rxjs/add/operator/map");
22745 require("rxjs/add/operator/pairwise");
22746 require("rxjs/add/operator/publish");
22747 require("rxjs/add/operator/publishReplay");
22748 require("rxjs/add/operator/scan");
22749 require("rxjs/add/operator/skipWhile");
22750 require("rxjs/add/operator/startWith");
22751 require("rxjs/add/operator/switchMap");
22752 require("rxjs/add/operator/takeUntil");
22753 require("rxjs/add/operator/withLatestFrom");
22754 var Component_1 = require("../../Component");
22755 var Render_1 = require("../../Render");
22756 var Tiles_1 = require("../../Tiles");
22757 var Utils_1 = require("../../Utils");
22758 var ImagePlaneComponent = (function (_super) {
22759 __extends(ImagePlaneComponent, _super);
22760 function ImagePlaneComponent(name, container, navigator) {
22761 var _this = _super.call(this, name, container, navigator) || this;
22762 _this._imageTileLoader = new Tiles_1.ImageTileLoader(Utils_1.Urls.tileScheme, Utils_1.Urls.tileDomain, Utils_1.Urls.origin);
22763 _this._roiCalculator = new Tiles_1.RegionOfInterestCalculator();
22764 _this._rendererOperation$ = new Subject_1.Subject();
22765 _this._rendererCreator$ = new Subject_1.Subject();
22766 _this._rendererDisposer$ = new Subject_1.Subject();
22767 _this._renderer$ = _this._rendererOperation$
22768 .scan(function (renderer, operation) {
22769 return operation(renderer);
22771 .filter(function (renderer) {
22772 return renderer != null;
22774 .distinctUntilChanged(undefined, function (renderer) {
22775 return renderer.frameId;
22777 _this._rendererCreator$
22779 return function (renderer) {
22780 if (renderer != null) {
22781 throw new Error("Multiple image plane states can not be created at the same time");
22783 return new Component_1.ImagePlaneGLRenderer();
22786 .subscribe(_this._rendererOperation$);
22787 _this._rendererDisposer$
22789 return function (renderer) {
22790 renderer.dispose();
22794 .subscribe(_this._rendererOperation$);
22797 ImagePlaneComponent.prototype._activate = function () {
22799 this._rendererSubscription = this._renderer$
22800 .map(function (renderer) {
22804 frameId: renderer.frameId,
22805 needsRender: renderer.needsRender,
22806 render: renderer.render.bind(renderer),
22807 stage: Render_1.GLRenderStage.Background,
22810 renderer.clearNeedsRender();
22813 .subscribe(this._container.glRenderer.render$);
22814 this._rendererCreator$.next(null);
22815 this._stateSubscription = this._navigator.stateService.currentState$
22816 .map(function (frame) {
22817 return function (renderer) {
22818 renderer.updateFrame(frame);
22822 .subscribe(this._rendererOperation$);
22823 var textureProvider$ = this._navigator.stateService.currentState$
22824 .distinctUntilChanged(undefined, function (frame) {
22825 return frame.state.currentNode.key;
22827 .combineLatest(this._configuration$)
22828 .filter(function (args) {
22829 return args[1].imageTiling === true;
22831 .map(function (args) {
22834 .withLatestFrom(this._container.glRenderer.webGLRenderer$, this._container.renderService.size$)
22835 .map(function (args) {
22836 var state = args[0].state;
22837 var renderer = args[1];
22838 var viewportSize = args[2];
22839 var currentNode = state.currentNode;
22840 var currentTransform = state.currentTransform;
22841 var tileSize = Math.max(viewportSize.width, viewportSize.height) > 1024 ? 1024 : 512;
22842 return new Tiles_1.TextureProvider(currentNode.key, currentTransform.basicWidth, currentTransform.basicHeight, tileSize, currentNode.image, _this._imageTileLoader, new Tiles_1.ImageTileStore(), renderer);
22846 this._textureProviderSubscription = textureProvider$.subscribe(function () { });
22847 this._setTextureProviderSubscription = textureProvider$
22848 .map(function (provider) {
22849 return function (renderer) {
22850 renderer.setTextureProvider(provider.key, provider);
22854 .subscribe(this._rendererOperation$);
22855 this._abortTextureProviderSubscription = textureProvider$
22857 .subscribe(function (pair) {
22858 var previous = pair[0];
22861 var roiTrigger$ = this._container.renderService.renderCameraFrame$
22862 .map(function (renderCamera) {
22864 renderCamera.camera.position.clone(),
22865 renderCamera.camera.lookat.clone(),
22866 renderCamera.zoom.valueOf()
22870 .skipWhile(function (pls) {
22871 return pls[1][2] - pls[0][2] < 0 || pls[1][2] === 0;
22873 .map(function (pls) {
22874 var samePosition = pls[0][0].equals(pls[1][0]);
22875 var sameLookat = pls[0][1].equals(pls[1][1]);
22876 var sameZoom = pls[0][2] === pls[1][2];
22877 return samePosition && sameLookat && sameZoom;
22879 .distinctUntilChanged()
22880 .filter(function (stalled) {
22883 .switchMap(function (stalled) {
22884 return _this._container.renderService.renderCameraFrame$
22887 .withLatestFrom(this._container.renderService.size$, this._navigator.stateService.currentTransform$);
22888 this._setRegionOfInterestSubscription = textureProvider$
22889 .switchMap(function (provider) {
22891 .map(function (args) {
22893 _this._roiCalculator.computeRegionOfInterest(args[0], args[1], args[2]),
22898 .filter(function (args) {
22899 return !args[1].disposed;
22901 .subscribe(function (args) {
22903 var provider = args[1];
22904 provider.setRegionOfInterest(roi);
22906 var hasTexture$ = textureProvider$
22907 .switchMap(function (provider) {
22908 return provider.hasTexture$;
22913 this._hasTextureSubscription = hasTexture$.subscribe(function () { });
22914 var nodeImage$ = this._navigator.stateService.currentNode$
22915 .debounceTime(1000)
22916 .withLatestFrom(hasTexture$)
22917 .filter(function (args) {
22920 .map(function (args) {
22923 .filter(function (node) {
22925 Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize :
22926 Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize;
22928 .switchMap(function (node) {
22929 var baseImageSize = node.pano ?
22930 Utils_1.Settings.basePanoramaSize :
22931 Utils_1.Settings.baseImageSize;
22932 if (Math.max(node.image.width, node.image.height) > baseImageSize) {
22933 return Observable_1.Observable.empty();
22936 .cacheImage$(Utils_1.Settings.maxImageSize)
22937 .map(function (n) {
22938 return [n.image, n];
22941 .takeUntil(hasTexture$
22942 .filter(function (hasTexture) {
22945 .catch(function (error, caught) {
22946 console.error("Failed to fetch high res image (" + node.key + ")", error);
22947 return Observable_1.Observable.empty();
22952 this._updateBackgroundSubscription = nodeImage$
22953 .withLatestFrom(textureProvider$)
22954 .subscribe(function (args) {
22955 if (args[0][1].key !== args[1].key ||
22956 args[1].disposed) {
22959 args[1].updateBackground(args[0][0]);
22961 this._updateTextureImageSubscription = nodeImage$
22962 .map(function (imn) {
22963 return function (renderer) {
22964 renderer.updateTextureImage(imn[0], imn[1]);
22968 .subscribe(this._rendererOperation$);
22970 ImagePlaneComponent.prototype._deactivate = function () {
22971 this._rendererDisposer$.next(null);
22972 this._abortTextureProviderSubscription.unsubscribe();
22973 this._hasTextureSubscription.unsubscribe();
22974 this._rendererSubscription.unsubscribe();
22975 this._setRegionOfInterestSubscription.unsubscribe();
22976 this._setTextureProviderSubscription.unsubscribe();
22977 this._stateSubscription.unsubscribe();
22978 this._textureProviderSubscription.unsubscribe();
22979 this._updateBackgroundSubscription.unsubscribe();
22980 this._updateTextureImageSubscription.unsubscribe();
22982 ImagePlaneComponent.prototype._getDefaultConfiguration = function () {
22983 return { imageTiling: false };
22985 ImagePlaneComponent.componentName = "imagePlane";
22986 return ImagePlaneComponent;
22987 }(Component_1.Component));
22988 exports.ImagePlaneComponent = ImagePlaneComponent;
22989 Component_1.ComponentService.register(ImagePlaneComponent);
22990 exports.default = ImagePlaneComponent;
22992 },{"../../Component":226,"../../Render":232,"../../Tiles":235,"../../Utils":236,"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":73,"rxjs/add/operator/skipWhile":77,"rxjs/add/operator/startWith":78,"rxjs/add/operator/switchMap":79,"rxjs/add/operator/takeUntil":81,"rxjs/add/operator/withLatestFrom":83}],257:[function(require,module,exports){
22994 /// <reference path="../../../typings/index.d.ts" />
22995 Object.defineProperty(exports, "__esModule", { value: true });
22996 var THREE = require("three");
22997 var Component_1 = require("../../Component");
22998 var ImagePlaneFactory = (function () {
22999 function ImagePlaneFactory(imagePlaneDepth, imageSphereRadius) {
23000 this._imagePlaneDepth = imagePlaneDepth != null ? imagePlaneDepth : 200;
23001 this._imageSphereRadius = imageSphereRadius != null ? imageSphereRadius : 200;
23003 ImagePlaneFactory.prototype.createMesh = function (node, transform) {
23004 var mesh = node.pano ?
23005 this._createImageSphere(node, transform) :
23006 this._createImagePlane(node, transform);
23009 ImagePlaneFactory.prototype._createImageSphere = function (node, transform) {
23010 var texture = this._createTexture(node.image);
23011 var materialParameters = this._createSphereMaterialParameters(transform, texture);
23012 var material = new THREE.ShaderMaterial(materialParameters);
23013 var mesh = this._useMesh(transform, node) ?
23014 new THREE.Mesh(this._getImageSphereGeo(transform, node), material) :
23015 new THREE.Mesh(this._getFlatImageSphereGeo(transform), material);
23018 ImagePlaneFactory.prototype._createImagePlane = function (node, transform) {
23019 var texture = this._createTexture(node.image);
23020 var materialParameters = this._createPlaneMaterialParameters(transform, texture);
23021 var material = new THREE.ShaderMaterial(materialParameters);
23022 var geometry = this._useMesh(transform, node) ?
23023 this._getImagePlaneGeo(transform, node) :
23024 this._getFlatImagePlaneGeo(transform);
23025 return new THREE.Mesh(geometry, material);
23027 ImagePlaneFactory.prototype._createSphereMaterialParameters = function (transform, texture) {
23028 var gpano = transform.gpano;
23029 var halfCroppedWidth = (gpano.FullPanoWidthPixels - gpano.CroppedAreaImageWidthPixels) / 2;
23030 var phiShift = 2 * Math.PI * (gpano.CroppedAreaLeftPixels - halfCroppedWidth) / gpano.FullPanoWidthPixels;
23031 var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels;
23032 var halfCroppedHeight = (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels) / 2;
23033 var thetaShift = Math.PI * (halfCroppedHeight - gpano.CroppedAreaTopPixels) / gpano.FullPanoHeightPixels;
23034 var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels;
23035 var materialParameters = {
23037 fragmentShader: Component_1.ImagePlaneShaders.equirectangular.fragment,
23038 side: THREE.DoubleSide,
23055 value: transform.rt,
23063 value: thetaLength,
23070 vertexShader: Component_1.ImagePlaneShaders.equirectangular.vertex,
23072 return materialParameters;
23074 ImagePlaneFactory.prototype._createPlaneMaterialParameters = function (transform, texture) {
23075 var materialParameters = {
23077 fragmentShader: Component_1.ImagePlaneShaders.perspective.fragment,
23078 side: THREE.DoubleSide,
23083 value: new THREE.Vector4(0, 0, 1, 1),
23091 value: transform.projectorMatrix(),
23098 vertexShader: Component_1.ImagePlaneShaders.perspective.vertex,
23100 return materialParameters;
23102 ImagePlaneFactory.prototype._createTexture = function (image) {
23103 var texture = new THREE.Texture(image);
23104 texture.minFilter = THREE.LinearFilter;
23105 texture.needsUpdate = true;
23108 ImagePlaneFactory.prototype._useMesh = function (transform, node) {
23109 return node.mesh.vertices.length && transform.hasValidScale;
23111 ImagePlaneFactory.prototype._getImageSphereGeo = function (transform, node) {
23112 var t = new THREE.Matrix4().getInverse(transform.srt);
23113 // push everything at least 5 meters in front of the camera
23114 var minZ = 5.0 * transform.scale;
23115 var maxZ = this._imageSphereRadius * transform.scale;
23116 var vertices = node.mesh.vertices;
23117 var numVertices = vertices.length / 3;
23118 var positions = new Float32Array(vertices.length);
23119 for (var i = 0; i < numVertices; ++i) {
23121 var x = vertices[index + 0];
23122 var y = vertices[index + 1];
23123 var z = vertices[index + 2];
23124 var l = Math.sqrt(x * x + y * y + z * z);
23125 var boundedL = Math.max(minZ, Math.min(l, maxZ));
23126 var factor = boundedL / l;
23127 var p = new THREE.Vector3(x * factor, y * factor, z * factor);
23129 positions[index + 0] = p.x;
23130 positions[index + 1] = p.y;
23131 positions[index + 2] = p.z;
23133 var faces = node.mesh.faces;
23134 var indices = new Uint16Array(faces.length);
23135 for (var i = 0; i < faces.length; ++i) {
23136 indices[i] = faces[i];
23138 var geometry = new THREE.BufferGeometry();
23139 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
23140 geometry.setIndex(new THREE.BufferAttribute(indices, 1));
23143 ImagePlaneFactory.prototype._getImagePlaneGeo = function (transform, node) {
23144 var t = new THREE.Matrix4().getInverse(transform.srt);
23145 // push everything at least 5 meters in front of the camera
23146 var minZ = 5.0 * transform.scale;
23147 var maxZ = this._imagePlaneDepth * transform.scale;
23148 var vertices = node.mesh.vertices;
23149 var numVertices = vertices.length / 3;
23150 var positions = new Float32Array(vertices.length);
23151 for (var i = 0; i < numVertices; ++i) {
23153 var x = vertices[index + 0];
23154 var y = vertices[index + 1];
23155 var z = vertices[index + 2];
23156 var boundedZ = Math.max(minZ, Math.min(z, maxZ));
23157 var factor = boundedZ / z;
23158 var p = new THREE.Vector3(x * factor, y * factor, boundedZ);
23160 positions[index + 0] = p.x;
23161 positions[index + 1] = p.y;
23162 positions[index + 2] = p.z;
23164 var faces = node.mesh.faces;
23165 var indices = new Uint16Array(faces.length);
23166 for (var i = 0; i < faces.length; ++i) {
23167 indices[i] = faces[i];
23169 var geometry = new THREE.BufferGeometry();
23170 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
23171 geometry.setIndex(new THREE.BufferAttribute(indices, 1));
23174 ImagePlaneFactory.prototype._getFlatImageSphereGeo = function (transform) {
23175 var gpano = transform.gpano;
23176 var phiStart = 2 * Math.PI * gpano.CroppedAreaLeftPixels / gpano.FullPanoWidthPixels;
23177 var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels;
23178 var thetaStart = Math.PI *
23179 (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels - gpano.CroppedAreaTopPixels) /
23180 gpano.FullPanoHeightPixels;
23181 var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels;
23182 var geometry = new THREE.SphereGeometry(this._imageSphereRadius, 20, 40, phiStart - Math.PI / 2, phiLength, thetaStart, thetaLength);
23183 geometry.applyMatrix(new THREE.Matrix4().getInverse(transform.rt));
23186 ImagePlaneFactory.prototype._getFlatImagePlaneGeo = function (transform) {
23187 var width = transform.width;
23188 var height = transform.height;
23189 var size = Math.max(width, height);
23190 var dx = width / 2.0 / size;
23191 var dy = height / 2.0 / size;
23193 vertices.push(transform.unprojectSfM([-dx, -dy], this._imagePlaneDepth));
23194 vertices.push(transform.unprojectSfM([dx, -dy], this._imagePlaneDepth));
23195 vertices.push(transform.unprojectSfM([dx, dy], this._imagePlaneDepth));
23196 vertices.push(transform.unprojectSfM([-dx, dy], this._imagePlaneDepth));
23197 var positions = new Float32Array(12);
23198 for (var i = 0; i < vertices.length; i++) {
23200 positions[index + 0] = vertices[i][0];
23201 positions[index + 1] = vertices[i][1];
23202 positions[index + 2] = vertices[i][2];
23204 var indices = new Uint16Array(6);
23211 var geometry = new THREE.BufferGeometry();
23212 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
23213 geometry.setIndex(new THREE.BufferAttribute(indices, 1));
23216 return ImagePlaneFactory;
23218 exports.ImagePlaneFactory = ImagePlaneFactory;
23219 exports.default = ImagePlaneFactory;
23221 },{"../../Component":226,"three":176}],258:[function(require,module,exports){
23223 /// <reference path="../../../typings/index.d.ts" />
23224 Object.defineProperty(exports, "__esModule", { value: true });
23225 var Component_1 = require("../../Component");
23226 var Geo_1 = require("../../Geo");
23227 var ImagePlaneGLRenderer = (function () {
23228 function ImagePlaneGLRenderer() {
23229 this._imagePlaneFactory = new Component_1.ImagePlaneFactory();
23230 this._imagePlaneScene = new Component_1.ImagePlaneScene();
23232 this._alphaOld = 0;
23233 this._fadeOutSpeed = 0.05;
23234 this._lastCamera = new Geo_1.Camera();
23235 this._epsilon = 0.000001;
23236 this._currentKey = null;
23237 this._previousKey = null;
23238 this._providerDisposers = {};
23240 this._needsRender = false;
23242 Object.defineProperty(ImagePlaneGLRenderer.prototype, "frameId", {
23244 return this._frameId;
23249 Object.defineProperty(ImagePlaneGLRenderer.prototype, "needsRender", {
23251 return this._needsRender;
23256 ImagePlaneGLRenderer.prototype.indicateNeedsRender = function () {
23257 this._needsRender = true;
23259 ImagePlaneGLRenderer.prototype.updateFrame = function (frame) {
23260 this._updateFrameId(frame.id);
23261 this._needsRender = this._updateAlpha(frame.state.alpha) || this._needsRender;
23262 this._needsRender = this._updateAlphaOld(frame.state.alpha) || this._needsRender;
23263 this._needsRender = this._updateImagePlanes(frame.state) || this._needsRender;
23265 ImagePlaneGLRenderer.prototype.setTextureProvider = function (key, provider) {
23267 if (key !== this._currentKey) {
23270 var createdSubscription = provider.textureCreated$
23271 .subscribe(function (texture) {
23272 _this._updateTexture(texture);
23274 var updatedSubscription = provider.textureUpdated$
23275 .subscribe(function (updated) {
23276 _this._needsRender = true;
23278 var dispose = function () {
23279 createdSubscription.unsubscribe();
23280 updatedSubscription.unsubscribe();
23281 provider.dispose();
23283 if (key in this._providerDisposers) {
23284 var disposeProvider = this._providerDisposers[key];
23286 delete this._providerDisposers[key];
23288 this._providerDisposers[key] = dispose;
23290 ImagePlaneGLRenderer.prototype._updateTexture = function (texture) {
23291 this._needsRender = true;
23292 for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
23293 var plane = _a[_i];
23294 var material = plane.material;
23295 var oldTexture = material.uniforms.projectorTex.value;
23296 material.uniforms.projectorTex.value = null;
23297 oldTexture.dispose();
23298 material.uniforms.projectorTex.value = texture;
23301 ImagePlaneGLRenderer.prototype.updateTextureImage = function (image, node) {
23302 if (this._currentKey !== node.key) {
23305 this._needsRender = true;
23306 for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
23307 var plane = _a[_i];
23308 var material = plane.material;
23309 var texture = material.uniforms.projectorTex.value;
23310 texture.image = image;
23311 texture.needsUpdate = true;
23314 ImagePlaneGLRenderer.prototype.render = function (perspectiveCamera, renderer) {
23315 var planeAlpha = this._imagePlaneScene.imagePlanesOld.length ? 1 : this._alpha;
23316 for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
23317 var plane = _a[_i];
23318 plane.material.uniforms.opacity.value = planeAlpha;
23320 for (var _b = 0, _c = this._imagePlaneScene.imagePlanesOld; _b < _c.length; _b++) {
23321 var plane = _c[_b];
23322 plane.material.uniforms.opacity.value = this._alphaOld;
23324 renderer.render(this._imagePlaneScene.scene, perspectiveCamera);
23325 renderer.render(this._imagePlaneScene.sceneOld, perspectiveCamera);
23326 for (var _d = 0, _e = this._imagePlaneScene.imagePlanes; _d < _e.length; _d++) {
23327 var plane = _e[_d];
23328 plane.material.uniforms.opacity.value = this._alpha;
23330 renderer.render(this._imagePlaneScene.scene, perspectiveCamera);
23332 ImagePlaneGLRenderer.prototype.clearNeedsRender = function () {
23333 this._needsRender = false;
23335 ImagePlaneGLRenderer.prototype.dispose = function () {
23336 this._imagePlaneScene.clear();
23338 ImagePlaneGLRenderer.prototype._updateFrameId = function (frameId) {
23339 this._frameId = frameId;
23341 ImagePlaneGLRenderer.prototype._updateAlpha = function (alpha) {
23342 if (alpha === this._alpha) {
23345 this._alpha = alpha;
23348 ImagePlaneGLRenderer.prototype._updateAlphaOld = function (alpha) {
23349 if (alpha < 1 || this._alphaOld === 0) {
23352 this._alphaOld = Math.max(0, this._alphaOld - this._fadeOutSpeed);
23355 ImagePlaneGLRenderer.prototype._updateImagePlanes = function (state) {
23356 if (state.currentNode == null || state.currentNode.key === this._currentKey) {
23359 var previousKey = state.previousNode != null ? state.previousNode.key : null;
23360 var currentKey = state.currentNode.key;
23361 if (this._previousKey !== previousKey &&
23362 this._previousKey !== currentKey &&
23363 this._previousKey in this._providerDisposers) {
23364 var disposeProvider = this._providerDisposers[this._previousKey];
23366 delete this._providerDisposers[this._previousKey];
23368 if (previousKey != null) {
23369 if (previousKey !== this._currentKey && previousKey !== this._previousKey) {
23370 var previousMesh = this._imagePlaneFactory.createMesh(state.previousNode, state.previousTransform);
23371 this._imagePlaneScene.updateImagePlanes([previousMesh]);
23373 this._previousKey = previousKey;
23375 this._currentKey = currentKey;
23376 var currentMesh = this._imagePlaneFactory.createMesh(state.currentNode, state.currentTransform);
23377 this._imagePlaneScene.updateImagePlanes([currentMesh]);
23378 this._alphaOld = 1;
23381 return ImagePlaneGLRenderer;
23383 exports.ImagePlaneGLRenderer = ImagePlaneGLRenderer;
23384 exports.default = ImagePlaneGLRenderer;
23386 },{"../../Component":226,"../../Geo":229}],259:[function(require,module,exports){
23388 /// <reference path="../../../typings/index.d.ts" />
23389 Object.defineProperty(exports, "__esModule", { value: true });
23390 var THREE = require("three");
23391 var ImagePlaneScene = (function () {
23392 function ImagePlaneScene() {
23393 this.scene = new THREE.Scene();
23394 this.sceneOld = new THREE.Scene();
23395 this.imagePlanes = [];
23396 this.imagePlanesOld = [];
23398 ImagePlaneScene.prototype.updateImagePlanes = function (planes) {
23399 this._dispose(this.imagePlanesOld, this.sceneOld);
23400 for (var _i = 0, _a = this.imagePlanes; _i < _a.length; _i++) {
23401 var plane = _a[_i];
23402 this.scene.remove(plane);
23403 this.sceneOld.add(plane);
23405 for (var _b = 0, planes_1 = planes; _b < planes_1.length; _b++) {
23406 var plane = planes_1[_b];
23407 this.scene.add(plane);
23409 this.imagePlanesOld = this.imagePlanes;
23410 this.imagePlanes = planes;
23412 ImagePlaneScene.prototype.addImagePlanes = function (planes) {
23413 for (var _i = 0, planes_2 = planes; _i < planes_2.length; _i++) {
23414 var plane = planes_2[_i];
23415 this.scene.add(plane);
23416 this.imagePlanes.push(plane);
23419 ImagePlaneScene.prototype.addImagePlanesOld = function (planes) {
23420 for (var _i = 0, planes_3 = planes; _i < planes_3.length; _i++) {
23421 var plane = planes_3[_i];
23422 this.sceneOld.add(plane);
23423 this.imagePlanesOld.push(plane);
23426 ImagePlaneScene.prototype.setImagePlanes = function (planes) {
23428 this.addImagePlanes(planes);
23430 ImagePlaneScene.prototype.setImagePlanesOld = function (planes) {
23432 this.addImagePlanesOld(planes);
23434 ImagePlaneScene.prototype.clear = function () {
23438 ImagePlaneScene.prototype._clear = function () {
23439 this._dispose(this.imagePlanes, this.scene);
23440 this.imagePlanes.length = 0;
23442 ImagePlaneScene.prototype._clearOld = function () {
23443 this._dispose(this.imagePlanesOld, this.sceneOld);
23444 this.imagePlanesOld.length = 0;
23446 ImagePlaneScene.prototype._dispose = function (planes, scene) {
23447 for (var _i = 0, planes_4 = planes; _i < planes_4.length; _i++) {
23448 var plane = planes_4[_i];
23449 scene.remove(plane);
23450 plane.geometry.dispose();
23451 plane.material.dispose();
23452 var texture = plane.material.uniforms.projectorTex.value;
23453 if (texture != null) {
23458 return ImagePlaneScene;
23460 exports.ImagePlaneScene = ImagePlaneScene;
23461 exports.default = ImagePlaneScene;
23463 },{"three":176}],260:[function(require,module,exports){
23465 /// <reference path="../../../typings/index.d.ts" />
23466 Object.defineProperty(exports, "__esModule", { value: true });
23468 var path = require("path");
23469 var ImagePlaneShaders = (function () {
23470 function ImagePlaneShaders() {
23472 ImagePlaneShaders.equirectangular = {
23473 fragment: "#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D projectorTex;\nuniform float opacity;\nuniform float phiLength;\nuniform float phiShift;\nuniform float thetaLength;\nuniform float thetaShift;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n vec3 b = normalize(vRstq.xyz);\n float lat = -asin(b.y);\n float lon = atan(b.x, b.z);\n float x = (lon - phiShift) / phiLength + 0.5;\n float y = (lat - thetaShift) / thetaLength + 0.5;\n vec4 baseColor = texture2D(projectorTex, vec2(x, y));\n baseColor.a = opacity;\n gl_FragColor = baseColor;\n}",
23474 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}",
23476 ImagePlaneShaders.perspective = {
23477 fragment: "#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D projectorTex;\nuniform float opacity;\nuniform vec4 bbox;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n float x = vRstq.x / vRstq.w;\n float y = vRstq.y / vRstq.w;\n\n vec4 baseColor;\n if (x > bbox[0] && y > bbox[1] && x < bbox[2] && y < bbox[3]) {\n baseColor = texture2D(projectorTex, vec2(x, y));\n baseColor.a = opacity;\n } else {\n baseColor = vec4(0.0, 0.0, 0.0, 0.0);\n }\n\n gl_FragColor = baseColor;\n}",
23478 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}",
23480 return ImagePlaneShaders;
23482 exports.ImagePlaneShaders = ImagePlaneShaders;
23484 },{"path":22}],261:[function(require,module,exports){
23486 /// <reference path="../../../typings/index.d.ts" />
23487 var __extends = (this && this.__extends) || (function () {
23488 var extendStatics = Object.setPrototypeOf ||
23489 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23490 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23491 return function (d, b) {
23492 extendStatics(d, b);
23493 function __() { this.constructor = d; }
23494 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23497 Object.defineProperty(exports, "__esModule", { value: true });
23498 var Observable_1 = require("rxjs/Observable");
23499 var Subject_1 = require("rxjs/Subject");
23500 require("rxjs/add/observable/combineLatest");
23501 require("rxjs/add/observable/fromEvent");
23502 require("rxjs/add/observable/of");
23503 require("rxjs/add/observable/zip");
23504 require("rxjs/add/operator/distinctUntilChanged");
23505 require("rxjs/add/operator/filter");
23506 require("rxjs/add/operator/first");
23507 require("rxjs/add/operator/map");
23508 require("rxjs/add/operator/merge");
23509 require("rxjs/add/operator/mergeMap");
23510 require("rxjs/add/operator/scan");
23511 require("rxjs/add/operator/switchMap");
23512 require("rxjs/add/operator/withLatestFrom");
23513 require("rxjs/add/operator/zip");
23514 var State_1 = require("../../State");
23515 var Render_1 = require("../../Render");
23516 var Utils_1 = require("../../Utils");
23517 var Component_1 = require("../../Component");
23518 var SliderState = (function () {
23519 function SliderState() {
23520 this._imagePlaneFactory = new Component_1.ImagePlaneFactory();
23521 this._imagePlaneScene = new Component_1.ImagePlaneScene();
23522 this._currentKey = null;
23523 this._previousKey = null;
23524 this._currentPano = false;
23526 this._glNeedsRender = false;
23527 this._domNeedsRender = true;
23530 Object.defineProperty(SliderState.prototype, "frameId", {
23532 return this._frameId;
23537 Object.defineProperty(SliderState.prototype, "curtain", {
23539 return this._curtain;
23544 Object.defineProperty(SliderState.prototype, "glNeedsRender", {
23546 return this._glNeedsRender;
23551 Object.defineProperty(SliderState.prototype, "domNeedsRender", {
23553 return this._domNeedsRender;
23558 Object.defineProperty(SliderState.prototype, "sliderVisible", {
23560 return this._sliderVisible;
23562 set: function (value) {
23563 this._sliderVisible = value;
23564 this._domNeedsRender = true;
23569 Object.defineProperty(SliderState.prototype, "disabled", {
23571 return this._currentKey == null ||
23572 this._previousKey == null ||
23578 SliderState.prototype.update = function (frame) {
23579 this._updateFrameId(frame.id);
23580 var needsRender = this._updateImagePlanes(frame.state);
23581 this._domNeedsRender = needsRender || this._domNeedsRender;
23582 needsRender = this._updateCurtain(frame.state.alpha) || needsRender;
23583 this._glNeedsRender = needsRender || this._glNeedsRender;
23585 SliderState.prototype.updateTexture = function (image, node) {
23586 var imagePlanes = node.key === this._currentKey ?
23587 this._imagePlaneScene.imagePlanes :
23588 node.key === this._previousKey ?
23589 this._imagePlaneScene.imagePlanesOld :
23591 if (imagePlanes.length === 0) {
23594 this._glNeedsRender = true;
23595 for (var _i = 0, imagePlanes_1 = imagePlanes; _i < imagePlanes_1.length; _i++) {
23596 var plane = imagePlanes_1[_i];
23597 var material = plane.material;
23598 var texture = material.uniforms.projectorTex.value;
23599 texture.image = image;
23600 texture.needsUpdate = true;
23603 SliderState.prototype.render = function (perspectiveCamera, renderer) {
23604 if (!this.disabled) {
23605 renderer.render(this._imagePlaneScene.sceneOld, perspectiveCamera);
23607 renderer.render(this._imagePlaneScene.scene, perspectiveCamera);
23609 SliderState.prototype.dispose = function () {
23610 this._imagePlaneScene.clear();
23612 SliderState.prototype.clearGLNeedsRender = function () {
23613 this._glNeedsRender = false;
23615 SliderState.prototype.clearDomNeedsRender = function () {
23616 this._domNeedsRender = false;
23618 SliderState.prototype._updateFrameId = function (frameId) {
23619 this._frameId = frameId;
23621 SliderState.prototype._updateImagePlanes = function (state) {
23622 if (state.currentNode == null) {
23625 var needsRender = false;
23626 if (state.previousNode != null && this._previousKey !== state.previousNode.key) {
23627 needsRender = true;
23628 this._previousKey = state.previousNode.key;
23629 this._imagePlaneScene.setImagePlanesOld([
23630 this._imagePlaneFactory.createMesh(state.previousNode, state.previousTransform),
23633 if (this._currentKey !== state.currentNode.key) {
23634 needsRender = true;
23635 this._currentKey = state.currentNode.key;
23636 this._currentPano = state.currentNode.pano;
23637 this._imagePlaneScene.setImagePlanes([
23638 this._imagePlaneFactory.createMesh(state.currentNode, state.currentTransform),
23640 if (!this.disabled) {
23641 this._updateBbox();
23644 return needsRender;
23646 SliderState.prototype._updateCurtain = function (alpha) {
23647 if (this.disabled ||
23648 Math.abs(this._curtain - alpha) < 0.001) {
23651 this._curtain = alpha;
23652 this._updateBbox();
23655 SliderState.prototype._updateBbox = function () {
23656 for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
23657 var plane = _a[_i];
23658 var shaderMaterial = plane.material;
23659 var bbox = shaderMaterial.uniforms.bbox.value;
23660 bbox.z = this._curtain;
23663 return SliderState;
23665 var SliderComponent = (function (_super) {
23666 __extends(SliderComponent, _super);
23668 * Create a new slider component instance.
23669 * @class SliderComponent
23671 function SliderComponent(name, container, navigator) {
23672 var _this = _super.call(this, name, container, navigator) || this;
23673 _this._sliderStateOperation$ = new Subject_1.Subject();
23674 _this._sliderStateCreator$ = new Subject_1.Subject();
23675 _this._sliderStateDisposer$ = new Subject_1.Subject();
23676 _this._sliderState$ = _this._sliderStateOperation$
23677 .scan(function (sliderState, operation) {
23678 return operation(sliderState);
23680 .filter(function (sliderState) {
23681 return sliderState != null;
23683 .distinctUntilChanged(undefined, function (sliderState) {
23684 return sliderState.frameId;
23686 _this._sliderStateCreator$
23688 return function (sliderState) {
23689 if (sliderState != null) {
23690 throw new Error("Multiple slider states can not be created at the same time");
23692 return new SliderState();
23695 .subscribe(_this._sliderStateOperation$);
23696 _this._sliderStateDisposer$
23698 return function (sliderState) {
23699 sliderState.dispose();
23703 .subscribe(_this._sliderStateOperation$);
23707 * Set the image keys.
23709 * Configures the component to show the image planes for the supplied image keys.
23711 * @param {keys} ISliderKeys - Slider keys object specifying the images to be shown in the foreground and the background.
23713 SliderComponent.prototype.setKeys = function (keys) {
23714 this.configure({ keys: keys });
23717 * Set the initial position.
23719 * Configures the intial position of the slider. The inital position value will be used when the component is activated.
23721 * @param {number} initialPosition - Initial slider position.
23723 SliderComponent.prototype.setInitialPosition = function (initialPosition) {
23724 this.configure({ initialPosition: initialPosition });
23727 * Set the value controlling if the slider is visible.
23729 * @param {boolean} sliderVisible - Value indicating if the slider should be visible or not.
23731 SliderComponent.prototype.setSliderVisible = function (sliderVisible) {
23732 this.configure({ sliderVisible: sliderVisible });
23734 SliderComponent.prototype._activate = function () {
23736 this._sliderContainer = this._createElement("div", "mapillary-js-slider-container", this._container.element);
23737 this._sliderWrapper = this._createElement("div", "SliderWrapper", this._sliderContainer);
23738 this._sliderControl = this._createElement("input", "SliderControl", this._sliderWrapper);
23739 this._sliderControl.setAttribute("type", "range");
23740 this._sliderControl.setAttribute("min", "0");
23741 this._sliderControl.setAttribute("max", "1000");
23742 this._sliderControl.style.visibility = "hidden";
23743 this._moveToHandler = function (e) {
23744 var curtain = Number(e.target.value) / 1000;
23745 _this._navigator.stateService.moveTo(curtain);
23747 this._sliderControl.addEventListener("input", this._moveToHandler);
23748 this._sliderControl.addEventListener("change", this._moveToHandler);
23749 Observable_1.Observable
23750 .combineLatest(this._navigator.stateService.state$, this._configuration$)
23752 .subscribe(function (_a) {
23753 var state = _a[0], configuration = _a[1];
23754 if (state === State_1.State.Traversing) {
23755 _this._navigator.stateService.wait();
23756 var position = configuration.initialPosition != null ? configuration.initialPosition : 1;
23757 _this._sliderControl.value = (1000 * position).toString();
23758 _this._navigator.stateService.moveTo(position);
23761 this._glRenderSubscription = this._sliderState$
23762 .map(function (sliderState) {
23766 frameId: sliderState.frameId,
23767 needsRender: sliderState.glNeedsRender,
23768 render: sliderState.render.bind(sliderState),
23769 stage: Render_1.GLRenderStage.Background,
23772 sliderState.clearGLNeedsRender();
23775 .subscribe(this._container.glRenderer.render$);
23776 this._domRenderSubscription = this._sliderState$
23777 .filter(function (sliderState) {
23778 return sliderState.domNeedsRender;
23780 .subscribe(function (sliderState) {
23781 _this._sliderControl.value = (1000 * sliderState.curtain).toString();
23782 var visibility = sliderState.disabled || !sliderState.sliderVisible ? "hidden" : "visible";
23783 _this._sliderControl.style.visibility = visibility;
23784 sliderState.clearDomNeedsRender();
23786 this._sliderStateCreator$.next(null);
23787 this._stateSubscription = this._navigator.stateService.currentState$
23788 .map(function (frame) {
23789 return function (sliderState) {
23790 sliderState.update(frame);
23791 return sliderState;
23794 .subscribe(this._sliderStateOperation$);
23795 this._setSliderVisibleSubscription = this._configuration$
23796 .map(function (configuration) {
23797 return configuration.sliderVisible == null || configuration.sliderVisible;
23799 .distinctUntilChanged()
23800 .map(function (sliderVisible) {
23801 return function (sliderState) {
23802 sliderState.sliderVisible = sliderVisible;
23803 return sliderState;
23806 .subscribe(this._sliderStateOperation$);
23807 this._setKeysSubscription = this._configuration$
23808 .filter(function (configuration) {
23809 return configuration.keys != null;
23811 .switchMap(function (configuration) {
23812 return Observable_1.Observable
23813 .zip(_this._catchCacheNode$(configuration.keys.background), _this._catchCacheNode$(configuration.keys.foreground))
23814 .map(function (nodes) {
23815 return { background: nodes[0], foreground: nodes[1] };
23817 .zip(_this._navigator.stateService.currentState$.first())
23818 .map(function (nf) {
23819 return { nodes: nf[0], state: nf[1].state };
23822 .subscribe(function (co) {
23823 if (co.state.currentNode != null &&
23824 co.state.previousNode != null &&
23825 co.state.currentNode.key === co.nodes.foreground.key &&
23826 co.state.previousNode.key === co.nodes.background.key) {
23829 if (co.state.currentNode.key === co.nodes.background.key) {
23830 _this._navigator.stateService.setNodes([co.nodes.foreground]);
23833 if (co.state.currentNode.key === co.nodes.foreground.key &&
23834 co.state.trajectory.length === 1) {
23835 _this._navigator.stateService.prependNodes([co.nodes.background]);
23838 _this._navigator.stateService.setNodes([co.nodes.background]);
23839 _this._navigator.stateService.setNodes([co.nodes.foreground]);
23843 var previousNode$ = this._navigator.stateService.currentState$
23844 .map(function (frame) {
23845 return frame.state.previousNode;
23847 .filter(function (node) {
23848 return node != null;
23850 .distinctUntilChanged(undefined, function (node) {
23853 this._nodeSubscription = Observable_1.Observable
23854 .merge(previousNode$, this._navigator.stateService.currentNode$)
23855 .filter(function (node) {
23857 Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize :
23858 Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize;
23860 .mergeMap(function (node) {
23861 var baseImageSize = node.pano ?
23862 Utils_1.Settings.basePanoramaSize :
23863 Utils_1.Settings.baseImageSize;
23864 if (Math.max(node.image.width, node.image.height) > baseImageSize) {
23865 return Observable_1.Observable.empty();
23867 return node.cacheImage$(Utils_1.Settings.maxImageSize)
23868 .map(function (n) {
23869 return [n.image, n];
23871 .catch(function (error, caught) {
23872 console.error("Failed to fetch high res slider image (" + node.key + ")", error);
23873 return Observable_1.Observable.empty();
23876 .map(function (_a) {
23877 var element = _a[0], node = _a[1];
23878 return function (sliderState) {
23879 sliderState.updateTexture(element, node);
23880 return sliderState;
23883 .subscribe(this._sliderStateOperation$);
23885 SliderComponent.prototype._deactivate = function () {
23887 this._navigator.stateService.state$
23889 .subscribe(function (state) {
23890 if (state === State_1.State.Waiting) {
23891 _this._navigator.stateService.traverse();
23894 this._sliderStateDisposer$.next(null);
23895 this._setKeysSubscription.unsubscribe();
23896 this._setSliderVisibleSubscription.unsubscribe();
23897 this._stateSubscription.unsubscribe();
23898 this._glRenderSubscription.unsubscribe();
23899 this._domRenderSubscription.unsubscribe();
23900 this._nodeSubscription.unsubscribe();
23901 this.configure({ keys: null });
23902 this._sliderControl.removeEventListener("input", this._moveToHandler);
23903 this._sliderControl.removeEventListener("change", this._moveToHandler);
23904 this._container.element.removeChild(this._sliderContainer);
23905 this._moveToHandler = null;
23906 this._sliderControl = null;
23907 this._sliderWrapper = null;
23908 this._sliderContainer = null;
23910 SliderComponent.prototype._getDefaultConfiguration = function () {
23913 SliderComponent.prototype._catchCacheNode$ = function (key) {
23914 return this._navigator.graphService.cacheNode$(key)
23915 .catch(function (error, caught) {
23916 console.error("Failed to cache slider node (" + key + ")", error);
23917 return Observable_1.Observable.empty();
23920 SliderComponent.prototype._createElement = function (tagName, className, container) {
23921 var element = document.createElement(tagName);
23923 element.className = className;
23926 container.appendChild(element);
23930 SliderComponent.componentName = "slider";
23931 return SliderComponent;
23932 }(Component_1.Component));
23933 exports.SliderComponent = SliderComponent;
23934 Component_1.ComponentService.register(SliderComponent);
23935 exports.default = SliderComponent;
23937 },{"../../Component":226,"../../Render":232,"../../State":233,"../../Utils":236,"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":73,"rxjs/add/operator/switchMap":79,"rxjs/add/operator/withLatestFrom":83,"rxjs/add/operator/zip":84}],262:[function(require,module,exports){
23939 Object.defineProperty(exports, "__esModule", { value: true });
23941 (function (CoverState) {
23942 CoverState[CoverState["Hidden"] = 0] = "Hidden";
23943 CoverState[CoverState["Loading"] = 1] = "Loading";
23944 CoverState[CoverState["Visible"] = 2] = "Visible";
23945 })(CoverState = exports.CoverState || (exports.CoverState = {}));
23947 },{}],263:[function(require,module,exports){
23949 Object.defineProperty(exports, "__esModule", { value: true });
23950 var ICoverConfiguration_1 = require("./ICoverConfiguration");
23951 exports.CoverState = ICoverConfiguration_1.CoverState;
23953 },{"./ICoverConfiguration":262}],264:[function(require,module,exports){
23955 /// <reference path="../../../typings/index.d.ts" />
23956 var __extends = (this && this.__extends) || (function () {
23957 var extendStatics = Object.setPrototypeOf ||
23958 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23959 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23960 return function (d, b) {
23961 extendStatics(d, b);
23962 function __() { this.constructor = d; }
23963 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23966 Object.defineProperty(exports, "__esModule", { value: true });
23967 require("rxjs/add/operator/switchMap");
23968 require("rxjs/add/operator/withLatestFrom");
23969 var Component_1 = require("../../Component");
23970 var Edge_1 = require("../../Edge");
23972 * The `KeySequenceNavigationHandler` allows the user navigate through a sequence using the
23973 * following key commands:
23975 * `ALT` + `Up Arrow`: Navigate to next image in the sequence.
23976 * `ALT` + `Down Arrow`: Navigate to previous image in sequence.
23980 * var keyboardComponent = viewer.getComponent("keyboard");
23982 * keyboardComponent.keySequenceNavigation.disable();
23983 * keyboardComponent.keySequenceNavigation.enable();
23985 * var isEnabled = keyboardComponent.keySequenceNavigation.isEnabled;
23988 var KeySequenceNavigationHandler = (function (_super) {
23989 __extends(KeySequenceNavigationHandler, _super);
23990 function KeySequenceNavigationHandler() {
23991 return _super !== null && _super.apply(this, arguments) || this;
23993 KeySequenceNavigationHandler.prototype._enable = function () {
23995 var sequenceEdges$ = this._navigator.stateService.currentNode$
23996 .switchMap(function (node) {
23997 return node.sequenceEdges$;
23999 this._keyDownSubscription = this._container.keyboardService.keyDown$
24000 .withLatestFrom(sequenceEdges$)
24001 .subscribe(function (_a) {
24002 var event = _a[0], edgeStatus = _a[1];
24003 var direction = null;
24004 switch (event.keyCode) {
24006 direction = Edge_1.EdgeDirection.Next;
24009 direction = Edge_1.EdgeDirection.Prev;
24014 event.preventDefault();
24015 if (!event.altKey || event.shiftKey || !edgeStatus.cached) {
24018 for (var _i = 0, _b = edgeStatus.edges; _i < _b.length; _i++) {
24020 if (edge.data.direction === direction) {
24021 _this._navigator.moveToKey$(edge.to)
24022 .subscribe(function (n) { return; }, function (e) { console.error(e); });
24028 KeySequenceNavigationHandler.prototype._disable = function () {
24029 this._keyDownSubscription.unsubscribe();
24031 KeySequenceNavigationHandler.prototype._getConfiguration = function (enable) {
24032 return { keySequenceNavigation: enable };
24034 return KeySequenceNavigationHandler;
24035 }(Component_1.HandlerBase));
24036 exports.KeySequenceNavigationHandler = KeySequenceNavigationHandler;
24037 exports.default = KeySequenceNavigationHandler;
24039 },{"../../Component":226,"../../Edge":227,"rxjs/add/operator/switchMap":79,"rxjs/add/operator/withLatestFrom":83}],265:[function(require,module,exports){
24041 /// <reference path="../../../typings/index.d.ts" />
24042 var __extends = (this && this.__extends) || (function () {
24043 var extendStatics = Object.setPrototypeOf ||
24044 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24045 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24046 return function (d, b) {
24047 extendStatics(d, b);
24048 function __() { this.constructor = d; }
24049 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24052 Object.defineProperty(exports, "__esModule", { value: true });
24053 require("rxjs/add/operator/switchMap");
24054 require("rxjs/add/operator/withLatestFrom");
24055 var Component_1 = require("../../Component");
24056 var Edge_1 = require("../../Edge");
24058 * The `KeySpatialNavigationHandler` allows the user navigate through a sequence using the
24059 * following key commands:
24061 * `Up Arrow`: Step forward.
24062 * `Down Arrow`: Step backward.
24063 * `Left Arrow`: Step to the left.
24064 * `Rigth Arrow`: Step to the right.
24065 * `SHIFT` + `Down Arrow`: Turn around.
24066 * `SHIFT` + `Left Arrow`: Turn to the left.
24067 * `SHIFT` + `Rigth Arrow`: Turn to the right.
24071 * var keyboardComponent = viewer.getComponent("keyboard");
24073 * keyboardComponent.keySpatialNavigation.disable();
24074 * keyboardComponent.keySpatialNavigation.enable();
24076 * var isEnabled = keyboardComponent.keySpatialNavigation.isEnabled;
24079 var KeySpatialNavigationHandler = (function (_super) {
24080 __extends(KeySpatialNavigationHandler, _super);
24081 function KeySpatialNavigationHandler(component, container, navigator, spatial) {
24082 var _this = _super.call(this, component, container, navigator) || this;
24083 _this._spatial = spatial;
24086 KeySpatialNavigationHandler.prototype._enable = function () {
24088 var spatialEdges$ = this._navigator.stateService.currentNode$
24089 .switchMap(function (node) {
24090 return node.spatialEdges$;
24092 this._keyDownSubscription = this._container.keyboardService.keyDown$
24093 .withLatestFrom(spatialEdges$, this._navigator.stateService.currentState$)
24094 .subscribe(function (_a) {
24095 var event = _a[0], edgeStatus = _a[1], frame = _a[2];
24096 var pano = frame.state.currentNode.pano;
24097 var direction = null;
24098 switch (event.keyCode) {
24100 direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.TurnLeft : Edge_1.EdgeDirection.StepLeft;
24103 direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.Pano : Edge_1.EdgeDirection.StepForward;
24106 direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.TurnRight : Edge_1.EdgeDirection.StepRight;
24109 direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.TurnU : Edge_1.EdgeDirection.StepBackward;
24114 event.preventDefault();
24115 if (event.altKey || !edgeStatus.cached ||
24116 (event.shiftKey && pano)) {
24120 _this._moveDir(direction, edgeStatus);
24124 shifts[Edge_1.EdgeDirection.StepBackward] = Math.PI;
24125 shifts[Edge_1.EdgeDirection.StepForward] = 0;
24126 shifts[Edge_1.EdgeDirection.StepLeft] = Math.PI / 2;
24127 shifts[Edge_1.EdgeDirection.StepRight] = -Math.PI / 2;
24128 var phi = _this._rotationFromCamera(frame.state.camera).phi;
24129 var navigationAngle = _this._spatial.wrapAngle(phi + shifts[direction]);
24130 var threshold = Math.PI / 4;
24131 var edges = edgeStatus.edges.filter(function (e) {
24132 return e.data.direction === Edge_1.EdgeDirection.Pano || e.data.direction === direction;
24134 var smallestAngle = Number.MAX_VALUE;
24136 for (var _i = 0, edges_1 = edges; _i < edges_1.length; _i++) {
24137 var edge = edges_1[_i];
24138 var angle = Math.abs(_this._spatial.wrapAngle(edge.data.worldMotionAzimuth - navigationAngle));
24139 if (angle < Math.min(smallestAngle, threshold)) {
24140 smallestAngle = angle;
24144 if (toKey == null) {
24147 _this._moveToKey(toKey);
24151 KeySpatialNavigationHandler.prototype._disable = function () {
24152 this._keyDownSubscription.unsubscribe();
24154 KeySpatialNavigationHandler.prototype._getConfiguration = function (enable) {
24155 return { keySpatialNavigation: enable };
24157 KeySpatialNavigationHandler.prototype._moveDir = function (direction, edgeStatus) {
24158 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
24160 if (edge.data.direction === direction) {
24161 this._moveToKey(edge.to);
24166 KeySpatialNavigationHandler.prototype._moveToKey = function (key) {
24167 this._navigator.moveToKey$(key)
24168 .subscribe(function (n) { }, function (e) { console.error(e); });
24170 KeySpatialNavigationHandler.prototype._rotationFromCamera = function (camera) {
24171 var direction = camera.lookat.clone().sub(camera.position);
24172 var upProjection = direction.clone().dot(camera.up);
24173 var planeProjection = direction.clone().sub(camera.up.clone().multiplyScalar(upProjection));
24174 var phi = Math.atan2(planeProjection.y, planeProjection.x);
24175 var theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
24176 return { phi: phi, theta: theta };
24178 return KeySpatialNavigationHandler;
24179 }(Component_1.HandlerBase));
24180 exports.KeySpatialNavigationHandler = KeySpatialNavigationHandler;
24181 exports.default = KeySpatialNavigationHandler;
24183 },{"../../Component":226,"../../Edge":227,"rxjs/add/operator/switchMap":79,"rxjs/add/operator/withLatestFrom":83}],266:[function(require,module,exports){
24185 /// <reference path="../../../typings/index.d.ts" />
24186 var __extends = (this && this.__extends) || (function () {
24187 var extendStatics = Object.setPrototypeOf ||
24188 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24189 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24190 return function (d, b) {
24191 extendStatics(d, b);
24192 function __() { this.constructor = d; }
24193 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24196 Object.defineProperty(exports, "__esModule", { value: true });
24197 require("rxjs/add/operator/withLatestFrom");
24198 var Component_1 = require("../../Component");
24200 * The `KeyZoomHandler` allows the user zoom in and out using the
24201 * following key commands:
24208 * var keyboardComponent = viewer.getComponent("keyboard");
24210 * keyboardComponent.keyZoom.disable();
24211 * keyboardComponent.keyZoom.enable();
24213 * var isEnabled = keyboardComponent.keyZoom.isEnabled;
24216 var KeyZoomHandler = (function (_super) {
24217 __extends(KeyZoomHandler, _super);
24218 function KeyZoomHandler(component, container, navigator, viewportCoords) {
24219 var _this = _super.call(this, component, container, navigator) || this;
24220 _this._viewportCoords = viewportCoords;
24223 KeyZoomHandler.prototype._enable = function () {
24225 this._keyDownSubscription = this._container.keyboardService.keyDown$
24226 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
24227 .subscribe(function (_a) {
24228 var event = _a[0], render = _a[1], transform = _a[2];
24229 if (event.altKey || event.shiftKey || event.ctrlKey || event.metaKey) {
24233 switch (event.key) {
24243 event.preventDefault();
24244 var unprojected = _this._viewportCoords.unprojectFromViewport(0, 0, render.perspective);
24245 var reference = transform.projectBasic(unprojected.toArray());
24246 _this._navigator.stateService.zoomIn(delta, reference);
24249 KeyZoomHandler.prototype._disable = function () {
24250 this._keyDownSubscription.unsubscribe();
24252 KeyZoomHandler.prototype._getConfiguration = function (enable) {
24253 return { keyZoom: enable };
24255 return KeyZoomHandler;
24256 }(Component_1.HandlerBase));
24257 exports.KeyZoomHandler = KeyZoomHandler;
24258 exports.default = KeyZoomHandler;
24260 },{"../../Component":226,"rxjs/add/operator/withLatestFrom":83}],267:[function(require,module,exports){
24262 var __extends = (this && this.__extends) || (function () {
24263 var extendStatics = Object.setPrototypeOf ||
24264 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24265 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24266 return function (d, b) {
24267 extendStatics(d, b);
24268 function __() { this.constructor = d; }
24269 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24272 Object.defineProperty(exports, "__esModule", { value: true });
24273 var Component_1 = require("../../Component");
24274 var Geo_1 = require("../../Geo");
24276 * @class KeyboardComponent
24278 * @classdesc Component for keyboard event handling.
24280 * To retrive and use the keyboard component
24284 * var viewer = new Mapillary.Viewer(
24289 * var keyboardComponent = viewer.getComponent("keyboard");
24292 var KeyboardComponent = (function (_super) {
24293 __extends(KeyboardComponent, _super);
24294 function KeyboardComponent(name, container, navigator) {
24295 var _this = _super.call(this, name, container, navigator) || this;
24296 _this._keyZoomHandler = new Component_1.KeyZoomHandler(_this, container, navigator, new Geo_1.ViewportCoords());
24297 _this._keySequenceNavigationHandler = new Component_1.KeySequenceNavigationHandler(_this, container, navigator);
24298 _this._keySpatialNavigationHandler = new Component_1.KeySpatialNavigationHandler(_this, container, navigator, new Geo_1.Spatial());
24301 Object.defineProperty(KeyboardComponent.prototype, "keyZoom", {
24305 * @returns {KeyZoomHandler} The key zoom handler.
24308 return this._keyZoomHandler;
24313 Object.defineProperty(KeyboardComponent.prototype, "keySequenceNavigation", {
24315 * Get key sequence navigation.
24317 * @returns {KeySequenceNavigationHandler} The key sequence navigation handler.
24320 return this._keySequenceNavigationHandler;
24325 Object.defineProperty(KeyboardComponent.prototype, "keySpatialNavigation", {
24329 * @returns {KeySpatialNavigationHandler} The spatial handler.
24332 return this._keySpatialNavigationHandler;
24337 KeyboardComponent.prototype._activate = function () {
24339 this._configurationSubscription = this._configuration$
24340 .subscribe(function (configuration) {
24341 if (configuration.keyZoom) {
24342 _this._keyZoomHandler.enable();
24345 _this._keyZoomHandler.disable();
24347 if (configuration.keySequenceNavigation) {
24348 _this._keySequenceNavigationHandler.enable();
24351 _this._keySequenceNavigationHandler.disable();
24353 if (configuration.keySpatialNavigation) {
24354 _this._keySpatialNavigationHandler.enable();
24357 _this._keySpatialNavigationHandler.disable();
24361 KeyboardComponent.prototype._deactivate = function () {
24362 this._configurationSubscription.unsubscribe();
24364 KeyboardComponent.prototype._getDefaultConfiguration = function () {
24365 return { keySequenceNavigation: true, keySpatialNavigation: true, keyZoom: true };
24367 KeyboardComponent.componentName = "keyboard";
24368 return KeyboardComponent;
24369 }(Component_1.Component));
24370 exports.KeyboardComponent = KeyboardComponent;
24371 Component_1.ComponentService.register(KeyboardComponent);
24372 exports.default = KeyboardComponent;
24374 },{"../../Component":226,"../../Geo":229}],268:[function(require,module,exports){
24376 Object.defineProperty(exports, "__esModule", { value: true });
24377 var MarkerComponent_1 = require("./MarkerComponent");
24378 exports.MarkerComponent = MarkerComponent_1.MarkerComponent;
24379 var SimpleMarker_1 = require("./marker/SimpleMarker");
24380 exports.SimpleMarker = SimpleMarker_1.SimpleMarker;
24381 var CircleMarker_1 = require("./marker/CircleMarker");
24382 exports.CircleMarker = CircleMarker_1.CircleMarker;
24384 },{"./MarkerComponent":269,"./marker/CircleMarker":272,"./marker/SimpleMarker":274}],269:[function(require,module,exports){
24386 /// <reference path="../../../typings/index.d.ts" />
24387 var __extends = (this && this.__extends) || (function () {
24388 var extendStatics = Object.setPrototypeOf ||
24389 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24390 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24391 return function (d, b) {
24392 extendStatics(d, b);
24393 function __() { this.constructor = d; }
24394 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24397 Object.defineProperty(exports, "__esModule", { value: true });
24398 var THREE = require("three");
24399 var when = require("when");
24400 var Observable_1 = require("rxjs/Observable");
24401 require("rxjs/add/observable/combineLatest");
24402 require("rxjs/add/operator/distinctUntilChanged");
24403 require("rxjs/add/operator/map");
24404 var Component_1 = require("../../Component");
24405 var Render_1 = require("../../Render");
24406 var Graph_1 = require("../../Graph");
24407 var Geo_1 = require("../../Geo");
24409 * @class MarkerComponent
24411 * @classdesc Component for showing and editing 3D marker objects.
24413 * The `add` method is used for adding new markers or replacing
24414 * markers already in the set.
24416 * If a marker already in the set has the same
24417 * id as one of the markers added, the old marker will be removed and
24418 * the added marker will take its place.
24420 * It is not possible to update markers in the set by updating any properties
24421 * directly on the marker object. Markers need to be replaced by
24422 * re-adding them for updates to geographic position or configuration
24425 * Markers added to the marker component can be either interactive
24426 * or non-interactive. Different marker types define their behavior.
24427 * Markers with interaction support can be configured with options
24428 * to respond to dragging inside the viewer and be detected when
24429 * retrieving markers from pixel points with the `getMarkerIdAt` method.
24431 * To retrive and use the marker component
24435 * var viewer = new Mapillary.Viewer(
24439 * { component: { marker: true } });
24441 * var markerComponent = viewer.getComponent("marker");
24444 var MarkerComponent = (function (_super) {
24445 __extends(MarkerComponent, _super);
24446 function MarkerComponent(name, container, navigator) {
24447 var _this = _super.call(this, name, container, navigator) || this;
24448 _this._relativeGroundAltitude = -2;
24449 _this._geoCoords = new Geo_1.GeoCoords();
24450 _this._graphCalculator = new Graph_1.GraphCalculator();
24451 _this._markerScene = new Component_1.MarkerScene();
24452 _this._markerSet = new Component_1.MarkerSet();
24453 _this._viewportCoords = new Geo_1.ViewportCoords();
24457 * Add markers to the marker set or replace markers in the marker set.
24459 * @description If a marker already in the set has the same
24460 * id as one of the markers added, the old marker will be removed
24461 * the added marker will take its place.
24463 * Any marker inside the visible bounding bbox
24464 * will be initialized and placed in the viewer.
24466 * @param {Array<Marker>} markers - Markers to add.
24468 * @example ```markerComponent.add([marker1, marker2]);```
24470 MarkerComponent.prototype.add = function (markers) {
24471 this._markerSet.add(markers);
24474 * Returns the marker in the marker set with the specified id, or
24475 * undefined if the id matches no marker.
24477 * @param {string} markerId - Id of the marker.
24479 * @example ```var marker = markerComponent.get("markerId");```
24482 MarkerComponent.prototype.get = function (markerId) {
24483 return this._markerSet.get(markerId);
24486 * Returns an array of all markers.
24488 * @example ```var markers = markerComponent.getAll();```
24490 MarkerComponent.prototype.getAll = function () {
24491 return this._markerSet.getAll();
24494 * Returns the id of the interactive marker closest to the current camera
24495 * position at the specified point.
24497 * @description Notice that the pixelPoint argument requires x, y
24498 * coordinates from pixel space.
24500 * With this function, you can use the coordinates provided by mouse
24501 * events to get information out of the marker component.
24503 * If no interactive geometry of an interactive marker exist at the pixel
24504 * point, `null` will be returned.
24506 * @param {Array<number>} pixelPoint - Pixel coordinates on the viewer element.
24507 * @returns {string} Id of the interactive marker closest to the camera. If no
24508 * interactive marker exist at the pixel point, `null` will be returned.
24512 * markerComponent.getMarkerIdAt([100, 100])
24513 * .then((markerId) => { console.log(markerId); });
24516 MarkerComponent.prototype.getMarkerIdAt = function (pixelPoint) {
24518 return when.promise(function (resolve, reject) {
24519 _this._container.renderService.renderCamera$
24521 .map(function (render) {
24522 var viewport = _this._viewportCoords
24523 .canvasToViewport(pixelPoint[0], pixelPoint[1], _this._container.element);
24524 var id = _this._markerScene.intersectObjects(viewport, render.perspective);
24527 .subscribe(function (id) {
24529 }, function (error) {
24535 * Check if a marker exist in the marker set.
24537 * @param {string} markerId - Id of the marker.
24539 * @example ```var markerExists = markerComponent.has("markerId");```
24541 MarkerComponent.prototype.has = function (markerId) {
24542 return this._markerSet.has(markerId);
24545 * Remove markers with the specified ids from the marker set.
24547 * @param {Array<string>} markerIds - Ids for markers to remove.
24549 * @example ```markerComponent.remove(["id-1", "id-2"]);```
24551 MarkerComponent.prototype.remove = function (markerIds) {
24552 this._markerSet.remove(markerIds);
24555 * Remove all markers from the marker set.
24557 * @example ```markerComponent.removeAll();```
24559 MarkerComponent.prototype.removeAll = function () {
24560 this._markerSet.removeAll();
24562 MarkerComponent.prototype._activate = function () {
24564 var groundAltitude$ = this._navigator.stateService.currentState$
24565 .map(function (frame) {
24566 return frame.state.camera.position.z + _this._relativeGroundAltitude;
24568 .distinctUntilChanged(function (a1, a2) {
24569 return Math.abs(a1 - a2) < 0.01;
24573 var geoInitiated$ = Observable_1.Observable
24574 .combineLatest(groundAltitude$, this._navigator.stateService.reference$)
24576 .map(function () { })
24579 var clampedConfiguration$ = this._configuration$
24580 .map(function (configuration) {
24581 return { visibleBBoxSize: Math.max(1, Math.min(200, configuration.visibleBBoxSize)) };
24583 var currentlatLon$ = this._navigator.stateService.currentNode$
24584 .map(function (node) { return node.latLon; })
24587 var visibleBBox$ = Observable_1.Observable
24588 .combineLatest(clampedConfiguration$, currentlatLon$)
24589 .map(function (_a) {
24590 var configuration = _a[0], latLon = _a[1];
24591 return _this._graphCalculator
24592 .boundingBoxCorners(latLon, configuration.visibleBBoxSize / 2);
24596 var visibleMarkers$ = Observable_1.Observable
24597 .combineLatest(Observable_1.Observable
24598 .of(this._markerSet)
24599 .concat(this._markerSet.changed$), visibleBBox$)
24600 .map(function (_a) {
24601 var set = _a[0], bbox = _a[1];
24602 return set.search(bbox);
24604 this._setChangedSubscription = geoInitiated$
24605 .switchMap(function () {
24606 return visibleMarkers$
24607 .withLatestFrom(_this._navigator.stateService.reference$, groundAltitude$);
24609 .subscribe(function (_a) {
24610 var markers = _a[0], reference = _a[1], alt = _a[2];
24611 var geoCoords = _this._geoCoords;
24612 var markerScene = _this._markerScene;
24613 var sceneMarkers = markerScene.markers;
24614 var markersToRemove = Object.assign({}, sceneMarkers);
24615 for (var _i = 0, markers_1 = markers; _i < markers_1.length; _i++) {
24616 var marker = markers_1[_i];
24617 if (marker.id in sceneMarkers) {
24618 delete markersToRemove[marker.id];
24621 var point3d = geoCoords
24622 .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
24623 markerScene.add(marker, point3d);
24626 for (var id in markersToRemove) {
24627 if (!markersToRemove.hasOwnProperty(id)) {
24630 markerScene.remove(id);
24633 this._markersUpdatedSubscription = geoInitiated$
24634 .switchMap(function () {
24635 return _this._markerSet.updated$
24636 .withLatestFrom(visibleBBox$, _this._navigator.stateService.reference$, groundAltitude$);
24638 .subscribe(function (_a) {
24639 var markers = _a[0], _b = _a[1], sw = _b[0], ne = _b[1], reference = _a[2], alt = _a[3];
24640 var geoCoords = _this._geoCoords;
24641 var markerScene = _this._markerScene;
24642 for (var _i = 0, markers_2 = markers; _i < markers_2.length; _i++) {
24643 var marker = markers_2[_i];
24644 var exists = markerScene.has(marker.id);
24645 var visible = marker.latLon.lat > sw.lat &&
24646 marker.latLon.lat < ne.lat &&
24647 marker.latLon.lon > sw.lon &&
24648 marker.latLon.lon < ne.lon;
24650 var point3d = geoCoords
24651 .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
24652 markerScene.add(marker, point3d);
24654 else if (!visible && exists) {
24655 markerScene.remove(marker.id);
24659 this._referenceSubscription = this._navigator.stateService.reference$
24661 .withLatestFrom(groundAltitude$)
24662 .subscribe(function (_a) {
24663 var reference = _a[0], alt = _a[1];
24664 var geoCoords = _this._geoCoords;
24665 var markerScene = _this._markerScene;
24666 for (var _i = 0, _b = markerScene.getAll(); _i < _b.length; _i++) {
24667 var marker = _b[_i];
24668 var point3d = geoCoords
24669 .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
24670 markerScene.update(marker.id, point3d);
24673 this._adjustHeightSubscription = groundAltitude$
24675 .withLatestFrom(this._navigator.stateService.reference$, currentlatLon$)
24676 .subscribe(function (_a) {
24677 var alt = _a[0], reference = _a[1], latLon = _a[2];
24678 var geoCoords = _this._geoCoords;
24679 var markerScene = _this._markerScene;
24680 var position = geoCoords
24681 .geodeticToEnu(latLon.lat, latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
24682 for (var _i = 0, _b = markerScene.getAll(); _i < _b.length; _i++) {
24683 var marker = _b[_i];
24684 var point3d = geoCoords
24685 .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
24686 var distanceX = point3d[0] - position[0];
24687 var distanceY = point3d[1] - position[1];
24688 var groundDistance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
24689 if (groundDistance > 50) {
24692 markerScene.lerpAltitude(marker.id, alt, Math.min(1, Math.max(0, 1.2 - 1.2 * groundDistance / 50)));
24695 this._renderSubscription = this._navigator.stateService.currentState$
24696 .map(function (frame) {
24697 var scene = _this._markerScene;
24702 needsRender: scene.needsRender,
24703 render: scene.render.bind(scene),
24704 stage: Render_1.GLRenderStage.Foreground,
24708 .subscribe(this._container.glRenderer.render$);
24709 var hoveredMarkerId$ = Observable_1.Observable
24710 .combineLatest(this._container.renderService.renderCamera$, this._container.mouseService.mouseMove$)
24711 .map(function (_a) {
24712 var render = _a[0], event = _a[1];
24713 var element = _this._container.element;
24714 var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
24715 var viewport = _this._viewportCoords.canvasToViewport(canvasX, canvasY, element);
24716 var markerId = _this._markerScene.intersectObjects(viewport, render.perspective);
24721 var draggingStarted$ = this._container.mouseService
24722 .filtered$(this._name, this._container.mouseService.mouseDragStart$)
24723 .map(function (event) {
24726 var draggingStopped$ = this._container.mouseService
24727 .filtered$(this._name, this._container.mouseService.mouseDragEnd$)
24728 .map(function (event) {
24731 var filteredDragging$ = Observable_1.Observable
24732 .merge(draggingStarted$, draggingStopped$)
24734 this._dragEventSubscription = draggingStarted$
24735 .withLatestFrom(hoveredMarkerId$)
24736 .merge(Observable_1.Observable
24737 .combineLatest(draggingStopped$, Observable_1.Observable.of(null)))
24738 .startWith([false, null])
24740 .subscribe(function (_a) {
24741 var previous = _a[0], current = _a[1];
24742 var dragging = current[0];
24743 var eventType = dragging ? MarkerComponent.dragstart : MarkerComponent.dragend;
24744 var id = dragging ? current[1] : previous[1];
24745 var marker = _this._markerScene.get(id);
24746 var markerEvent = { marker: marker, target: _this, type: eventType };
24747 _this.fire(eventType, markerEvent);
24749 var mouseDown$ = Observable_1.Observable
24750 .merge(this._container.mouseService.mouseDown$
24751 .map(function (event) { return true; }), this._container.mouseService.documentMouseUp$
24752 .map(function (event) { return false; }))
24754 this._mouseClaimSubscription = Observable_1.Observable
24755 .combineLatest(this._container.mouseService.active$, hoveredMarkerId$.distinctUntilChanged(), mouseDown$, filteredDragging$)
24756 .map(function (_a) {
24757 var active = _a[0], markerId = _a[1], mouseDown = _a[2], filteredDragging = _a[3];
24758 return (!active && markerId != null && mouseDown) || filteredDragging;
24760 .distinctUntilChanged()
24761 .subscribe(function (claim) {
24763 _this._container.mouseService.claimMouse(_this._name, 1);
24766 _this._container.mouseService.unclaimMouse(_this._name);
24769 var offset$ = this._container.mouseService
24770 .filtered$(this._name, this._container.mouseService.mouseDragStart$)
24771 .withLatestFrom(hoveredMarkerId$, this._container.renderService.renderCamera$)
24772 .map(function (_a) {
24773 var e = _a[0], id = _a[1], r = _a[2];
24774 var marker = _this._markerScene.get(id);
24775 var element = _this._container.element;
24776 var _b = _this._viewportCoords.projectToCanvas(marker.geometry.position.toArray(), element, r.perspective), groundCanvasX = _b[0], groundCanvasY = _b[1];
24777 var _c = _this._viewportCoords.canvasPosition(e, element), canvasX = _c[0], canvasY = _c[1];
24778 var offset = [canvasX - groundCanvasX, canvasY - groundCanvasY];
24779 return [marker, offset, r];
24783 this._updateMarkerSubscription = this._container.mouseService
24784 .filtered$(this._name, this._container.mouseService.mouseDrag$)
24785 .withLatestFrom(offset$, this._navigator.stateService.reference$, clampedConfiguration$)
24786 .subscribe(function (_a) {
24787 var event = _a[0], _b = _a[1], marker = _b[0], offset = _b[1], render = _b[2], reference = _a[2], configuration = _a[3];
24788 if (!_this._markerScene.has(marker.id)) {
24791 var element = _this._container.element;
24792 var _c = _this._viewportCoords.canvasPosition(event, element), canvasX = _c[0], canvasY = _c[1];
24793 var groundX = canvasX - offset[0];
24794 var groundY = canvasY - offset[1];
24795 var _d = _this._viewportCoords
24796 .canvasToViewport(groundX, groundY, element), viewportX = _d[0], viewportY = _d[1];
24797 var direction = new THREE.Vector3(viewportX, viewportY, 1)
24798 .unproject(render.perspective)
24799 .sub(render.perspective.position)
24801 var distance = Math.min(_this._relativeGroundAltitude / direction.z, configuration.visibleBBoxSize / 2 - 0.1);
24802 if (distance < 0) {
24805 var intersection = direction
24807 .multiplyScalar(distance)
24808 .add(render.perspective.position);
24809 intersection.z = render.perspective.position.z + _this._relativeGroundAltitude;
24810 var _e = _this._geoCoords
24811 .enuToGeodetic(intersection.x, intersection.y, intersection.z, reference.lat, reference.lon, reference.alt), lat = _e[0], lon = _e[1];
24812 _this._markerScene.update(marker.id, intersection.toArray(), { lat: lat, lon: lon });
24813 _this._markerSet.update(marker);
24814 var markerEvent = { marker: marker, target: _this, type: MarkerComponent.changed };
24815 _this.fire(MarkerComponent.changed, markerEvent);
24818 MarkerComponent.prototype._deactivate = function () {
24819 this._adjustHeightSubscription.unsubscribe();
24820 this._dragEventSubscription.unsubscribe();
24821 this._markersUpdatedSubscription.unsubscribe();
24822 this._mouseClaimSubscription.unsubscribe();
24823 this._referenceSubscription.unsubscribe();
24824 this._renderSubscription.unsubscribe();
24825 this._setChangedSubscription.unsubscribe();
24826 this._updateMarkerSubscription.unsubscribe();
24827 this._markerScene.clear();
24829 MarkerComponent.prototype._getDefaultConfiguration = function () {
24830 return { visibleBBoxSize: 100 };
24832 MarkerComponent.componentName = "marker";
24834 * Fired when the position of a marker is changed.
24836 * @type {IMarkerEvent} markerEvent - Marker event data.
24839 * markerComponent.on("changed", function(e) {
24840 * console.log(e.marker.id, e.marker.latLon);
24844 MarkerComponent.changed = "changed";
24846 * Fired when a marker drag interaction starts.
24848 * @type {IMarkerEvent} markerEvent - Marker event data.
24851 * markerComponent.on("dragstart", function(e) {
24852 * console.log(e.marker.id, e.marker.latLon);
24856 MarkerComponent.dragstart = "dragstart";
24858 * Fired when a marker drag interaction ends.
24860 * @type {IMarkerEvent} markerEvent - Marker event data.
24863 * markerComponent.on("dragend", function(e) {
24864 * console.log(e.marker.id, e.marker.latLon);
24868 MarkerComponent.dragend = "dragend";
24869 return MarkerComponent;
24870 }(Component_1.Component));
24871 exports.MarkerComponent = MarkerComponent;
24872 Component_1.ComponentService.register(MarkerComponent);
24873 exports.default = MarkerComponent;
24875 },{"../../Component":226,"../../Geo":229,"../../Graph":230,"../../Render":232,"rxjs/Observable":29,"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/map":65,"three":176,"when":223}],270:[function(require,module,exports){
24877 /// <reference path="../../../typings/index.d.ts" />
24878 Object.defineProperty(exports, "__esModule", { value: true });
24879 var THREE = require("three");
24880 var MarkerScene = (function () {
24881 function MarkerScene(scene, raycaster) {
24882 this._needsRender = false;
24883 this._interactiveObjects = [];
24884 this._markers = {};
24885 this._objectMarkers = {};
24886 this._raycaster = !!raycaster ? raycaster : new THREE.Raycaster();
24887 this._scene = !!scene ? scene : new THREE.Scene();
24889 Object.defineProperty(MarkerScene.prototype, "markers", {
24891 return this._markers;
24896 Object.defineProperty(MarkerScene.prototype, "needsRender", {
24898 return this._needsRender;
24903 MarkerScene.prototype.add = function (marker, position) {
24904 if (marker.id in this._markers) {
24905 this._dispose(marker.id);
24907 marker.createGeometry(position);
24908 this._scene.add(marker.geometry);
24909 this._markers[marker.id] = marker;
24910 for (var _i = 0, _a = marker.getInteractiveObjects(); _i < _a.length; _i++) {
24911 var interactiveObject = _a[_i];
24912 this._interactiveObjects.push(interactiveObject);
24913 this._objectMarkers[interactiveObject.uuid] = marker.id;
24915 this._needsRender = true;
24917 MarkerScene.prototype.clear = function () {
24918 for (var id in this._markers) {
24919 if (!this._markers.hasOwnProperty) {
24924 this._needsRender = true;
24926 MarkerScene.prototype.get = function (id) {
24927 return this._markers[id];
24929 MarkerScene.prototype.getAll = function () {
24932 .keys(this._markers)
24933 .map(function (id) { return _this._markers[id]; });
24935 MarkerScene.prototype.has = function (id) {
24936 return id in this._markers;
24938 MarkerScene.prototype.intersectObjects = function (_a, camera) {
24939 var viewportX = _a[0], viewportY = _a[1];
24940 this._raycaster.setFromCamera(new THREE.Vector2(viewportX, viewportY), camera);
24941 var intersects = this._raycaster.intersectObjects(this._interactiveObjects);
24942 for (var _i = 0, intersects_1 = intersects; _i < intersects_1.length; _i++) {
24943 var intersect = intersects_1[_i];
24944 if (intersect.object.uuid in this._objectMarkers) {
24945 return this._objectMarkers[intersect.object.uuid];
24950 MarkerScene.prototype.lerpAltitude = function (id, alt, alpha) {
24951 if (!(id in this._markers)) {
24954 this._markers[id].lerpAltitude(alt, alpha);
24955 this._needsRender = true;
24957 MarkerScene.prototype.remove = function (id) {
24958 if (!(id in this._markers)) {
24962 this._needsRender = true;
24964 MarkerScene.prototype.render = function (perspectiveCamera, renderer) {
24965 renderer.render(this._scene, perspectiveCamera);
24966 this._needsRender = false;
24968 MarkerScene.prototype.update = function (id, position, latLon) {
24969 if (!(id in this._markers)) {
24972 var marker = this._markers[id];
24973 marker.updatePosition(position, latLon);
24974 this._needsRender = true;
24976 MarkerScene.prototype._dispose = function (id) {
24977 var marker = this._markers[id];
24978 this._scene.remove(marker.geometry);
24979 for (var _i = 0, _a = marker.getInteractiveObjects(); _i < _a.length; _i++) {
24980 var interactiveObject = _a[_i];
24981 var index = this._interactiveObjects.indexOf(interactiveObject);
24982 if (index !== -1) {
24983 this._interactiveObjects.splice(index, 1);
24986 console.warn("Object does not exist (" + interactiveObject.id + ") for " + id);
24988 delete this._objectMarkers[interactiveObject.uuid];
24990 marker.disposeGeometry();
24991 delete this._markers[id];
24993 return MarkerScene;
24995 exports.MarkerScene = MarkerScene;
24996 exports.default = MarkerScene;
24998 },{"three":176}],271:[function(require,module,exports){
25000 /// <reference path="../../../typings/index.d.ts" />
25001 Object.defineProperty(exports, "__esModule", { value: true });
25002 var rbush = require("rbush");
25003 var Subject_1 = require("rxjs/Subject");
25004 require("rxjs/add/operator/map");
25005 require("rxjs/add/operator/publishReplay");
25006 require("rxjs/add/operator/scan");
25007 var MarkerSet = (function () {
25008 function MarkerSet() {
25010 this._index = rbush(16, [".lon", ".lat", ".lon", ".lat"]);
25011 this._indexChanged$ = new Subject_1.Subject();
25012 this._updated$ = new Subject_1.Subject();
25014 Object.defineProperty(MarkerSet.prototype, "changed$", {
25016 return this._indexChanged$;
25021 Object.defineProperty(MarkerSet.prototype, "updated$", {
25023 return this._updated$;
25028 MarkerSet.prototype.add = function (markers) {
25030 var hash = this._hash;
25031 var index = this._index;
25032 for (var _i = 0, markers_1 = markers; _i < markers_1.length; _i++) {
25033 var marker = markers_1[_i];
25034 var id = marker.id;
25036 index.remove(hash[id]);
25037 updated.push(marker);
25040 lat: marker.latLon.lat,
25041 lon: marker.latLon.lon,
25045 index.insert(item);
25047 if (updated.length > 0) {
25048 this._updated$.next(updated);
25050 if (markers.length > updated.length) {
25051 this._indexChanged$.next(this);
25054 MarkerSet.prototype.has = function (id) {
25055 return id in this._hash;
25057 MarkerSet.prototype.get = function (id) {
25058 return this.has(id) ? this._hash[id].marker : undefined;
25060 MarkerSet.prototype.getAll = function () {
25063 .map(function (indexItem) {
25064 return indexItem.marker;
25067 MarkerSet.prototype.remove = function (ids) {
25068 var hash = this._hash;
25069 var index = this._index;
25070 var changed = false;
25071 for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
25072 var id = ids_1[_i];
25073 if (!(id in hash)) {
25076 var item = hash[id];
25077 index.remove(item);
25082 this._indexChanged$.next(this);
25085 MarkerSet.prototype.removeAll = function () {
25087 this._index.clear();
25088 this._indexChanged$.next(this);
25090 MarkerSet.prototype.search = function (_a) {
25091 var sw = _a[0], ne = _a[1];
25093 .search({ maxX: ne.lon, maxY: ne.lat, minX: sw.lon, minY: sw.lat })
25094 .map(function (indexItem) {
25095 return indexItem.marker;
25098 MarkerSet.prototype.update = function (marker) {
25099 var hash = this._hash;
25100 var index = this._index;
25101 var id = marker.id;
25102 if (!(id in hash)) {
25105 index.remove(hash[id]);
25107 lat: marker.latLon.lat,
25108 lon: marker.latLon.lon,
25112 index.insert(item);
25116 exports.MarkerSet = MarkerSet;
25117 exports.default = MarkerSet;
25119 },{"rbush":25,"rxjs/Subject":34,"rxjs/add/operator/map":65,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":73}],272:[function(require,module,exports){
25121 /// <reference path="../../../../typings/index.d.ts" />
25122 var __extends = (this && this.__extends) || (function () {
25123 var extendStatics = Object.setPrototypeOf ||
25124 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25125 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25126 return function (d, b) {
25127 extendStatics(d, b);
25128 function __() { this.constructor = d; }
25129 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25132 Object.defineProperty(exports, "__esModule", { value: true });
25133 var THREE = require("three");
25134 var Component_1 = require("../../../Component");
25136 * @class CircleMarker
25138 * @classdesc Non-interactive marker with a flat circle shape. The circle
25139 * marker can not be configured to be interactive.
25141 * Circle marker properties can not be updated after creation.
25143 * To create and add one `CircleMarker` with default configuration
25144 * and one with configuration use
25148 * var defaultMarker = new Mapillary.MarkerComponent.CircleMarker(
25150 * { lat: 0, lon: 0, });
25152 * var configuredMarker = new Mapillary.MarkerComponent.CircleMarker(
25154 * { lat: 0, lon: 0, },
25161 * markerComponent.add([defaultMarker, configuredMarker]);
25164 var CircleMarker = (function (_super) {
25165 __extends(CircleMarker, _super);
25166 function CircleMarker(id, latLon, options) {
25167 var _this = _super.call(this, id, latLon) || this;
25168 options = !!options ? options : {};
25169 _this._color = options.color != null ? options.color : 0xffffff;
25170 _this._opacity = options.opacity != null ? options.opacity : 0.4;
25171 _this._radius = options.radius != null ? options.radius : 1;
25174 CircleMarker.prototype._createGeometry = function (position) {
25175 var circle = new THREE.Mesh(new THREE.CircleGeometry(this._radius, 16), new THREE.MeshBasicMaterial({
25176 color: this._color,
25177 opacity: this._opacity,
25180 circle.up.fromArray([0, 0, 1]);
25181 circle.renderOrder = -1;
25182 var group = new THREE.Object3D();
25184 group.position.fromArray(position);
25185 this._geometry = group;
25187 CircleMarker.prototype._disposeGeometry = function () {
25188 for (var _i = 0, _a = this._geometry.children; _i < _a.length; _i++) {
25190 mesh.geometry.dispose();
25191 mesh.material.dispose();
25194 CircleMarker.prototype._getInteractiveObjects = function () {
25197 return CircleMarker;
25198 }(Component_1.Marker));
25199 exports.CircleMarker = CircleMarker;
25200 exports.default = CircleMarker;
25202 },{"../../../Component":226,"three":176}],273:[function(require,module,exports){
25204 /// <reference path="../../../../typings/index.d.ts" />
25205 Object.defineProperty(exports, "__esModule", { value: true });
25209 * @classdesc Represents an abstract marker class that should be extended
25210 * by marker implementations used in the marker component.
25212 var Marker = (function () {
25213 function Marker(id, latLon) {
25215 this._latLon = latLon;
25217 Object.defineProperty(Marker.prototype, "id", {
25220 * @returns {string} The id of the marker.
25228 Object.defineProperty(Marker.prototype, "geometry", {
25230 return this._geometry;
25235 Object.defineProperty(Marker.prototype, "latLon", {
25238 * @returns {ILatLon} The geographic coordinates of the marker.
25241 return this._latLon;
25246 Marker.prototype.createGeometry = function (position) {
25247 if (!!this._geometry) {
25250 this._createGeometry(position);
25251 // update matrix world if raycasting occurs before first render
25252 this._geometry.updateMatrixWorld(true);
25254 Marker.prototype.disposeGeometry = function () {
25255 if (!this._geometry) {
25258 this._disposeGeometry();
25259 this._geometry = undefined;
25261 Marker.prototype.getInteractiveObjects = function () {
25262 if (!this._geometry) {
25265 return this._getInteractiveObjects();
25267 Marker.prototype.lerpAltitude = function (alt, alpha) {
25268 if (!this._geometry) {
25271 this._geometry.position.z = (1 - alpha) * this._geometry.position.z + alpha * alt;
25273 Marker.prototype.updatePosition = function (position, latLon) {
25275 this._latLon.lat = latLon.lat;
25276 this._latLon.lon = latLon.lon;
25278 if (!this._geometry) {
25281 this._geometry.position.fromArray(position);
25282 this._geometry.updateMatrixWorld(true);
25286 exports.Marker = Marker;
25287 exports.default = Marker;
25289 },{}],274:[function(require,module,exports){
25291 /// <reference path="../../../../typings/index.d.ts" />
25292 var __extends = (this && this.__extends) || (function () {
25293 var extendStatics = Object.setPrototypeOf ||
25294 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25295 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25296 return function (d, b) {
25297 extendStatics(d, b);
25298 function __() { this.constructor = d; }
25299 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25302 Object.defineProperty(exports, "__esModule", { value: true });
25303 var THREE = require("three");
25304 var Component_1 = require("../../../Component");
25306 * @class SimpleMarker
25308 * @classdesc Interactive marker with ice cream shape. The sphere
25309 * inside the ice cream can be configured to be interactive.
25311 * Simple marker properties can not be updated after creation.
25313 * To create and add one `SimpleMarker` with default configuration
25314 * (non-interactive) and one interactive with configuration use
25318 * var defaultMarker = new Mapillary.MarkerComponent.SimpleMarker(
25320 * { lat: 0, lon: 0, });
25322 * var interactiveMarker = new Mapillary.MarkerComponent.SimpleMarker(
25324 * { lat: 0, lon: 0, },
25326 * ballColor: "#00f",
25327 * ballOpacity: 0.5,
25329 * interactive: true,
25334 * markerComponent.add([defaultMarker, interactiveMarker]);
25337 var SimpleMarker = (function (_super) {
25338 __extends(SimpleMarker, _super);
25339 function SimpleMarker(id, latLon, options) {
25340 var _this = _super.call(this, id, latLon) || this;
25341 options = !!options ? options : {};
25342 _this._ballColor = options.ballColor != null ? options.ballColor : 0xff0000;
25343 _this._ballOpacity = options.ballOpacity != null ? options.ballOpacity : 0.8;
25344 _this._circleToRayAngle = 2;
25345 _this._color = options.color != null ? options.color : 0xff0000;
25346 _this._interactive = !!options.interactive;
25347 _this._opacity = options.opacity != null ? options.opacity : 0.4;
25348 _this._radius = options.radius != null ? options.radius : 1;
25351 SimpleMarker.prototype._createGeometry = function (position) {
25352 var radius = this._radius;
25353 var cone = new THREE.Mesh(this._markerGeometry(radius, 8, 8), new THREE.MeshBasicMaterial({
25354 color: this._color,
25355 opacity: this._opacity,
25356 shading: THREE.SmoothShading,
25359 cone.renderOrder = 1;
25360 var ball = new THREE.Mesh(new THREE.SphereGeometry(radius / 2, 8, 8), new THREE.MeshBasicMaterial({
25361 color: this._ballColor,
25362 opacity: this._ballOpacity,
25363 shading: THREE.SmoothShading,
25366 ball.position.z = this._markerHeight(radius);
25367 var group = new THREE.Object3D();
25370 group.position.fromArray(position);
25371 this._geometry = group;
25373 SimpleMarker.prototype._disposeGeometry = function () {
25374 for (var _i = 0, _a = this._geometry.children; _i < _a.length; _i++) {
25376 mesh.geometry.dispose();
25377 mesh.material.dispose();
25380 SimpleMarker.prototype._getInteractiveObjects = function () {
25381 return this._interactive ? [this._geometry.children[0]] : [];
25383 SimpleMarker.prototype._markerHeight = function (radius) {
25384 var t = Math.tan(Math.PI - this._circleToRayAngle);
25385 return radius * Math.sqrt(1 + t * t);
25387 SimpleMarker.prototype._markerGeometry = function (radius, widthSegments, heightSegments) {
25388 var geometry = new THREE.Geometry();
25389 widthSegments = Math.max(3, Math.floor(widthSegments) || 8);
25390 heightSegments = Math.max(2, Math.floor(heightSegments) || 6);
25391 var height = this._markerHeight(radius);
25393 for (var y = 0; y <= heightSegments; ++y) {
25394 var verticesRow = [];
25395 for (var x = 0; x <= widthSegments; ++x) {
25396 var u = x / widthSegments * Math.PI * 2;
25397 var v = y / heightSegments * Math.PI;
25399 if (v < this._circleToRayAngle) {
25403 var t = Math.tan(v - this._circleToRayAngle);
25404 r = radius * Math.sqrt(1 + t * t);
25406 var vertex = new THREE.Vector3();
25407 vertex.x = r * Math.cos(u) * Math.sin(v);
25408 vertex.y = r * Math.sin(u) * Math.sin(v);
25409 vertex.z = r * Math.cos(v) + height;
25410 geometry.vertices.push(vertex);
25411 verticesRow.push(geometry.vertices.length - 1);
25413 vertices.push(verticesRow);
25415 for (var y = 0; y < heightSegments; ++y) {
25416 for (var x = 0; x < widthSegments; ++x) {
25417 var v1 = vertices[y][x + 1];
25418 var v2 = vertices[y][x];
25419 var v3 = vertices[y + 1][x];
25420 var v4 = vertices[y + 1][x + 1];
25421 var n1 = geometry.vertices[v1].clone().normalize();
25422 var n2 = geometry.vertices[v2].clone().normalize();
25423 var n3 = geometry.vertices[v3].clone().normalize();
25424 var n4 = geometry.vertices[v4].clone().normalize();
25425 geometry.faces.push(new THREE.Face3(v1, v2, v4, [n1, n2, n4]));
25426 geometry.faces.push(new THREE.Face3(v2, v3, v4, [n2.clone(), n3, n4.clone()]));
25429 geometry.computeFaceNormals();
25430 geometry.boundingSphere = new THREE.Sphere(new THREE.Vector3(), radius + height);
25433 return SimpleMarker;
25434 }(Component_1.Marker));
25435 exports.SimpleMarker = SimpleMarker;
25436 exports.default = SimpleMarker;
25438 },{"../../../Component":226,"three":176}],275:[function(require,module,exports){
25440 /// <reference path="../../../typings/index.d.ts" />
25441 var __extends = (this && this.__extends) || (function () {
25442 var extendStatics = Object.setPrototypeOf ||
25443 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25444 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25445 return function (d, b) {
25446 extendStatics(d, b);
25447 function __() { this.constructor = d; }
25448 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25451 Object.defineProperty(exports, "__esModule", { value: true });
25452 var Observable_1 = require("rxjs/Observable");
25453 var Component_1 = require("../../Component");
25455 * The `BounceHandler` ensures that the viewer bounces back to the image
25456 * when drag panning outside of the image edge.
25458 var BounceHandler = (function (_super) {
25459 __extends(BounceHandler, _super);
25460 function BounceHandler(component, container, navigator, viewportCoords, spatial) {
25461 var _this = _super.call(this, component, container, navigator) || this;
25462 _this._spatial = spatial;
25463 _this._viewportCoords = viewportCoords;
25464 _this._basicDistanceThreshold = 1e-3;
25465 _this._basicRotationThreshold = 5e-2;
25466 _this._bounceCoeff = 1e-1;
25469 BounceHandler.prototype._enable = function () {
25471 var inTransition$ = this._navigator.stateService.currentState$
25472 .map(function (frame) {
25473 return frame.state.alpha < 1;
25475 this._bounceSubscription = Observable_1.Observable
25476 .combineLatest(inTransition$, this._navigator.stateService.inTranslation$, this._container.mouseService.active$, this._container.touchService.active$)
25477 .map(function (noForce) {
25478 return noForce[0] || noForce[1] || noForce[2] || noForce[3];
25480 .distinctUntilChanged()
25481 .switchMap(function (noForce) {
25483 Observable_1.Observable.empty() :
25484 Observable_1.Observable.combineLatest(_this._container.renderService.renderCamera$, _this._navigator.stateService.currentTransform$.first());
25486 .subscribe(function (args) {
25487 var renderCamera = args[0];
25488 var perspectiveCamera = renderCamera.perspective;
25489 var transform = args[1];
25490 if (!transform.hasValidScale && renderCamera.camera.focal < 0.1) {
25493 if (renderCamera.perspective.aspect === 0 || renderCamera.perspective.aspect === Number.POSITIVE_INFINITY) {
25496 var distanceThreshold = _this._basicDistanceThreshold / Math.pow(2, renderCamera.zoom);
25497 var basicCenter = _this._viewportCoords.viewportToBasic(0, 0, transform, perspectiveCamera);
25498 if (Math.abs(basicCenter[0] - 0.5) < distanceThreshold && Math.abs(basicCenter[1] - 0.5) < distanceThreshold) {
25501 var basicDistances = _this._viewportCoords.getBasicDistances(transform, perspectiveCamera);
25504 if (basicDistances[0] < distanceThreshold && basicDistances[1] < distanceThreshold &&
25505 basicDistances[2] < distanceThreshold && basicDistances[3] < distanceThreshold) {
25508 if (Math.abs(basicDistances[0] - basicDistances[2]) < distanceThreshold &&
25509 Math.abs(basicDistances[1] - basicDistances[3]) < distanceThreshold) {
25512 var coeff = _this._bounceCoeff;
25513 if (basicDistances[1] > 0 && basicDistances[3] === 0) {
25514 basicX = -coeff * basicDistances[1];
25516 else if (basicDistances[1] === 0 && basicDistances[3] > 0) {
25517 basicX = coeff * basicDistances[3];
25519 else if (basicDistances[1] > 0 && basicDistances[3] > 0) {
25520 basicX = coeff * (basicDistances[3] - basicDistances[1]) / 2;
25522 if (basicDistances[0] > 0 && basicDistances[2] === 0) {
25523 basicY = coeff * basicDistances[0];
25525 else if (basicDistances[0] === 0 && basicDistances[2] > 0) {
25526 basicY = -coeff * basicDistances[2];
25528 else if (basicDistances[0] > 0 && basicDistances[2] > 0) {
25529 basicY = coeff * (basicDistances[0] - basicDistances[2]) / 2;
25531 var rotationThreshold = _this._basicRotationThreshold;
25532 basicX = _this._spatial.clamp(basicX, -rotationThreshold, rotationThreshold);
25533 basicY = _this._spatial.clamp(basicY, -rotationThreshold, rotationThreshold);
25534 _this._navigator.stateService.rotateBasicUnbounded([basicX, basicY]);
25537 BounceHandler.prototype._disable = function () {
25538 this._bounceSubscription.unsubscribe();
25540 BounceHandler.prototype._getConfiguration = function (enable) {
25543 return BounceHandler;
25544 }(Component_1.HandlerBase));
25545 exports.BounceHandler = BounceHandler;
25546 exports.default = BounceHandler;
25548 },{"../../Component":226,"rxjs/Observable":29}],276:[function(require,module,exports){
25550 var __extends = (this && this.__extends) || (function () {
25551 var extendStatics = Object.setPrototypeOf ||
25552 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25553 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25554 return function (d, b) {
25555 extendStatics(d, b);
25556 function __() { this.constructor = d; }
25557 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25560 Object.defineProperty(exports, "__esModule", { value: true });
25561 var Observable_1 = require("rxjs/Observable");
25562 var Component_1 = require("../../Component");
25564 * The `DoubleClickZoomHandler` allows the user to zoom the viewer photo at a point by double clicking.
25568 * var mouseComponent = viewer.getComponent("mouse");
25570 * mouseComponent.doubleClickZoom.disable();
25571 * mouseComponent.doubleClickZoom.enable();
25573 * var isEnabled = mouseComponent.doubleClickZoom.isEnabled;
25576 var DoubleClickZoomHandler = (function (_super) {
25577 __extends(DoubleClickZoomHandler, _super);
25578 function DoubleClickZoomHandler(component, container, navigator, viewportCoords) {
25579 var _this = _super.call(this, component, container, navigator) || this;
25580 _this._viewportCoords = viewportCoords;
25583 DoubleClickZoomHandler.prototype._enable = function () {
25585 this._zoomSubscription = Observable_1.Observable
25586 .merge(this._container.mouseService
25587 .filtered$(this._component.name, this._container.mouseService.dblClick$), this._container.touchService.doubleTap$
25588 .map(function (e) {
25589 var touch = e.touches[0];
25590 return { clientX: touch.clientX, clientY: touch.clientY, shiftKey: e.shiftKey };
25592 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
25593 .subscribe(function (_a) {
25594 var event = _a[0], render = _a[1], transform = _a[2];
25595 var element = _this._container.element;
25596 var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
25597 var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
25598 var reference = transform.projectBasic(unprojected.toArray());
25599 var delta = !!event.shiftKey ? -1 : 1;
25600 _this._navigator.stateService.zoomIn(delta, reference);
25603 DoubleClickZoomHandler.prototype._disable = function () {
25604 this._zoomSubscription.unsubscribe();
25606 DoubleClickZoomHandler.prototype._getConfiguration = function (enable) {
25607 return { doubleClickZoom: enable };
25609 return DoubleClickZoomHandler;
25610 }(Component_1.HandlerBase));
25611 exports.DoubleClickZoomHandler = DoubleClickZoomHandler;
25612 exports.default = DoubleClickZoomHandler;
25614 },{"../../Component":226,"rxjs/Observable":29}],277:[function(require,module,exports){
25616 /// <reference path="../../../typings/index.d.ts" />
25617 var __extends = (this && this.__extends) || (function () {
25618 var extendStatics = Object.setPrototypeOf ||
25619 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25620 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25621 return function (d, b) {
25622 extendStatics(d, b);
25623 function __() { this.constructor = d; }
25624 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25627 Object.defineProperty(exports, "__esModule", { value: true });
25628 var THREE = require("three");
25629 var Observable_1 = require("rxjs/Observable");
25630 var Component_1 = require("../../Component");
25632 * The `DragPanHandler` allows the user to pan the viewer photo by clicking and dragging the cursor.
25636 * var mouseComponent = viewer.getComponent("mouse");
25638 * mouseComponent.dragPan.disable();
25639 * mouseComponent.dragPan.enable();
25641 * var isEnabled = mouseComponent.dragPan.isEnabled;
25644 var DragPanHandler = (function (_super) {
25645 __extends(DragPanHandler, _super);
25646 function DragPanHandler(component, container, navigator, viewportCoords, spatial) {
25647 var _this = _super.call(this, component, container, navigator) || this;
25648 _this._spatial = spatial;
25649 _this._viewportCoords = viewportCoords;
25650 _this._basicRotationThreshold = 5e-2;
25651 _this._forceCoeff = 2e-1;
25654 DragPanHandler.prototype._enable = function () {
25656 var draggingStarted$ = this._container.mouseService
25657 .filtered$(this._component.name, this._container.mouseService.mouseDragStart$)
25658 .map(function (event) {
25661 var draggingStopped$ = this._container.mouseService
25662 .filtered$(this._component.name, this._container.mouseService.mouseDragEnd$)
25663 .map(function (event) {
25666 this._activeMouseSubscription = Observable_1.Observable
25667 .merge(draggingStarted$, draggingStopped$)
25668 .subscribe(this._container.mouseService.activate$);
25669 this._preventDefaultSubscription = Observable_1.Observable
25670 .merge(draggingStarted$, draggingStopped$)
25671 .switchMap(function (dragging) {
25673 _this._container.mouseService.documentMouseMove$ :
25674 Observable_1.Observable.empty();
25676 .merge(this._container.touchService.touchMove$)
25677 .subscribe(function (event) {
25678 event.preventDefault(); // prevent selection of content outside the viewer
25680 var touchMovingStarted$ = this._container.touchService.singleTouchDragStart$
25681 .map(function (event) {
25684 var touchMovingStopped$ = this._container.touchService.singleTouchDragEnd$
25685 .map(function (event) {
25688 this._activeTouchSubscription = Observable_1.Observable
25689 .merge(touchMovingStarted$, touchMovingStopped$)
25690 .subscribe(this._container.touchService.activate$);
25691 this._rotateBasicSubscription = this._navigator.stateService.currentState$
25692 .map(function (frame) {
25693 return frame.state.currentNode.fullPano || frame.state.nodesAhead < 1;
25695 .distinctUntilChanged()
25696 .switchMap(function (enable) {
25698 return Observable_1.Observable.empty();
25700 var mouseDrag$ = Observable_1.Observable
25701 .merge(_this._container.mouseService.filtered$(_this._component.name, _this._container.mouseService.mouseDragStart$), _this._container.mouseService.filtered$(_this._component.name, _this._container.mouseService.mouseDrag$), _this._container.mouseService.filtered$(_this._component.name, _this._container.mouseService.mouseDragEnd$)
25702 .map(function (e) { return null; }))
25704 .filter(function (pair) {
25705 return pair[0] != null && pair[1] != null;
25707 var singleTouchDrag$ = Observable_1.Observable
25708 .merge(_this._container.touchService.singleTouchDragStart$, _this._container.touchService.singleTouchDrag$, _this._container.touchService.singleTouchDragEnd$.map(function (t) { return null; }))
25709 .map(function (event) {
25710 return event != null && event.touches.length > 0 ?
25711 event.touches[0] : null;
25714 .filter(function (pair) {
25715 return pair[0] != null && pair[1] != null;
25717 return Observable_1.Observable
25718 .merge(mouseDrag$, singleTouchDrag$);
25720 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, this._navigator.stateService.currentCamera$)
25721 .map(function (_a) {
25722 var events = _a[0], render = _a[1], transform = _a[2], c = _a[3];
25723 var camera = c.clone();
25724 var previousEvent = events[0];
25725 var event = events[1];
25726 var movementX = event.clientX - previousEvent.clientX;
25727 var movementY = event.clientY - previousEvent.clientY;
25728 var element = _this._container.element;
25729 var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
25730 var currentDirection = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective)
25731 .sub(render.perspective.position);
25732 var directionX = _this._viewportCoords.unprojectFromCanvas(canvasX - movementX, canvasY, element, render.perspective)
25733 .sub(render.perspective.position);
25734 var directionY = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY - movementY, element, render.perspective)
25735 .sub(render.perspective.position);
25736 var deltaPhi = (movementX > 0 ? 1 : -1) * directionX.angleTo(currentDirection);
25737 var deltaTheta = (movementY > 0 ? -1 : 1) * directionY.angleTo(currentDirection);
25738 var upQuaternion = new THREE.Quaternion().setFromUnitVectors(camera.up, new THREE.Vector3(0, 0, 1));
25739 var upQuaternionInverse = upQuaternion.clone().inverse();
25740 var offset = new THREE.Vector3();
25741 offset.copy(camera.lookat).sub(camera.position);
25742 offset.applyQuaternion(upQuaternion);
25743 var length = offset.length();
25744 var phi = Math.atan2(offset.y, offset.x);
25746 var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z);
25747 theta += deltaTheta;
25748 theta = Math.max(0.01, Math.min(Math.PI - 0.01, theta));
25749 offset.x = Math.sin(theta) * Math.cos(phi);
25750 offset.y = Math.sin(theta) * Math.sin(phi);
25751 offset.z = Math.cos(theta);
25752 offset.applyQuaternion(upQuaternionInverse);
25753 var lookat = new THREE.Vector3().copy(camera.position).add(offset.multiplyScalar(length));
25754 var basic = transform.projectBasic(lookat.toArray());
25755 var original = transform.projectBasic(camera.lookat.toArray());
25756 var x = basic[0] - original[0];
25757 var y = basic[1] - original[1];
25758 if (Math.abs(x) > 1) {
25761 else if (x > 0.5) {
25764 else if (x < -0.5) {
25767 var rotationThreshold = _this._basicRotationThreshold;
25768 x = _this._spatial.clamp(x, -rotationThreshold, rotationThreshold);
25769 y = _this._spatial.clamp(y, -rotationThreshold, rotationThreshold);
25770 if (transform.fullPano) {
25773 var pixelDistances = _this._viewportCoords.getPixelDistances(_this._container.element, transform, render.perspective);
25774 var coeff = _this._forceCoeff;
25775 if (pixelDistances[0] > 0 && y < 0 && basic[1] < 0.5) {
25776 y /= Math.max(1, coeff * pixelDistances[0]);
25778 if (pixelDistances[1] > 0 && x > 0 && basic[0] > 0.5) {
25779 x /= Math.max(1, coeff * pixelDistances[1]);
25781 if (pixelDistances[2] > 0 && y > 0 && basic[1] > 0.5) {
25782 y /= Math.max(1, coeff * pixelDistances[2]);
25784 if (pixelDistances[3] > 0 && x < 0 && basic[0] < 0.5) {
25785 x /= Math.max(1, coeff * pixelDistances[3]);
25789 .subscribe(function (basicRotation) {
25790 _this._navigator.stateService.rotateBasic(basicRotation);
25793 DragPanHandler.prototype._disable = function () {
25794 this._activeMouseSubscription.unsubscribe();
25795 this._activeTouchSubscription.unsubscribe();
25796 this._preventDefaultSubscription.unsubscribe();
25797 this._rotateBasicSubscription.unsubscribe();
25798 this._activeMouseSubscription = null;
25799 this._activeTouchSubscription = null;
25800 this._preventDefaultSubscription = null;
25801 this._rotateBasicSubscription = null;
25803 DragPanHandler.prototype._getConfiguration = function (enable) {
25804 return { dragPan: enable };
25806 return DragPanHandler;
25807 }(Component_1.HandlerBase));
25808 exports.DragPanHandler = DragPanHandler;
25809 exports.default = DragPanHandler;
25811 },{"../../Component":226,"rxjs/Observable":29,"three":176}],278:[function(require,module,exports){
25813 var __extends = (this && this.__extends) || (function () {
25814 var extendStatics = Object.setPrototypeOf ||
25815 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25816 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25817 return function (d, b) {
25818 extendStatics(d, b);
25819 function __() { this.constructor = d; }
25820 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25823 Object.defineProperty(exports, "__esModule", { value: true });
25824 require("rxjs/add/observable/merge");
25825 require("rxjs/add/operator/filter");
25826 require("rxjs/add/operator/map");
25827 require("rxjs/add/operator/withLatestFrom");
25828 var Component_1 = require("../../Component");
25829 var Geo_1 = require("../../Geo");
25831 * @class MouseComponent
25833 * @classdesc Component handling mouse and touch events for camera movement.
25835 var MouseComponent = (function (_super) {
25836 __extends(MouseComponent, _super);
25837 function MouseComponent(name, container, navigator) {
25838 var _this = _super.call(this, name, container, navigator) || this;
25839 var spatial = new Geo_1.Spatial();
25840 var viewportCoords = new Geo_1.ViewportCoords();
25841 _this._spatial = spatial;
25842 _this._viewportCoords = viewportCoords;
25843 _this._bounceHandler = new Component_1.BounceHandler(_this, container, navigator, viewportCoords, spatial);
25844 _this._doubleClickZoomHandler = new Component_1.DoubleClickZoomHandler(_this, container, navigator, viewportCoords);
25845 _this._dragPanHandler = new Component_1.DragPanHandler(_this, container, navigator, viewportCoords, spatial);
25846 _this._scrollZoomHandler = new Component_1.ScrollZoomHandler(_this, container, navigator, viewportCoords);
25847 _this._touchZoomHandler = new Component_1.TouchZoomHandler(_this, container, navigator, viewportCoords);
25850 Object.defineProperty(MouseComponent.prototype, "doubleClickZoom", {
25852 * Get double click zoom.
25854 * @returns {DoubleClickZoomHandler} The double click zoom handler.
25857 return this._doubleClickZoomHandler;
25862 Object.defineProperty(MouseComponent.prototype, "dragPan", {
25866 * @returns {DragPanHandler} The drag pan handler.
25869 return this._dragPanHandler;
25874 Object.defineProperty(MouseComponent.prototype, "scrollZoom", {
25878 * @returns {ScrollZoomHandler} The scroll zoom handler.
25881 return this._scrollZoomHandler;
25886 Object.defineProperty(MouseComponent.prototype, "touchZoom", {
25890 * @returns {TouchZoomHandler} The touch zoom handler.
25893 return this._touchZoomHandler;
25898 MouseComponent.prototype._activate = function () {
25900 this._bounceHandler.enable();
25901 this._configurationSubscription = this._configuration$
25902 .subscribe(function (configuration) {
25903 if (configuration.doubleClickZoom) {
25904 _this._doubleClickZoomHandler.enable();
25907 _this._doubleClickZoomHandler.disable();
25909 if (configuration.dragPan) {
25910 _this._dragPanHandler.enable();
25913 _this._dragPanHandler.disable();
25915 if (configuration.scrollZoom) {
25916 _this._scrollZoomHandler.enable();
25919 _this._scrollZoomHandler.disable();
25921 if (configuration.touchZoom) {
25922 _this._touchZoomHandler.enable();
25925 _this._touchZoomHandler.disable();
25928 this._container.mouseService.claimMouse(this._name, 0);
25930 MouseComponent.prototype._deactivate = function () {
25931 this._container.mouseService.unclaimMouse(this._name);
25932 this._configurationSubscription.unsubscribe();
25933 this._bounceHandler.disable();
25934 this._doubleClickZoomHandler.disable();
25935 this._dragPanHandler.disable();
25936 this._scrollZoomHandler.disable();
25937 this._touchZoomHandler.disable();
25939 MouseComponent.prototype._getDefaultConfiguration = function () {
25940 return { doubleClickZoom: true, dragPan: true, scrollZoom: true, touchZoom: true };
25943 MouseComponent.componentName = "mouse";
25944 return MouseComponent;
25945 }(Component_1.Component));
25946 exports.MouseComponent = MouseComponent;
25947 Component_1.ComponentService.register(MouseComponent);
25948 exports.default = MouseComponent;
25950 },{"../../Component":226,"../../Geo":229,"rxjs/add/observable/merge":44,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/withLatestFrom":83}],279:[function(require,module,exports){
25952 var __extends = (this && this.__extends) || (function () {
25953 var extendStatics = Object.setPrototypeOf ||
25954 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25955 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25956 return function (d, b) {
25957 extendStatics(d, b);
25958 function __() { this.constructor = d; }
25959 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25962 Object.defineProperty(exports, "__esModule", { value: true });
25963 var Component_1 = require("../../Component");
25965 * The `ScrollZoomHandler` allows the user to zoom the viewer photo by scrolling.
25969 * var mouseComponent = viewer.getComponent("mouse");
25971 * mouseComponent.scrollZoom.disable();
25972 * mouseComponent.scrollZoom.enable();
25974 * var isEnabled = mouseComponent.scrollZoom.isEnabled;
25977 var ScrollZoomHandler = (function (_super) {
25978 __extends(ScrollZoomHandler, _super);
25979 function ScrollZoomHandler(component, container, navigator, viewportCoords) {
25980 var _this = _super.call(this, component, container, navigator) || this;
25981 _this._viewportCoords = viewportCoords;
25984 ScrollZoomHandler.prototype._enable = function () {
25986 this._preventDefaultSubscription = this._container.mouseService.mouseWheel$
25987 .subscribe(function (event) {
25988 event.preventDefault();
25990 this._zoomSubscription = this._container.mouseService
25991 .filtered$(this._component.name, this._container.mouseService.mouseWheel$)
25992 .withLatestFrom(this._navigator.stateService.currentState$, function (w, f) {
25995 .filter(function (args) {
25996 var state = args[1].state;
25997 return state.currentNode.fullPano || state.nodesAhead < 1;
25999 .map(function (args) {
26002 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, function (w, r, t) {
26005 .subscribe(function (args) {
26006 var event = args[0];
26007 var render = args[1];
26008 var transform = args[2];
26009 var element = _this._container.element;
26010 var _a = _this._viewportCoords.canvasPosition(event, element), canvasX = _a[0], canvasY = _a[1];
26011 var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
26012 var reference = transform.projectBasic(unprojected.toArray());
26013 var deltaY = event.deltaY;
26014 if (event.deltaMode === 1) {
26015 deltaY = 40 * deltaY;
26017 else if (event.deltaMode === 2) {
26018 deltaY = 800 * deltaY;
26020 var canvasSize = _this._viewportCoords.containerToCanvas(element);
26021 var zoom = -3 * deltaY / canvasSize[1];
26022 _this._navigator.stateService.zoomIn(zoom, reference);
26025 ScrollZoomHandler.prototype._disable = function () {
26026 this._preventDefaultSubscription.unsubscribe();
26027 this._zoomSubscription.unsubscribe();
26028 this._preventDefaultSubscription = null;
26029 this._zoomSubscription = null;
26031 ScrollZoomHandler.prototype._getConfiguration = function (enable) {
26032 return { scrollZoom: enable };
26034 return ScrollZoomHandler;
26035 }(Component_1.HandlerBase));
26036 exports.ScrollZoomHandler = ScrollZoomHandler;
26037 exports.default = ScrollZoomHandler;
26039 },{"../../Component":226}],280:[function(require,module,exports){
26041 /// <reference path="../../../typings/index.d.ts" />
26042 var __extends = (this && this.__extends) || (function () {
26043 var extendStatics = Object.setPrototypeOf ||
26044 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26045 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
26046 return function (d, b) {
26047 extendStatics(d, b);
26048 function __() { this.constructor = d; }
26049 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26052 Object.defineProperty(exports, "__esModule", { value: true });
26053 var Observable_1 = require("rxjs/Observable");
26054 var Component_1 = require("../../Component");
26056 * The `TouchZoomHandler` allows the user to zoom the viewer photo by pinching on a touchscreen.
26060 * var mouseComponent = viewer.getComponent("mouse");
26062 * mouseComponent.touchZoom.disable();
26063 * mouseComponent.touchZoom.enable();
26065 * var isEnabled = mouseComponent.touchZoom.isEnabled;
26068 var TouchZoomHandler = (function (_super) {
26069 __extends(TouchZoomHandler, _super);
26070 function TouchZoomHandler(component, container, navigator, viewportCoords) {
26071 var _this = _super.call(this, component, container, navigator) || this;
26072 _this._viewportCoords = viewportCoords;
26075 TouchZoomHandler.prototype._enable = function () {
26077 this._preventDefaultSubscription = this._container.touchService.pinch$
26078 .subscribe(function (pinch) {
26079 pinch.originalEvent.preventDefault();
26081 var pinchStarted$ = this._container.touchService.pinchStart$
26082 .map(function (event) {
26085 var pinchStopped$ = this._container.touchService.pinchEnd$
26086 .map(function (event) {
26089 this._activeSubscription = Observable_1.Observable
26090 .merge(pinchStarted$, pinchStopped$)
26091 .subscribe(this._container.touchService.activate$);
26092 this._zoomSubscription = this._container.touchService.pinch$
26093 .withLatestFrom(this._navigator.stateService.currentState$)
26094 .filter(function (args) {
26095 var state = args[1].state;
26096 return state.currentNode.fullPano || state.nodesAhead < 1;
26098 .map(function (args) {
26101 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
26102 .subscribe(function (_a) {
26103 var pinch = _a[0], render = _a[1], transform = _a[2];
26104 var element = _this._container.element;
26105 var _b = _this._viewportCoords.canvasPosition(pinch, element), canvasX = _b[0], canvasY = _b[1];
26106 var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
26107 var reference = transform.projectBasic(unprojected.toArray());
26108 var _c = _this._viewportCoords.containerToCanvas(element), canvasWidth = _c[0], canvasHeight = _c[1];
26109 var zoom = 3 * pinch.distanceChange / Math.min(canvasWidth, canvasHeight);
26110 _this._navigator.stateService.zoomIn(zoom, reference);
26113 TouchZoomHandler.prototype._disable = function () {
26114 this._activeSubscription.unsubscribe();
26115 this._preventDefaultSubscription.unsubscribe();
26116 this._zoomSubscription.unsubscribe();
26117 this._preventDefaultSubscription = null;
26118 this._zoomSubscription = null;
26120 TouchZoomHandler.prototype._getConfiguration = function (enable) {
26121 return { touchZoom: enable };
26123 return TouchZoomHandler;
26124 }(Component_1.HandlerBase));
26125 exports.TouchZoomHandler = TouchZoomHandler;
26126 exports.default = TouchZoomHandler;
26128 },{"../../Component":226,"rxjs/Observable":29}],281:[function(require,module,exports){
26130 Object.defineProperty(exports, "__esModule", { value: true });
26131 var Popup_1 = require("./popup/Popup");
26132 exports.Popup = Popup_1.Popup;
26133 var PopupComponent_1 = require("./PopupComponent");
26134 exports.PopupComponent = PopupComponent_1.PopupComponent;
26136 },{"./PopupComponent":282,"./popup/Popup":283}],282:[function(require,module,exports){
26138 var __extends = (this && this.__extends) || (function () {
26139 var extendStatics = Object.setPrototypeOf ||
26140 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26141 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
26142 return function (d, b) {
26143 extendStatics(d, b);
26144 function __() { this.constructor = d; }
26145 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26148 Object.defineProperty(exports, "__esModule", { value: true });
26149 var Observable_1 = require("rxjs/Observable");
26150 var Subject_1 = require("rxjs/Subject");
26151 var Component_1 = require("../../Component");
26153 * @class PopupComponent
26155 * @classdesc Component for showing HTML popup objects.
26157 * The `add` method is used for adding new popups. Popups are removed by reference.
26159 * It is not possible to update popups in the set by updating any properties
26160 * directly on the popup object. Popups need to be replaced by
26161 * removing them and creating new ones with relevant changed properties and
26162 * adding those instead.
26164 * Popups are only relevant to a single image because they are based on
26165 * 2D basic image coordinates. Popups related to a certain image should
26166 * be removed when the viewer is moved to another node.
26168 * To retrive and use the popup component
26172 * var viewer = new Mapillary.Viewer(
26176 * { component: { popup: true } });
26178 * var popupComponent = viewer.getComponent("popup");
26181 var PopupComponent = (function (_super) {
26182 __extends(PopupComponent, _super);
26183 function PopupComponent(name, container, navigator) {
26184 var _this = _super.call(this, name, container, navigator) || this;
26185 _this._popups = [];
26186 _this._added$ = new Subject_1.Subject();
26187 _this._popups$ = new Subject_1.Subject();
26191 * Add popups to the popups set.
26193 * @description Adding a new popup never replaces an old one
26194 * because they are stored by reference. Adding an already
26195 * existing popup has no effect.
26197 * @param {Array<Popup>} popups - Popups to add.
26199 * @example ```popupComponent.add([popup1, popup2]);```
26201 PopupComponent.prototype.add = function (popups) {
26202 for (var _i = 0, popups_1 = popups; _i < popups_1.length; _i++) {
26203 var popup = popups_1[_i];
26204 if (this._popups.indexOf(popup) !== -1) {
26207 this._popups.push(popup);
26208 if (this._activated) {
26209 popup.setParentContainer(this._popupContainer);
26212 this._added$.next(popups);
26213 this._popups$.next(this._popups);
26216 * Returns an array of all popups.
26218 * @example ```var popups = popupComponent.getAll();```
26220 PopupComponent.prototype.getAll = function () {
26221 return this._popups.slice();
26224 * Remove popups based on reference from the popup set.
26226 * @param {Array<Popup>} popups - Popups to remove.
26228 * @example ```popupComponent.remove([popup1, popup2]);```
26230 PopupComponent.prototype.remove = function (popups) {
26231 for (var _i = 0, popups_2 = popups; _i < popups_2.length; _i++) {
26232 var popup = popups_2[_i];
26233 this._remove(popup);
26235 this._popups$.next(this._popups);
26238 * Remove all popups from the popup set.
26240 * @example ```popupComponent.removeAll();```
26242 PopupComponent.prototype.removeAll = function () {
26243 for (var _i = 0, _a = this._popups.slice(); _i < _a.length; _i++) {
26244 var popup = _a[_i];
26245 this._remove(popup);
26247 this._popups$.next(this._popups);
26249 PopupComponent.prototype._activate = function () {
26251 this._popupContainer = document.createElement("div");
26252 this._popupContainer.className = "mapillary-js-popup-container";
26253 this._container.element.appendChild(this._popupContainer);
26254 for (var _i = 0, _a = this._popups; _i < _a.length; _i++) {
26255 var popup = _a[_i];
26256 popup.setParentContainer(this._popupContainer);
26258 this._updateAllSubscription = Observable_1.Observable
26259 .combineLatest(this._container.renderService.renderCamera$, this._container.renderService.size$, this._navigator.stateService.currentTransform$)
26260 .subscribe(function (_a) {
26261 var renderCamera = _a[0], size = _a[1], transform = _a[2];
26262 for (var _i = 0, _b = _this._popups; _i < _b.length; _i++) {
26263 var popup = _b[_i];
26264 popup.update(renderCamera, size, transform);
26267 var changed$ = this._popups$
26268 .startWith(this._popups)
26269 .switchMap(function (popups) {
26270 return Observable_1.Observable
26272 .mergeMap(function (popup) {
26273 return popup.changed$;
26276 .map(function (popup) {
26279 this._updateAddedChangedSubscription = this._added$
26281 .withLatestFrom(this._container.renderService.renderCamera$, this._container.renderService.size$, this._navigator.stateService.currentTransform$)
26282 .subscribe(function (_a) {
26283 var popups = _a[0], renderCamera = _a[1], size = _a[2], transform = _a[3];
26284 for (var _i = 0, popups_3 = popups; _i < popups_3.length; _i++) {
26285 var popup = popups_3[_i];
26286 popup.update(renderCamera, size, transform);
26290 PopupComponent.prototype._deactivate = function () {
26291 this._updateAllSubscription.unsubscribe();
26292 this._updateAddedChangedSubscription.unsubscribe();
26293 for (var _i = 0, _a = this._popups; _i < _a.length; _i++) {
26294 var popup = _a[_i];
26297 this._container.element.removeChild(this._popupContainer);
26298 delete this._popupContainer;
26300 PopupComponent.prototype._getDefaultConfiguration = function () {
26303 PopupComponent.prototype._remove = function (popup) {
26304 var index = this._popups.indexOf(popup);
26305 if (index === -1) {
26308 var removed = this._popups.splice(index, 1)[0];
26309 if (this._activated) {
26313 PopupComponent.componentName = "popup";
26314 return PopupComponent;
26315 }(Component_1.Component));
26316 exports.PopupComponent = PopupComponent;
26317 Component_1.ComponentService.register(PopupComponent);
26318 exports.default = PopupComponent;
26320 },{"../../Component":226,"rxjs/Observable":29,"rxjs/Subject":34}],283:[function(require,module,exports){
26322 /// <reference path="../../../../typings/index.d.ts" />
26323 Object.defineProperty(exports, "__esModule", { value: true });
26324 var Subject_1 = require("rxjs/Subject");
26325 var Geo_1 = require("../../../Geo");
26326 var Viewer_1 = require("../../../Viewer");
26330 * @classdesc Popup instance for rendering custom HTML content
26331 * on top of images. Popups are based on 2D basic image coordinates
26332 * (see the {@link Viewer} class documentation for more information about coordinate
26333 * systems) and a certain popup is therefore only relevant to a single image.
26334 * Popups related to a certain image should be removed when moving
26335 * to another image.
26337 * A popup must have both its content and its point or rect set to be
26338 * rendered. Popup options can not be updated after creation but the
26339 * basic point or rect as well as its content can be changed by calling
26340 * the appropriate methods.
26342 * To create and add one `Popup` with default configuration
26343 * (tooltip visuals and automatic float) and one with specific options
26348 * var defaultSpan = document.createElement('span');
26349 * defaultSpan.innerHTML = 'hello default';
26351 * var defaultPopup = new Mapillary.PopupComponent.Popup();
26352 * defaultPopup.setDOMContent(defaultSpan);
26353 * defaultPopup.setBasicPoint([0.3, 0.3]);
26355 * var cleanSpan = document.createElement('span');
26356 * cleanSpan.innerHTML = 'hello clean';
26358 * var cleanPopup = new Mapillary.PopupComponent.Popup({
26360 * float: Mapillary.Alignment.Top,
26365 * cleanPopup.setDOMContent(cleanSpan);
26366 * cleanPopup.setBasicPoint([0.6, 0.6]);
26368 * popupComponent.add([defaultPopup, cleanPopup]);
26371 * @description Implementation of API methods and API documentation inspired
26372 * by/used from https://github.com/mapbox/mapbox-gl-js/blob/v0.38.0/src/ui/popup.js
26374 var Popup = (function () {
26375 function Popup(options, viewportCoords) {
26376 this._options = {};
26378 this._options.clean = options.clean;
26379 this._options.float = options.float;
26380 this._options.offset = options.offset;
26381 this._options.opacity = options.opacity;
26382 this._options.position = options.position;
26384 this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
26385 this._notifyChanged$ = new Subject_1.Subject();
26387 Object.defineProperty(Popup.prototype, "changed$", {
26391 * @description Internal observable used by the component to
26392 * render the popup when its position or content has changed.
26395 return this._notifyChanged$;
26403 * @description Internal method used by the component to
26404 * remove all references to the popup.
26406 Popup.prototype.remove = function () {
26407 if (this._content && this._content.parentNode) {
26408 this._content.parentNode.removeChild(this._content);
26410 if (this._container) {
26411 this._container.parentNode.removeChild(this._container);
26412 delete this._container;
26414 if (this._parentContainer) {
26415 delete this._parentContainer;
26419 * Sets a 2D basic image coordinates point to the popup's anchor, and
26420 * moves the popup to it.
26422 * @description Overwrites any previously set point or rect.
26424 * @param {Array<number>} basicPoint - Point in 2D basic image coordinates.
26428 * var popup = new Mapillary.PopupComponent.Popup();
26429 * popup.setText('hello image');
26430 * popup.setBasicPoint([0.3, 0.3]);
26432 * popupComponent.add([popup]);
26435 Popup.prototype.setBasicPoint = function (basicPoint) {
26436 this._point = basicPoint.slice();
26438 this._notifyChanged$.next(this);
26441 * Sets a 2D basic image coordinates rect to the popup's anchor, and
26442 * moves the popup to it.
26444 * @description Overwrites any previously set point or rect.
26446 * @param {Array<number>} basicRect - Rect in 2D basic image
26447 * coordinates ([topLeftX, topLeftY, bottomRightX, bottomRightY]) .
26451 * var popup = new Mapillary.PopupComponent.Popup();
26452 * popup.setText('hello image');
26453 * popup.setBasicRect([0.3, 0.3, 0.5, 0.6]);
26455 * popupComponent.add([popup]);
26458 Popup.prototype.setBasicRect = function (basicRect) {
26459 this._rect = basicRect.slice();
26460 this._point = null;
26461 this._notifyChanged$.next(this);
26464 * Sets the popup's content to the element provided as a DOM node.
26466 * @param {Node} htmlNode - A DOM node to be used as content for the popup.
26470 * var div = document.createElement('div');
26471 * div.innerHTML = 'hello image';
26473 * var popup = new Mapillary.PopupComponent.Popup();
26474 * popup.setDOMContent(div);
26475 * popup.setBasicPoint([0.3, 0.3]);
26477 * popupComponent.add([popup]);
26480 Popup.prototype.setDOMContent = function (htmlNode) {
26481 if (this._content && this._content.parentNode) {
26482 this._content.parentNode.removeChild(this._content);
26484 var className = "mapillaryjs-popup-content" + (this._options.clean === true ? "-clean" : "");
26485 this._content = this._createElement("div", className, this._container);
26486 this._content.appendChild(htmlNode);
26487 this._notifyChanged$.next(this);
26490 * Sets the popup's content to the HTML provided as a string.
26492 * @description This method does not perform HTML filtering or sanitization,
26493 * and must be used only with trusted content. Consider Popup#setText if the
26494 * content is an untrusted text string.
26496 * @param {string} html - A string representing HTML content for the popup.
26500 * var popup = new Mapillary.PopupComponent.Popup();
26501 * popup.setHTML('<div>hello image</div>');
26502 * popup.setBasicPoint([0.3, 0.3]);
26504 * popupComponent.add([popup]);
26507 Popup.prototype.setHTML = function (html) {
26508 var frag = document.createDocumentFragment();
26509 var temp = document.createElement("body");
26511 temp.innerHTML = html;
26513 child = temp.firstChild;
26517 frag.appendChild(child);
26519 this.setDOMContent(frag);
26522 * Sets the popup's content to a string of text.
26524 * @description This function creates a Text node in the DOM, so it cannot insert raw HTML.
26525 * Use this method for security against XSS if the popup content is user-provided.
26527 * @param {string} text - Textual content for the popup.
26531 * var popup = new Mapillary.PopupComponent.Popup();
26532 * popup.setText('hello image');
26533 * popup.setBasicPoint([0.3, 0.3]);
26535 * popupComponent.add([popup]);
26538 Popup.prototype.setText = function (text) {
26539 this.setDOMContent(document.createTextNode(text));
26544 * @description Internal method for attaching the popup to
26545 * its parent container so that it is rendered in the DOM tree.
26547 Popup.prototype.setParentContainer = function (parentContainer) {
26548 this._parentContainer = parentContainer;
26553 * @description Internal method for updating the rendered
26554 * position of the popup called by the popup component.
26556 Popup.prototype.update = function (renderCamera, size, transform) {
26557 if (!this._parentContainer || !this._content) {
26560 if (!this._point && !this._rect) {
26563 if (!this._container) {
26564 this._container = this._createElement("div", "mapillaryjs-popup", this._parentContainer);
26565 var showTip = this._options.clean !== true &&
26566 this._options.float !== Viewer_1.Alignment.Center;
26568 this._tip = this._createElement("div", "mapillaryjs-popup-tip", this._container);
26569 this._createElement("div", "mapillaryjs-popup-tip-inner", this._tip);
26571 this._container.appendChild(this._content);
26572 this._parentContainer.appendChild(this._container);
26573 if (this._options.opacity != null) {
26574 this._container.style.opacity = this._options.opacity.toString();
26577 var pointPixel = null;
26578 var position = this._alignmentToPopupAligment(this._options.position);
26579 var float = this._alignmentToPopupAligment(this._options.float);
26580 if (this._point != null) {
26582 this._viewportCoords.basicToCanvasSafe(this._point[0], this._point[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective);
26585 _a = this._rectToPixel(this._rect, position, renderCamera, size, transform), pointPixel = _a[0], position = _a[1];
26590 if (pointPixel == null) {
26591 this._container.style.visibility = "hidden";
26594 this._container.style.visibility = "visible";
26596 var width = this._container.offsetWidth;
26597 var height = this._container.offsetHeight;
26598 var floats = this._pixelToFloats(pointPixel, size, width, height);
26599 float = floats.length === 0 ? "bottom" : floats.join("-");
26601 if (!!this._options.offset) {
26602 var offset = this._options.offset;
26603 var sign = offset >= 0 ? 1 : -1;
26604 var cornerOffset = sign * Math.round(Math.sqrt(0.5 * Math.pow(offset, 2)));
26605 var floatOffset = {
26606 "bottom": [0, offset],
26607 "bottom-left": [-cornerOffset, cornerOffset],
26608 "bottom-right": [cornerOffset, cornerOffset],
26610 "left": [-offset, 0],
26611 "right": [offset, 0],
26612 "top": [0, -offset],
26613 "top-left": [-cornerOffset, -cornerOffset],
26614 "top-right": [cornerOffset, -cornerOffset],
26616 pointPixel = [pointPixel[0] + floatOffset[float][0], pointPixel[1] + floatOffset[float][1]];
26618 pointPixel = [Math.round(pointPixel[0]), Math.round(pointPixel[1])];
26619 var floatTranslate = {
26620 "bottom": "translate(-50%,0)",
26621 "bottom-left": "translate(-100%,0)",
26622 "bottom-right": "translate(0,0)",
26623 "center": "translate(-50%,-50%)",
26624 "left": "translate(-100%,-50%)",
26625 "right": "translate(0,-50%)",
26626 "top": "translate(-50%,-100%)",
26627 "top-left": "translate(-100%,-100%)",
26628 "top-right": "translate(0,-100%)",
26630 var classList = this._container.classList;
26631 for (var key in floatTranslate) {
26632 if (!floatTranslate.hasOwnProperty(key)) {
26635 classList.remove("mapillaryjs-popup-float-" + key);
26637 classList.add("mapillaryjs-popup-float-" + float);
26638 this._container.style.transform = floatTranslate[float] + " translate(" + pointPixel[0] + "px," + pointPixel[1] + "px)";
26641 Popup.prototype._createElement = function (tagName, className, container) {
26642 var element = document.createElement(tagName);
26644 element.className = className;
26647 container.appendChild(element);
26651 Popup.prototype._rectToPixel = function (rect, position, renderCamera, size, transform) {
26653 var width = this._container.offsetWidth;
26654 var height = this._container.offsetHeight;
26655 var floatOffsets = {
26656 "bottom": [0, height / 2],
26657 "bottom-left": [-width / 2, height / 2],
26658 "bottom-right": [width / 2, height / 2],
26659 "left": [-width / 2, 0],
26660 "right": [width / 2, 0],
26661 "top": [0, -height / 2],
26662 "top-left": [-width / 2, -height / 2],
26663 "top-right": [width / 2, -height / 2],
26665 var automaticPositions = ["bottom", "top", "left", "right"];
26666 var largestVisibleArea = [0, null, null];
26667 for (var _i = 0, automaticPositions_1 = automaticPositions; _i < automaticPositions_1.length; _i++) {
26668 var automaticPosition = automaticPositions_1[_i];
26669 var pointBasic_1 = this._pointFromRectPosition(rect, automaticPosition);
26670 var pointPixel = this._viewportCoords.basicToCanvasSafe(pointBasic_1[0], pointBasic_1[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective);
26671 if (pointPixel == null) {
26674 var floatOffset = floatOffsets[automaticPosition];
26675 var offsetedPosition = [pointPixel[0] + floatOffset[0], pointPixel[1] + floatOffset[1]];
26676 var floats = this._pixelToFloats(offsetedPosition, size, width, height / 2);
26677 if (floats.length === 0 &&
26678 pointPixel[0] > 0 &&
26679 pointPixel[0] < size.width &&
26680 pointPixel[1] > 0 &&
26681 pointPixel[1] < size.height) {
26682 return [pointPixel, automaticPosition];
26684 var minX = Math.max(offsetedPosition[0] - width / 2, 0);
26685 var maxX = Math.min(offsetedPosition[0] + width / 2, size.width);
26686 var minY = Math.max(offsetedPosition[1] - height / 2, 0);
26687 var maxY = Math.min(offsetedPosition[1] + height / 2, size.height);
26688 var visibleX = Math.max(0, maxX - minX);
26689 var visibleY = Math.max(0, maxY - minY);
26690 var visibleArea = visibleX * visibleY;
26691 if (visibleArea > largestVisibleArea[0]) {
26692 largestVisibleArea[0] = visibleArea;
26693 largestVisibleArea[1] = pointPixel;
26694 largestVisibleArea[2] = automaticPosition;
26697 if (largestVisibleArea[0] > 0) {
26698 return [largestVisibleArea[1], largestVisibleArea[2]];
26701 var pointBasic = this._pointFromRectPosition(rect, position);
26702 var pointCanvas = this._viewportCoords.basicToCanvasSafe(pointBasic[0], pointBasic[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective);
26703 return [pointCanvas, position != null ? position : "bottom"];
26705 Popup.prototype._alignmentToPopupAligment = function (float) {
26707 case Viewer_1.Alignment.Bottom:
26709 case Viewer_1.Alignment.BottomLeft:
26710 return "bottom-left";
26711 case Viewer_1.Alignment.BottomRight:
26712 return "bottom-right";
26713 case Viewer_1.Alignment.Center:
26715 case Viewer_1.Alignment.Left:
26717 case Viewer_1.Alignment.Right:
26719 case Viewer_1.Alignment.Top:
26721 case Viewer_1.Alignment.TopLeft:
26723 case Viewer_1.Alignment.TopRight:
26724 return "top-right";
26729 Popup.prototype._pixelToFloats = function (pointPixel, size, width, height) {
26731 if (pointPixel[1] < height) {
26732 floats.push("bottom");
26734 else if (pointPixel[1] > size.height - height) {
26735 floats.push("top");
26737 if (pointPixel[0] < width / 2) {
26738 floats.push("right");
26740 else if (pointPixel[0] > size.width - width / 2) {
26741 floats.push("left");
26745 Popup.prototype._pointFromRectPosition = function (rect, position) {
26746 switch (position) {
26748 return [(rect[0] + rect[2]) / 2, rect[3]];
26749 case "bottom-left":
26750 return [rect[0], rect[3]];
26751 case "bottom-right":
26752 return [rect[2], rect[3]];
26754 return [(rect[0] + rect[2]) / 2, (rect[1] + rect[3]) / 2];
26756 return [rect[0], (rect[1] + rect[3]) / 2];
26758 return [rect[2], (rect[1] + rect[3]) / 2];
26760 return [(rect[0] + rect[2]) / 2, rect[1]];
26762 return [rect[0], rect[1]];
26764 return [rect[2], rect[1]];
26766 return [(rect[0] + rect[2]) / 2, rect[3]];
26771 exports.Popup = Popup;
26772 exports.default = Popup;
26774 },{"../../../Geo":229,"../../../Viewer":237,"rxjs/Subject":34}],284:[function(require,module,exports){
26776 /// <reference path="../../../typings/index.d.ts" />
26777 var __extends = (this && this.__extends) || (function () {
26778 var extendStatics = Object.setPrototypeOf ||
26779 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26780 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
26781 return function (d, b) {
26782 extendStatics(d, b);
26783 function __() { this.constructor = d; }
26784 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26787 Object.defineProperty(exports, "__esModule", { value: true });
26788 var Observable_1 = require("rxjs/Observable");
26789 var Subject_1 = require("rxjs/Subject");
26790 require("rxjs/add/observable/combineLatest");
26791 require("rxjs/add/observable/of");
26792 require("rxjs/add/operator/bufferCount");
26793 require("rxjs/add/operator/concat");
26794 require("rxjs/add/operator/distinctUntilChanged");
26795 require("rxjs/add/operator/filter");
26796 require("rxjs/add/operator/finally");
26797 require("rxjs/add/operator/first");
26798 require("rxjs/add/operator/map");
26799 require("rxjs/add/operator/publishReplay");
26800 require("rxjs/add/operator/scan");
26801 require("rxjs/add/operator/share");
26802 require("rxjs/add/operator/switchMap");
26803 require("rxjs/add/operator/takeUntil");
26804 require("rxjs/add/operator/withLatestFrom");
26805 var Component_1 = require("../../Component");
26806 var Edge_1 = require("../../Edge");
26808 * @class SequenceComponent
26809 * @classdesc Component showing navigation arrows for sequence directions
26810 * as well as playing button. Exposes an API to start and stop play.
26812 var SequenceComponent = (function (_super) {
26813 __extends(SequenceComponent, _super);
26814 function SequenceComponent(name, container, navigator) {
26815 var _this = _super.call(this, name, container, navigator) || this;
26816 _this._nodesAhead = 5;
26817 _this._configurationOperation$ = new Subject_1.Subject();
26818 _this._sequenceDOMRenderer = new Component_1.SequenceDOMRenderer(container.element);
26819 _this._sequenceDOMInteraction = new Component_1.SequenceDOMInteraction();
26820 _this._containerWidth$ = new Subject_1.Subject();
26821 _this._hoveredKeySubject$ = new Subject_1.Subject();
26822 _this._hoveredKey$ = _this._hoveredKeySubject$.share();
26823 _this._edgeStatus$ = _this._navigator.stateService.currentNode$
26824 .switchMap(function (node) {
26825 return node.sequenceEdges$;
26831 Object.defineProperty(SequenceComponent.prototype, "hoveredKey$", {
26833 * Get hovered key observable.
26835 * @description An observable emitting the key of the node for the direction
26836 * arrow that is being hovered. When the mouse leaves a direction arrow null
26839 * @returns {Observable<string>}
26842 return this._hoveredKey$;
26850 * @fires PlayerComponent#playingchanged
26852 SequenceComponent.prototype.play = function () {
26853 this.configure({ playing: true });
26858 * @fires PlayerComponent#playingchanged
26860 SequenceComponent.prototype.stop = function () {
26861 this.configure({ playing: false });
26864 * Set the direction to follow when playing.
26866 * @param {EdgeDirection} direction - The direction that will be followed when playing.
26868 SequenceComponent.prototype.setDirection = function (direction) {
26869 this.configure({ direction: direction });
26872 * Set highlight key.
26874 * @description The arrow pointing towards the node corresponding to the
26875 * highlight key will be highlighted.
26877 * @param {string} highlightKey Key of node to be highlighted if existing.
26879 SequenceComponent.prototype.setHighlightKey = function (highlightKey) {
26880 this.configure({ highlightKey: highlightKey });
26883 * Set max width of container element.
26885 * @description Set max width of the container element holding
26886 * the sequence navigation elements. If the min width is larger than the
26887 * max width the min width value will be used.
26889 * The container element is automatically resized when the resize
26890 * method on the Viewer class is called.
26892 * @param {number} minWidth
26894 SequenceComponent.prototype.setMaxWidth = function (maxWidth) {
26895 this.configure({ maxWidth: maxWidth });
26898 * Set min width of container element.
26900 * @description Set min width of the container element holding
26901 * the sequence navigation elements. If the min width is larger than the
26902 * max width the min width value will be used.
26904 * The container element is automatically resized when the resize
26905 * method on the Viewer class is called.
26907 * @param {number} minWidth
26909 SequenceComponent.prototype.setMinWidth = function (minWidth) {
26910 this.configure({ minWidth: minWidth });
26913 * Set the value indicating whether the sequence UI elements should be visible.
26915 * @param {boolean} visible
26917 SequenceComponent.prototype.setVisible = function (visible) {
26918 this.configure({ visible: visible });
26921 SequenceComponent.prototype.resize = function () {
26923 this._configuration$
26925 .map(function (configuration) {
26926 return _this._sequenceDOMRenderer.getContainerWidth(_this._container.element, configuration);
26928 .subscribe(function (containerWidth) {
26929 _this._containerWidth$.next(containerWidth);
26932 SequenceComponent.prototype._activate = function () {
26934 this._renderSubscription = Observable_1.Observable
26935 .combineLatest(this._edgeStatus$, this._configuration$, this._containerWidth$)
26936 .map(function (ec) {
26937 var edgeStatus = ec[0];
26938 var configuration = ec[1];
26939 var containerWidth = ec[2];
26940 var vNode = _this._sequenceDOMRenderer
26941 .render(edgeStatus, configuration, containerWidth, _this, _this._sequenceDOMInteraction, _this._navigator);
26942 return { name: _this._name, vnode: vNode };
26944 .subscribe(this._container.domRenderer.render$);
26945 this._containerWidthSubscription = this._configuration$
26946 .distinctUntilChanged(function (value1, value2) {
26947 return value1[0] === value2[0] && value1[1] === value2[1];
26948 }, function (configuration) {
26949 return [configuration.minWidth, configuration.maxWidth];
26951 .map(function (configuration) {
26952 return _this._sequenceDOMRenderer.getContainerWidth(_this._container.element, configuration);
26954 .subscribe(this._containerWidth$);
26955 this._configurationSubscription = this._configurationOperation$
26956 .scan(function (configuration, operation) {
26957 return operation(configuration);
26958 }, { playing: false })
26959 .finally(function () {
26960 if (_this._playingSubscription != null) {
26961 _this._navigator.stateService.cutNodes();
26965 .subscribe(function () { });
26966 this._configuration$
26967 .map(function (newConfiguration) {
26968 return function (configuration) {
26969 if (newConfiguration.playing !== configuration.playing) {
26970 _this._navigator.stateService.cutNodes();
26971 if (newConfiguration.playing) {
26978 configuration.playing = newConfiguration.playing;
26979 return configuration;
26982 .subscribe(this._configurationOperation$);
26983 this._stopSubscription = this._configuration$
26984 .switchMap(function (configuration) {
26985 var edgeStatus$ = configuration.playing ?
26986 _this._edgeStatus$ :
26987 Observable_1.Observable.empty();
26988 var edgeDirection$ = Observable_1.Observable
26989 .of(configuration.direction);
26990 return Observable_1.Observable
26991 .combineLatest(edgeStatus$, edgeDirection$);
26993 .map(function (ne) {
26994 var edgeStatus = ne[0];
26995 var direction = ne[1];
26996 if (!edgeStatus.cached) {
26999 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
27001 if (edge.data.direction === direction) {
27007 .filter(function (hasEdge) {
27010 .map(function (hasEdge) {
27011 return { playing: false };
27013 .subscribe(this._configurationSubject$);
27014 this._hoveredKeySubscription = this._sequenceDOMInteraction.mouseEnterDirection$
27015 .switchMap(function (direction) {
27016 return _this._edgeStatus$
27017 .map(function (edgeStatus) {
27018 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
27020 if (edge.data.direction === direction) {
27026 .takeUntil(_this._sequenceDOMInteraction.mouseLeaveDirection$)
27027 .concat(Observable_1.Observable.of(null));
27029 .distinctUntilChanged()
27030 .subscribe(this._hoveredKeySubject$);
27032 SequenceComponent.prototype._deactivate = function () {
27033 this._stopSubscription.unsubscribe();
27034 this._renderSubscription.unsubscribe();
27035 this._configurationSubscription.unsubscribe();
27036 this._containerWidthSubscription.unsubscribe();
27037 this._hoveredKeySubscription.unsubscribe();
27040 SequenceComponent.prototype._getDefaultConfiguration = function () {
27042 direction: Edge_1.EdgeDirection.Next,
27049 SequenceComponent.prototype._play = function () {
27051 this._playingSubscription = this._navigator.stateService.currentState$
27052 .filter(function (frame) {
27053 return frame.state.nodesAhead < _this._nodesAhead;
27055 .map(function (frame) {
27056 return frame.state.lastNode;
27058 .distinctUntilChanged(undefined, function (lastNode) {
27059 return lastNode.key;
27061 .withLatestFrom(this._configuration$, function (lastNode, configuration) {
27062 return [lastNode, configuration.direction];
27064 .switchMap(function (nd) {
27065 return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(nd[1]) > -1 ?
27066 nd[0].sequenceEdges$ :
27067 nd[0].spatialEdges$)
27068 .filter(function (status) {
27069 return status.cached;
27071 .zip(Observable_1.Observable.of(nd[1]), function (status, direction) {
27072 return [status, direction];
27075 .map(function (ed) {
27076 var direction = ed[1];
27077 for (var _i = 0, _a = ed[0].edges; _i < _a.length; _i++) {
27079 if (edge.data.direction === direction) {
27085 .filter(function (key) {
27086 return key != null;
27088 .switchMap(function (key) {
27089 return _this._navigator.graphService.cacheNode$(key);
27091 .subscribe(function (node) {
27092 _this._navigator.stateService.appendNodes([node]);
27093 }, function (error) {
27094 console.error(error);
27097 this._clearSubscription = this._navigator.stateService.currentNode$
27099 .subscribe(function (nodes) {
27100 _this._navigator.stateService.clearPriorNodes();
27102 this.fire(SequenceComponent.playingchanged, true);
27104 SequenceComponent.prototype._stop = function () {
27105 this._playingSubscription.unsubscribe();
27106 this._playingSubscription = null;
27107 this._clearSubscription.unsubscribe();
27108 this._clearSubscription = null;
27109 this.fire(SequenceComponent.playingchanged, false);
27112 SequenceComponent.componentName = "sequence";
27114 * Event fired when playing starts or stops.
27116 * @event PlayerComponent#playingchanged
27117 * @type {boolean} Indicates whether the player is playing.
27119 SequenceComponent.playingchanged = "playingchanged";
27120 return SequenceComponent;
27121 }(Component_1.Component));
27122 exports.SequenceComponent = SequenceComponent;
27123 Component_1.ComponentService.register(SequenceComponent);
27124 exports.default = SequenceComponent;
27126 },{"../../Component":226,"../../Edge":227,"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/scan":73,"rxjs/add/operator/share":74,"rxjs/add/operator/switchMap":79,"rxjs/add/operator/takeUntil":81,"rxjs/add/operator/withLatestFrom":83}],285:[function(require,module,exports){
27128 Object.defineProperty(exports, "__esModule", { value: true });
27129 var Subject_1 = require("rxjs/Subject");
27130 var SequenceDOMInteraction = (function () {
27131 function SequenceDOMInteraction() {
27132 this._mouseEnterDirection$ = new Subject_1.Subject();
27133 this._mouseLeaveDirection$ = new Subject_1.Subject();
27135 Object.defineProperty(SequenceDOMInteraction.prototype, "mouseEnterDirection$", {
27137 return this._mouseEnterDirection$;
27142 Object.defineProperty(SequenceDOMInteraction.prototype, "mouseLeaveDirection$", {
27144 return this._mouseLeaveDirection$;
27149 return SequenceDOMInteraction;
27151 exports.SequenceDOMInteraction = SequenceDOMInteraction;
27152 exports.default = SequenceDOMInteraction;
27154 },{"rxjs/Subject":34}],286:[function(require,module,exports){
27156 /// <reference path="../../../typings/index.d.ts" />
27157 Object.defineProperty(exports, "__esModule", { value: true });
27158 var vd = require("virtual-dom");
27159 var Edge_1 = require("../../Edge");
27160 var SequenceDOMRenderer = (function () {
27161 function SequenceDOMRenderer(element) {
27162 this._minThresholdWidth = 320;
27163 this._maxThresholdWidth = 1480;
27164 this._minThresholdHeight = 240;
27165 this._maxThresholdHeight = 820;
27167 SequenceDOMRenderer.prototype.render = function (edgeStatus, configuration, containerWidth, component, interaction, navigator) {
27168 if (configuration.visible === false) {
27169 return vd.h("div.SequenceContainer", {}, []);
27171 var nextKey = null;
27172 var prevKey = null;
27173 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
27175 if (edge.data.direction === Edge_1.EdgeDirection.Next) {
27178 if (edge.data.direction === Edge_1.EdgeDirection.Prev) {
27182 var playingButton = this._createPlayingButton(nextKey, prevKey, configuration, component);
27183 var arrows = this._createSequenceArrows(nextKey, prevKey, configuration, interaction, navigator);
27184 var containerProperties = {
27185 oncontextmenu: function (event) { event.preventDefault(); },
27186 style: { height: (0.27 * containerWidth) + "px", width: containerWidth + "px" },
27188 return vd.h("div.SequenceContainer", containerProperties, arrows.concat([playingButton]));
27190 SequenceDOMRenderer.prototype.getContainerWidth = function (element, configuration) {
27191 var elementWidth = element.offsetWidth;
27192 var elementHeight = element.offsetHeight;
27193 var minWidth = configuration.minWidth;
27194 var maxWidth = configuration.maxWidth;
27195 if (maxWidth < minWidth) {
27196 maxWidth = minWidth;
27198 var relativeWidth = (elementWidth - this._minThresholdWidth) / (this._maxThresholdWidth - this._minThresholdWidth);
27199 var relativeHeight = (elementHeight - this._minThresholdHeight) / (this._maxThresholdHeight - this._minThresholdHeight);
27200 var coeff = Math.max(0, Math.min(1, Math.min(relativeWidth, relativeHeight)));
27201 return minWidth + coeff * (maxWidth - minWidth);
27203 SequenceDOMRenderer.prototype._createPlayingButton = function (nextKey, prevKey, configuration, component) {
27204 var canPlay = configuration.direction === Edge_1.EdgeDirection.Next && nextKey != null ||
27205 configuration.direction === Edge_1.EdgeDirection.Prev && prevKey != null;
27206 var onclick = configuration.playing ?
27207 function (e) { component.stop(); } :
27208 canPlay ? function (e) { component.play(); } : null;
27209 var buttonProperties = {
27213 var iconClass = configuration.playing ?
27215 canPlay ? "Play" : "PlayDisabled";
27216 var icon = vd.h("div.SequenceComponentIcon", { className: iconClass }, []);
27217 var buttonClass = canPlay ? "SequencePlay" : "SequencePlayDisabled";
27218 return vd.h("div." + buttonClass, buttonProperties, [icon]);
27220 SequenceDOMRenderer.prototype._createSequenceArrows = function (nextKey, prevKey, configuration, interaction, navigator) {
27221 var nextProperties = {
27222 onclick: nextKey != null ?
27224 navigator.moveDir$(Edge_1.EdgeDirection.Next)
27225 .subscribe(function (node) { return; }, function (error) { console.error(error); });
27228 onmouseenter: function (e) { interaction.mouseEnterDirection$.next(Edge_1.EdgeDirection.Next); },
27229 onmouseleave: function (e) { interaction.mouseLeaveDirection$.next(Edge_1.EdgeDirection.Next); },
27232 var prevProperties = {
27233 onclick: prevKey != null ?
27235 navigator.moveDir$(Edge_1.EdgeDirection.Prev)
27236 .subscribe(function (node) { return; }, function (error) { console.error(error); });
27239 onmouseenter: function (e) { interaction.mouseEnterDirection$.next(Edge_1.EdgeDirection.Prev); },
27240 onmouseleave: function (e) { interaction.mouseLeaveDirection$.next(Edge_1.EdgeDirection.Prev); },
27243 var nextClass = this._getStepClassName(Edge_1.EdgeDirection.Next, nextKey, configuration.highlightKey);
27244 var prevClass = this._getStepClassName(Edge_1.EdgeDirection.Prev, prevKey, configuration.highlightKey);
27245 var nextIcon = vd.h("div.SequenceComponentIcon", []);
27246 var prevIcon = vd.h("div.SequenceComponentIcon", []);
27248 vd.h("div." + nextClass, nextProperties, [nextIcon]),
27249 vd.h("div." + prevClass, prevProperties, [prevIcon]),
27252 SequenceDOMRenderer.prototype._getStepClassName = function (direction, key, highlightKey) {
27253 var className = direction === Edge_1.EdgeDirection.Next ?
27254 "SequenceStepNext" :
27255 "SequenceStepPrev";
27257 className += "Disabled";
27260 if (highlightKey === key) {
27261 className += "Highlight";
27266 return SequenceDOMRenderer;
27268 exports.SequenceDOMRenderer = SequenceDOMRenderer;
27269 exports.default = SequenceDOMRenderer;
27271 },{"../../Edge":227,"virtual-dom":182}],287:[function(require,module,exports){
27273 Object.defineProperty(exports, "__esModule", { value: true });
27274 var GeometryTagError_1 = require("./error/GeometryTagError");
27275 exports.GeometryTagError = GeometryTagError_1.GeometryTagError;
27276 var PointGeometry_1 = require("./geometry/PointGeometry");
27277 exports.PointGeometry = PointGeometry_1.PointGeometry;
27278 var RectGeometry_1 = require("./geometry/RectGeometry");
27279 exports.RectGeometry = RectGeometry_1.RectGeometry;
27280 var PolygonGeometry_1 = require("./geometry/PolygonGeometry");
27281 exports.PolygonGeometry = PolygonGeometry_1.PolygonGeometry;
27282 var OutlineTag_1 = require("./tag/OutlineTag");
27283 exports.OutlineTag = OutlineTag_1.OutlineTag;
27284 var SpotTag_1 = require("./tag/SpotTag");
27285 exports.SpotTag = SpotTag_1.SpotTag;
27286 var TagComponent_1 = require("./TagComponent");
27287 exports.TagComponent = TagComponent_1.TagComponent;
27288 var TagMode_1 = require("./TagMode");
27289 exports.TagMode = TagMode_1.TagMode;
27291 },{"./TagComponent":288,"./TagMode":291,"./error/GeometryTagError":295,"./geometry/PointGeometry":297,"./geometry/PolygonGeometry":298,"./geometry/RectGeometry":299,"./tag/OutlineTag":303,"./tag/SpotTag":306}],288:[function(require,module,exports){
27293 /// <reference path="../../../typings/index.d.ts" />
27294 var __extends = (this && this.__extends) || (function () {
27295 var extendStatics = Object.setPrototypeOf ||
27296 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
27297 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
27298 return function (d, b) {
27299 extendStatics(d, b);
27300 function __() { this.constructor = d; }
27301 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
27304 Object.defineProperty(exports, "__esModule", { value: true });
27305 var when = require("when");
27306 var Observable_1 = require("rxjs/Observable");
27307 var Subject_1 = require("rxjs/Subject");
27308 require("rxjs/add/observable/combineLatest");
27309 require("rxjs/add/observable/empty");
27310 require("rxjs/add/observable/from");
27311 require("rxjs/add/observable/merge");
27312 require("rxjs/add/observable/of");
27313 require("rxjs/add/operator/combineLatest");
27314 require("rxjs/add/operator/concat");
27315 require("rxjs/add/operator/distinctUntilChanged");
27316 require("rxjs/add/operator/do");
27317 require("rxjs/add/operator/filter");
27318 require("rxjs/add/operator/map");
27319 require("rxjs/add/operator/merge");
27320 require("rxjs/add/operator/mergeMap");
27321 require("rxjs/add/operator/publishReplay");
27322 require("rxjs/add/operator/scan");
27323 require("rxjs/add/operator/share");
27324 require("rxjs/add/operator/skip");
27325 require("rxjs/add/operator/skipUntil");
27326 require("rxjs/add/operator/startWith");
27327 require("rxjs/add/operator/switchMap");
27328 require("rxjs/add/operator/take");
27329 require("rxjs/add/operator/takeUntil");
27330 require("rxjs/add/operator/withLatestFrom");
27331 var Component_1 = require("../../Component");
27332 var Geo_1 = require("../../Geo");
27333 var Render_1 = require("../../Render");
27335 * @class TagComponent
27337 * @classdesc Component for showing and editing tags with different
27338 * geometries composed from 2D basic image coordinates (see the
27339 * {@link Viewer} class documentation for more information about coordinate
27342 * The `add` method is used for adding new tags or replacing
27343 * tags already in the set. Tags are removed by id.
27345 * If a tag already in the set has the same
27346 * id as one of the tags added, the old tag will be removed and
27347 * the added tag will take its place.
27349 * The tag component mode can be set to either be non interactive or
27350 * to be in creating mode of a certain geometry type.
27352 * The tag properties can be updated at any time and the change will
27353 * be visibile immediately.
27355 * Tags are only relevant to a single image because they are based on
27356 * 2D basic image coordinates. Tags related to a certain image should
27357 * be removed when the viewer is moved to another node.
27359 * To retrive and use the tag component
27363 * var viewer = new Mapillary.Viewer(
27367 * { component: { tag: true } });
27369 * var tagComponent = viewer.getComponent("tag");
27372 var TagComponent = (function (_super) {
27373 __extends(TagComponent, _super);
27374 function TagComponent(name, container, navigator) {
27375 var _this = _super.call(this, name, container, navigator) || this;
27376 _this._tagDomRenderer = new Component_1.TagDOMRenderer();
27377 _this._tagScene = new Component_1.TagScene();
27378 _this._tagSet = new Component_1.TagSet();
27379 _this._tagCreator = new Component_1.TagCreator(_this, navigator);
27380 _this._viewportCoords = new Geo_1.ViewportCoords();
27381 _this._renderTags$ = _this._tagSet.changed$
27382 .map(function (tagSet) {
27383 var tags = tagSet.getAll();
27384 // ensure that tags are always rendered in the same order
27385 // to avoid hover tracking problems on first resize.
27386 tags.sort(function (t1, t2) {
27387 var id1 = t1.tag.id;
27388 var id2 = t2.tag.id;
27400 _this._tagChanged$ = _this._renderTags$
27401 .switchMap(function (tags) {
27402 return Observable_1.Observable
27404 .mergeMap(function (tag) {
27405 return Observable_1.Observable
27406 .merge(tag.tag.changed$, tag.tag.geometryChanged$);
27410 _this._renderTagGLChanged$ = _this._renderTags$
27411 .switchMap(function (tags) {
27412 return Observable_1.Observable
27414 .mergeMap(function (tag) {
27415 return tag.glObjectsChanged$;
27419 _this._tagInterationInitiated$ = _this._renderTags$
27420 .switchMap(function (tags) {
27421 return Observable_1.Observable
27423 .mergeMap(function (tag) {
27424 return tag.interact$
27425 .map(function (interaction) {
27426 return interaction.tag.id;
27431 _this._tagInteractionAbort$ = Observable_1.Observable
27432 .merge(_this._container.mouseService.documentMouseUp$)
27433 .map(function (e) { })
27435 _this._activeTag$ = _this._renderTags$
27436 .switchMap(function (tags) {
27437 return Observable_1.Observable
27439 .mergeMap(function (tag) {
27440 return tag.interact$;
27443 .merge(_this._tagInteractionAbort$
27445 return { offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: null };
27448 _this._createGeometryChanged$ = _this._tagCreator.tag$
27449 .switchMap(function (tag) {
27450 return tag != null ?
27451 tag.geometryChanged$ :
27452 Observable_1.Observable.empty();
27455 _this._createGLObjectsChanged$ = _this._tagCreator.tag$
27456 .switchMap(function (tag) {
27457 return tag != null ?
27458 tag.glObjectsChanged$ :
27459 Observable_1.Observable.empty();
27462 _this._tagCreated$ = _this._tagCreator.tag$
27463 .switchMap(function (tag) {
27464 return tag != null ?
27466 Observable_1.Observable.empty();
27469 _this._vertexGeometryCreated$ = _this._tagCreated$
27470 .map(function (tag) {
27471 return tag.geometry;
27474 _this._pointGeometryCreated$ = new Subject_1.Subject();
27475 _this._geometryCreated$ = Observable_1.Observable
27476 .merge(_this._vertexGeometryCreated$, _this._pointGeometryCreated$)
27478 _this._basicClick$ = _this._container.mouseService.staticClick$
27479 .withLatestFrom(_this._container.renderService.renderCamera$, _this._navigator.stateService.currentTransform$, function (event, renderCamera, transform) {
27480 return [event, renderCamera, transform];
27482 .map(function (ert) {
27483 var event = ert[0];
27484 var camera = ert[1];
27485 var transform = ert[2];
27486 var basic = _this._mouseEventToBasic(event, _this._container.element, camera, transform);
27490 _this._validBasicClick$ = _this._basicClick$
27491 .filter(function (basic) {
27494 return 0 <= x && x <= 1 && 0 <= y && y <= 1;
27497 _this._creatingConfiguration$ = _this._configuration$
27498 .distinctUntilChanged(function (c1, c2) {
27499 return c1.mode === c2.mode;
27500 }, function (configuration) {
27502 createColor: configuration.createColor,
27503 mode: configuration.mode,
27508 _this._creating$ = _this._creatingConfiguration$
27509 .map(function (configuration) {
27510 return configuration.mode !== Component_1.TagMode.Default;
27514 _this._creatingConfiguration$
27515 .subscribe(function (configuration) {
27516 _this.fire(TagComponent.modechanged, configuration.mode);
27521 * Add tags to the tag set or replace tags in the tag set.
27523 * @description If a tag already in the set has the same
27524 * id as one of the tags added, the old tag will be removed
27525 * the added tag will take its place.
27527 * @param {Array<Tag>} tags - Tags to add.
27529 * @example ```tagComponent.add([tag1, tag2]);```
27531 TagComponent.prototype.add = function (tags) {
27533 if (this._activated) {
27534 this._navigator.stateService.currentTransform$
27536 .subscribe(function (transform) {
27537 _this._tagSet.add(tags, transform);
27538 var renderTags = tags
27539 .map(function (tag) {
27540 return _this._tagSet.get(tag.id);
27542 _this._tagScene.add(renderTags);
27546 this._tagSet.addDeactivated(tags);
27550 * Change the current tag mode.
27552 * @description Change the tag mode to one of the create modes for creating new geometries.
27554 * @param {TagMode} mode - New tag mode.
27556 * @fires TagComponent#modechanged
27558 * @example ```tagComponent.changeMode(Mapillary.TagComponent.TagMode.CreateRect);```
27560 TagComponent.prototype.changeMode = function (mode) {
27561 this.configure({ mode: mode });
27564 * Returns the tag in the tag set with the specified id, or
27565 * undefined if the id matches no tag.
27567 * @param {string} tagId - Id of the tag.
27569 * @example ```var tag = tagComponent.get("tagId");```
27571 TagComponent.prototype.get = function (tagId) {
27572 if (this._activated) {
27573 var renderTag = this._tagSet.get(tagId);
27574 return renderTag !== undefined ? renderTag.tag : undefined;
27577 return this._tagSet.getDeactivated(tagId);
27581 * Returns an array of all tags.
27583 * @example ```var tags = tagComponent.getAll();```
27585 TagComponent.prototype.getAll = function () {
27586 if (this.activated) {
27587 return this._tagSet
27589 .map(function (renderTag) {
27590 return renderTag.tag;
27594 return this._tagSet.getAllDeactivated();
27598 * Returns an array of tag ids for tags that contain the specified point.
27600 * @description The pixel point must lie inside the polygon or rectangle
27601 * of an added tag for the tag id to be returned. Tag ids for
27602 * tags that do not have a fill will also be returned if the point is inside
27603 * the geometry of the tag. Tags with point geometries can not be retrieved.
27605 * No tag ids will be returned for panoramas.
27607 * Notice that the pixelPoint argument requires x, y coordinates from pixel space.
27609 * With this function, you can use the coordinates provided by mouse
27610 * events to get information out of the tag component.
27612 * If no tag at exist the pixel point, an empty array will be returned.
27614 * @param {Array<number>} pixelPoint - Pixel coordinates on the viewer element.
27615 * @returns {Array<string>} Ids of the tags that contain the specified pixel point.
27619 * tagComponent.getTagIdsAt([100, 100])
27620 * .then((tagIds) => { console.log(tagIds); });
27623 TagComponent.prototype.getTagIdsAt = function (pixelPoint) {
27625 return when.promise(function (resolve, reject) {
27626 _this._container.renderService.renderCamera$
27628 .map(function (render) {
27629 var viewport = _this._viewportCoords
27630 .canvasToViewport(pixelPoint[0], pixelPoint[1], _this._container.element);
27631 var ids = _this._tagScene.intersectObjects(viewport, render.perspective);
27634 .subscribe(function (ids) {
27636 }, function (error) {
27642 * Check if a tag exist in the tag set.
27644 * @param {string} tagId - Id of the tag.
27646 * @example ```var tagExists = tagComponent.has("tagId");```
27648 TagComponent.prototype.has = function (tagId) {
27649 return this._activated ? this._tagSet.has(tagId) : this._tagSet.hasDeactivated(tagId);
27652 * Remove tags with the specified ids from the tag set.
27654 * @param {Array<string>} tagIds - Ids for tags to remove.
27656 * @example ```tagComponent.remove(["id-1", "id-2"]);```
27658 TagComponent.prototype.remove = function (tagIds) {
27659 if (this._activated) {
27660 this._tagSet.remove(tagIds);
27661 this._tagScene.remove(tagIds);
27664 this._tagSet.removeDeactivated(tagIds);
27668 * Remove all tags from the tag set.
27670 * @example ```tagComponent.removeAll();```
27672 TagComponent.prototype.removeAll = function () {
27673 if (this._activated) {
27674 this._tagSet.removeAll();
27675 this._tagScene.removeAll();
27678 this._tagSet.removeAllDeactivated();
27681 TagComponent.prototype._activate = function () {
27683 this._preventDefaultSubscription = this._activeTag$
27684 .switchMap(function (interaction) {
27685 return interaction.tag != null ?
27686 _this._container.mouseService.documentMouseMove$ :
27687 Observable_1.Observable.empty();
27689 .subscribe(function (event) {
27690 event.preventDefault(); // prevent selection of content outside the viewer
27692 this._geometryCreatedEventSubscription = this._geometryCreated$
27693 .subscribe(function (geometry) {
27694 _this.fire(TagComponent.geometrycreated, geometry);
27696 this._tagsChangedEventSubscription = this._renderTags$
27697 .subscribe(function (tags) {
27698 _this.fire(TagComponent.tagschanged, _this);
27700 var transformChanged$ = this.configuration$
27701 .switchMap(function (configuration) {
27702 return configuration.mode !== Component_1.TagMode.Default ?
27703 _this._navigator.stateService.currentTransform$
27704 .map(function (n) { return null; }) :
27705 Observable_1.Observable.empty();
27709 this._deleteCreatingSubscription = transformChanged$
27711 .subscribe(function () {
27712 _this._tagCreator.delete$.next(null);
27714 var tagAborted$ = this._tagCreator.tag$
27715 .switchMap(function (tag) {
27716 return tag != null ?
27718 .map(function (t) { return null; }) :
27719 Observable_1.Observable.empty();
27721 var tagCreated$ = this._tagCreated$
27722 .map(function (t) { return null; });
27723 var pointGeometryCreated$ = this._pointGeometryCreated$
27724 .map(function (p) { return null; });
27725 this._stopCreateSubscription = Observable_1.Observable
27726 .merge(tagAborted$, tagCreated$, pointGeometryCreated$)
27727 .subscribe(function () { _this.changeMode(Component_1.TagMode.Default); });
27728 var creatingStarted$ = Observable_1.Observable
27729 .combineLatest(this._creatingConfiguration$, transformChanged$)
27730 .map(function (_a) {
27731 var configuration = _a[0];
27732 return configuration;
27736 this._createSubscription = creatingStarted$
27737 .switchMap(function (configuration) {
27738 return configuration.mode === Component_1.TagMode.CreateRect ||
27739 configuration.mode === Component_1.TagMode.CreatePolygon ?
27740 _this._validBasicClick$.take(1) :
27741 Observable_1.Observable.empty();
27743 .subscribe(this._tagCreator.create$);
27744 this._createPointSubscription = creatingStarted$
27745 .switchMap(function (configuration) {
27746 return configuration.mode === Component_1.TagMode.CreatePoint ?
27747 _this._validBasicClick$.take(1) :
27748 Observable_1.Observable.empty();
27750 .map(function (basic) {
27751 return new Component_1.PointGeometry(basic);
27753 .subscribe(this._pointGeometryCreated$);
27754 var containerMouseMove$ = Observable_1.Observable
27755 .merge(this._container.mouseService.mouseMove$, this._container.mouseService.domMouseMove$)
27757 this._setCreateVertexSubscription = Observable_1.Observable
27758 .combineLatest(containerMouseMove$, this._tagCreator.tag$, this._container.renderService.renderCamera$)
27759 .filter(function (etr) {
27760 return etr[1] != null;
27762 .withLatestFrom(this._navigator.stateService.currentTransform$, function (etr, transform) {
27763 return [etr[0], etr[1], etr[2], transform];
27765 .subscribe(function (etrt) {
27766 var event = etrt[0];
27768 var camera = etrt[2];
27769 var transform = etrt[3];
27770 var basic = _this._mouseEventToBasic(event, _this._container.element, camera, transform);
27771 if (tag.geometry instanceof Component_1.RectGeometry) {
27772 tag.geometry.setVertex2d(3, basic, transform);
27774 else if (tag.geometry instanceof Component_1.PolygonGeometry) {
27775 tag.geometry.setVertex2d(tag.geometry.polygon.length - 2, basic, transform);
27778 this._addPointSubscription = creatingStarted$
27779 .switchMap(function (configuration) {
27780 return configuration.mode === Component_1.TagMode.CreateRect || configuration.mode === Component_1.TagMode.CreatePolygon ?
27781 _this._basicClick$.skipUntil(_this._validBasicClick$).skip(1) :
27782 Observable_1.Observable.empty();
27784 .withLatestFrom(this._tagCreator.tag$, function (basic, tag) {
27785 return [basic, tag];
27787 .subscribe(function (bt) {
27790 tag.addPoint(basic);
27792 this._containerClassListSubscription = this._creating$
27793 .subscribe(function (creating) {
27795 _this._container.element.classList.add("component-tag-create");
27798 _this._container.element.classList.remove("component-tag-create");
27801 this._deleteCreatedSubscription = this._creating$
27802 .subscribe(function (creating) {
27803 _this._tagCreator.delete$.next(null);
27805 this._setGLCreateTagSubscription = this._tagCreator.tag$
27806 .subscribe(function (tag) {
27807 if (_this._tagScene.hasCreateTag()) {
27808 _this._tagScene.removeCreateTag();
27811 _this._tagScene.addCreateTag(tag);
27814 this._createGLObjectsChangedSubscription = this._createGLObjectsChanged$
27815 .subscribe(function (tag) {
27816 _this._tagScene.updateCreateTagObjects(tag);
27818 this._claimMouseSubscription = this._tagInterationInitiated$
27819 .switchMap(function (id) {
27820 return containerMouseMove$
27821 .takeUntil(_this._tagInteractionAbort$)
27824 .subscribe(function (e) {
27825 _this._container.mouseService.claimMouse(_this._name, 1);
27827 this._mouseDragSubscription = this._activeTag$
27828 .withLatestFrom(containerMouseMove$, function (a, e) {
27831 .switchMap(function (args) {
27832 var activeTag = args[0];
27833 var mouseMove = args[1];
27834 if (activeTag.operation === Component_1.TagOperation.None) {
27835 return Observable_1.Observable.empty();
27837 var mouseDrag$ = Observable_1.Observable
27839 .concat(_this._container.mouseService
27840 .filtered$(_this._name, _this._container.mouseService.domMouseDrag$)
27841 .filter(function (event) {
27842 return _this._viewportCoords.insideElement(event, _this._container.element);
27844 return Observable_1.Observable
27845 .combineLatest(mouseDrag$, _this._container.renderService.renderCamera$)
27846 .withLatestFrom(Observable_1.Observable.of(activeTag), _this._navigator.stateService.currentTransform$, function (ec, a, t) {
27847 return [ec[0], ec[1], a, t];
27850 .subscribe(function (args) {
27851 var mouseEvent = args[0];
27852 var renderCamera = args[1];
27853 var activeTag = args[2];
27854 var transform = args[3];
27855 if (activeTag.operation === Component_1.TagOperation.None) {
27858 var basic = _this._mouseEventToBasic(mouseEvent, _this._container.element, renderCamera, transform, activeTag.offsetX, activeTag.offsetY);
27859 if (activeTag.operation === Component_1.TagOperation.Centroid) {
27860 activeTag.tag.geometry.setCentroid2d(basic, transform);
27862 else if (activeTag.operation === Component_1.TagOperation.Vertex) {
27863 var vertexGeometry = activeTag.tag.geometry;
27864 vertexGeometry.setVertex2d(activeTag.vertexIndex, basic, transform);
27867 this._unclaimMouseSubscription = this._container.mouseService
27868 .filtered$(this._name, this._container.mouseService.domMouseDragEnd$)
27869 .subscribe(function (e) {
27870 _this._container.mouseService.unclaimMouse(_this._name);
27872 this._updateGLObjectsSubscription = this._renderTagGLChanged$
27873 .subscribe(function (tag) {
27874 _this._tagScene.updateObjects(tag);
27876 this._updateTagSceneSubscription = this._tagChanged$
27877 .subscribe(function (tag) {
27878 _this._tagScene.update();
27880 this._domSubscription = this._renderTags$
27882 .do(function (tags) {
27883 _this._container.domRenderer.render$.next({
27885 vnode: _this._tagDomRenderer.clear(),
27888 .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) {
27889 return [rc, atlas, size, renderTags, tag, ct];
27891 .map(function (args) {
27894 vnode: _this._tagDomRenderer.render(args[3], args[5], args[1], args[0].perspective, args[2]),
27897 .subscribe(this._container.domRenderer.render$);
27898 this._glSubscription = this._navigator.stateService.currentState$
27899 .map(function (frame) {
27900 var tagScene = _this._tagScene;
27905 needsRender: tagScene.needsRender,
27906 render: tagScene.render.bind(tagScene),
27907 stage: Render_1.GLRenderStage.Foreground,
27911 .subscribe(this._container.glRenderer.render$);
27912 this._navigator.stateService.currentTransform$
27914 .subscribe(function (transform) {
27915 _this._tagSet.activate(transform);
27916 _this._tagScene.add(_this._tagSet.getAll());
27919 TagComponent.prototype._deactivate = function () {
27920 this._tagScene.clear();
27921 this._tagSet.deactivate();
27922 this._tagCreator.delete$.next(null);
27923 this._claimMouseSubscription.unsubscribe();
27924 this._mouseDragSubscription.unsubscribe();
27925 this._unclaimMouseSubscription.unsubscribe();
27926 this._updateGLObjectsSubscription.unsubscribe();
27927 this._updateTagSceneSubscription.unsubscribe();
27928 this._stopCreateSubscription.unsubscribe();
27929 this._deleteCreatingSubscription.unsubscribe();
27930 this._createSubscription.unsubscribe();
27931 this._createPointSubscription.unsubscribe();
27932 this._setCreateVertexSubscription.unsubscribe();
27933 this._addPointSubscription.unsubscribe();
27934 this._deleteCreatedSubscription.unsubscribe();
27935 this._setGLCreateTagSubscription.unsubscribe();
27936 this._createGLObjectsChangedSubscription.unsubscribe();
27937 this._preventDefaultSubscription.unsubscribe();
27938 this._containerClassListSubscription.unsubscribe();
27939 this._domSubscription.unsubscribe();
27940 this._glSubscription.unsubscribe();
27941 this._geometryCreatedEventSubscription.unsubscribe();
27942 this._tagsChangedEventSubscription.unsubscribe();
27943 this._container.element.classList.remove("component-tag-create");
27945 TagComponent.prototype._getDefaultConfiguration = function () {
27947 createColor: 0xFFFFFF,
27948 mode: Component_1.TagMode.Default,
27951 TagComponent.prototype._mouseEventToBasic = function (event, element, camera, transform, offsetX, offsetY) {
27952 offsetX = offsetX != null ? offsetX : 0;
27953 offsetY = offsetY != null ? offsetY : 0;
27954 var _a = this._viewportCoords.canvasPosition(event, element), canvasX = _a[0], canvasY = _a[1];
27955 var basic = this._viewportCoords.canvasToBasic(canvasX - offsetX, canvasY - offsetY, element, transform, camera.perspective);
27959 TagComponent.componentName = "tag";
27961 * Event fired when the create mode is changed.
27963 * @event TagComponent#modechanged
27964 * @type {TagMode} Tag mode
27967 * tagComponent.on("modechanged", function(mode) {
27968 * console.log(mode);
27972 TagComponent.modechanged = "modechanged";
27974 * Event fired when a geometry has been created.
27976 * @event TagComponent#geometrycreated
27977 * @type {Geometry} Created geometry.
27980 * tagComponent.on("geometrycreated", function(geometry) {
27981 * console.log(geometry);
27985 TagComponent.geometrycreated = "geometrycreated";
27987 * Event fired when the tags collection has changed.
27989 * @event TagComponent#tagschanged
27990 * @type {TagComponent} Tag component.
27993 * tagComponent.on("tagschanged", function(component) {
27994 * console.log(component.getAll());
27998 TagComponent.tagschanged = "tagschanged";
27999 return TagComponent;
28000 }(Component_1.Component));
28001 exports.TagComponent = TagComponent;
28002 Component_1.ComponentService.register(TagComponent);
28003 exports.default = TagComponent;
28005 },{"../../Component":226,"../../Geo":229,"../../Render":232,"rxjs/Observable":29,"rxjs/Subject":34,"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":73,"rxjs/add/operator/share":74,"rxjs/add/operator/skip":75,"rxjs/add/operator/skipUntil":76,"rxjs/add/operator/startWith":78,"rxjs/add/operator/switchMap":79,"rxjs/add/operator/take":80,"rxjs/add/operator/takeUntil":81,"rxjs/add/operator/withLatestFrom":83,"when":223}],289:[function(require,module,exports){
28007 Object.defineProperty(exports, "__esModule", { value: true });
28008 var Subject_1 = require("rxjs/Subject");
28009 require("rxjs/add/operator/map");
28010 require("rxjs/add/operator/scan");
28011 require("rxjs/add/operator/share");
28012 require("rxjs/add/operator/withLatestFrom");
28013 var Component_1 = require("../../Component");
28014 var TagCreator = (function () {
28015 function TagCreator(component, navigator) {
28016 this._component = component;
28017 this._navigator = navigator;
28018 this._tagOperation$ = new Subject_1.Subject();
28019 this._create$ = new Subject_1.Subject();
28020 this._delete$ = new Subject_1.Subject();
28021 this._tag$ = this._tagOperation$
28022 .scan(function (tag, operation) {
28023 return operation(tag);
28027 .withLatestFrom(this._component.configuration$, this._navigator.stateService.currentTransform$)
28028 .map(function (_a) {
28029 var coord = _a[0], conf = _a[1], transform = _a[2];
28030 return function (tag) {
28031 if (conf.mode === Component_1.TagMode.CreateRect) {
28032 var geometry = new Component_1.RectGeometry([
28038 return new Component_1.OutlineCreateTag(geometry, { color: conf.createColor }, transform);
28040 else if (conf.mode === Component_1.TagMode.CreatePolygon) {
28041 var geometry = new Component_1.PolygonGeometry([
28042 [coord[0], coord[1]],
28043 [coord[0], coord[1]],
28044 [coord[0], coord[1]],
28046 return new Component_1.OutlineCreateTag(geometry, { color: conf.createColor }, transform);
28051 .subscribe(this._tagOperation$);
28054 return function (tag) {
28058 .subscribe(this._tagOperation$);
28060 Object.defineProperty(TagCreator.prototype, "create$", {
28062 return this._create$;
28067 Object.defineProperty(TagCreator.prototype, "delete$", {
28069 return this._delete$;
28074 Object.defineProperty(TagCreator.prototype, "tag$", {
28083 exports.TagCreator = TagCreator;
28084 exports.default = TagCreator;
28086 },{"../../Component":226,"rxjs/Subject":34,"rxjs/add/operator/map":65,"rxjs/add/operator/scan":73,"rxjs/add/operator/share":74,"rxjs/add/operator/withLatestFrom":83}],290:[function(require,module,exports){
28088 /// <reference path="../../../typings/index.d.ts" />
28089 Object.defineProperty(exports, "__esModule", { value: true });
28090 var vd = require("virtual-dom");
28091 var TagDOMRenderer = (function () {
28092 function TagDOMRenderer() {
28094 TagDOMRenderer.prototype.render = function (tags, createTag, atlas, camera, size) {
28096 for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
28097 var tag = tags_1[_i];
28098 vNodes = vNodes.concat(tag.getDOMObjects(atlas, camera, size));
28100 if (createTag != null) {
28101 vNodes = vNodes.concat(createTag.getDOMObjects(camera, size));
28103 return vd.h("div.TagContainer", {}, vNodes);
28105 TagDOMRenderer.prototype.clear = function () {
28106 return vd.h("div", {}, []);
28108 return TagDOMRenderer;
28110 exports.TagDOMRenderer = TagDOMRenderer;
28112 },{"virtual-dom":182}],291:[function(require,module,exports){
28114 Object.defineProperty(exports, "__esModule", { value: true });
28116 * Enumeration for tag modes
28119 * @description Modes for the interaction in the tag component.
28122 (function (TagMode) {
28124 * Disables creating tags.
28126 TagMode[TagMode["Default"] = 0] = "Default";
28128 * Create a point geometry through a click.
28130 TagMode[TagMode["CreatePoint"] = 1] = "CreatePoint";
28132 * Create a polygon geometry through clicks.
28134 TagMode[TagMode["CreatePolygon"] = 2] = "CreatePolygon";
28136 * Create a rect geometry through clicks.
28138 TagMode[TagMode["CreateRect"] = 3] = "CreateRect";
28139 })(TagMode = exports.TagMode || (exports.TagMode = {}));
28140 exports.default = TagMode;
28142 },{}],292:[function(require,module,exports){
28144 Object.defineProperty(exports, "__esModule", { value: true });
28146 (function (TagOperation) {
28147 TagOperation[TagOperation["None"] = 0] = "None";
28148 TagOperation[TagOperation["Centroid"] = 1] = "Centroid";
28149 TagOperation[TagOperation["Vertex"] = 2] = "Vertex";
28150 })(TagOperation = exports.TagOperation || (exports.TagOperation = {}));
28151 exports.default = TagOperation;
28153 },{}],293:[function(require,module,exports){
28155 /// <reference path="../../../typings/index.d.ts" />
28156 Object.defineProperty(exports, "__esModule", { value: true });
28157 var THREE = require("three");
28158 var TagScene = (function () {
28159 function TagScene(scene, raycaster) {
28160 this._createTag = null;
28161 this._needsRender = false;
28162 this._raycaster = !!raycaster ? raycaster : new THREE.Raycaster();
28163 this._scene = !!scene ? scene : new THREE.Scene();
28164 this._objectTags = {};
28165 this._retrievableObjects = [];
28168 Object.defineProperty(TagScene.prototype, "needsRender", {
28170 return this._needsRender;
28175 TagScene.prototype.add = function (tags) {
28176 for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
28177 var tag = tags_1[_i];
28178 if (tag.tag.id in this._tags) {
28179 this._remove(tag.tag.id);
28183 this._needsRender = true;
28185 TagScene.prototype.addCreateTag = function (tag) {
28186 for (var _i = 0, _a = tag.glObjects; _i < _a.length; _i++) {
28187 var object = _a[_i];
28188 this._scene.add(object);
28190 this._createTag = { tag: tag, objects: tag.glObjects };
28191 this._needsRender = true;
28193 TagScene.prototype.clear = function () {
28194 for (var _i = 0, _a = Object.keys(this._tags); _i < _a.length; _i++) {
28198 this._needsRender = false;
28200 TagScene.prototype.get = function (id) {
28201 return this.has(id) ? this._tags[id].tag : undefined;
28203 TagScene.prototype.has = function (id) {
28204 return id in this._tags;
28206 TagScene.prototype.hasCreateTag = function () {
28207 return this._createTag != null;
28209 TagScene.prototype.intersectObjects = function (_a, camera) {
28210 var viewportX = _a[0], viewportY = _a[1];
28211 this._raycaster.setFromCamera(new THREE.Vector2(viewportX, viewportY), camera);
28212 var intersects = this._raycaster.intersectObjects(this._retrievableObjects);
28213 var intersectedIds = [];
28214 for (var _i = 0, intersects_1 = intersects; _i < intersects_1.length; _i++) {
28215 var intersect = intersects_1[_i];
28216 if (intersect.object.uuid in this._objectTags) {
28217 intersectedIds.push(this._objectTags[intersect.object.uuid]);
28220 return intersectedIds;
28222 TagScene.prototype.remove = function (ids) {
28223 for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
28224 var id = ids_1[_i];
28227 this._needsRender = true;
28229 TagScene.prototype.removeAll = function () {
28230 for (var _i = 0, _a = Object.keys(this._tags); _i < _a.length; _i++) {
28234 this._needsRender = true;
28236 TagScene.prototype.removeCreateTag = function () {
28237 if (this._createTag == null) {
28240 for (var _i = 0, _a = this._createTag.objects; _i < _a.length; _i++) {
28241 var object = _a[_i];
28242 this._scene.remove(object);
28244 this._createTag.tag.dispose();
28245 this._createTag = null;
28246 this._needsRender = true;
28248 TagScene.prototype.render = function (perspectiveCamera, renderer) {
28249 renderer.render(this._scene, perspectiveCamera);
28250 this._needsRender = false;
28252 TagScene.prototype.update = function () {
28253 this._needsRender = true;
28255 TagScene.prototype.updateCreateTagObjects = function (tag) {
28256 if (this._createTag.tag !== tag) {
28257 throw new Error("Create tags do not have the same reference.");
28259 for (var _i = 0, _a = this._createTag.objects; _i < _a.length; _i++) {
28260 var object = _a[_i];
28261 this._scene.remove(object);
28263 for (var _b = 0, _c = tag.glObjects; _b < _c.length; _b++) {
28264 var object = _c[_b];
28265 this._scene.add(object);
28267 this._createTag.objects = tag.glObjects;
28268 this._needsRender = true;
28270 TagScene.prototype.updateObjects = function (tag) {
28271 var id = tag.tag.id;
28272 if (this._tags[id].tag !== tag) {
28273 throw new Error("Tags do not have the same reference.");
28275 var tagObjects = this._tags[id];
28276 this._removeObjects(tagObjects);
28277 delete this._tags[id];
28279 this._needsRender = true;
28281 TagScene.prototype._add = function (tag) {
28282 var id = tag.tag.id;
28283 var tagObjects = { tag: tag, objects: [], retrievableObjects: [] };
28284 this._tags[id] = tagObjects;
28285 for (var _i = 0, _a = tag.getGLObjects(); _i < _a.length; _i++) {
28286 var object = _a[_i];
28287 tagObjects.objects.push(object);
28288 this._scene.add(object);
28290 for (var _b = 0, _c = tag.getRetrievableObjects(); _b < _c.length; _b++) {
28291 var retrievableObject = _c[_b];
28292 tagObjects.retrievableObjects.push(retrievableObject);
28293 this._retrievableObjects.push(retrievableObject);
28294 this._objectTags[retrievableObject.uuid] = tag.tag.id;
28297 TagScene.prototype._remove = function (id) {
28298 var tagObjects = this._tags[id];
28299 this._removeObjects(tagObjects);
28300 tagObjects.tag.dispose();
28301 delete this._tags[id];
28303 TagScene.prototype._removeObjects = function (tagObjects) {
28304 for (var _i = 0, _a = tagObjects.objects; _i < _a.length; _i++) {
28305 var object = _a[_i];
28306 this._scene.remove(object);
28308 for (var _b = 0, _c = tagObjects.retrievableObjects; _b < _c.length; _b++) {
28309 var retrievableObject = _c[_b];
28310 var index = this._retrievableObjects.indexOf(retrievableObject);
28311 if (index !== -1) {
28312 this._retrievableObjects.splice(index, 1);
28318 exports.TagScene = TagScene;
28319 exports.default = TagScene;
28321 },{"three":176}],294:[function(require,module,exports){
28323 Object.defineProperty(exports, "__esModule", { value: true });
28324 var Subject_1 = require("rxjs/Subject");
28325 require("rxjs/add/operator/map");
28326 require("rxjs/add/operator/scan");
28327 require("rxjs/add/operator/share");
28328 var Component_1 = require("../../Component");
28329 var TagSet = (function () {
28330 function TagSet() {
28331 this._active = false;
28333 this._hashDeactivated = {};
28334 this._notifyChanged$ = new Subject_1.Subject();
28336 Object.defineProperty(TagSet.prototype, "active", {
28338 return this._active;
28343 Object.defineProperty(TagSet.prototype, "changed$", {
28345 return this._notifyChanged$;
28350 TagSet.prototype.activate = function (transform) {
28351 if (this._active) {
28354 for (var id in this._hashDeactivated) {
28355 if (!this._hashDeactivated.hasOwnProperty(id)) {
28358 var tag = this._hashDeactivated[id];
28359 this._add(tag, transform);
28361 this._hashDeactivated = {};
28362 this._active = true;
28363 this._notifyChanged$.next(this);
28365 TagSet.prototype.deactivate = function () {
28366 if (!this._active) {
28369 for (var id in this._hash) {
28370 if (!this._hash.hasOwnProperty(id)) {
28373 this._hashDeactivated[id] = this._hash[id].tag;
28376 this._active = false;
28378 TagSet.prototype.add = function (tags, transform) {
28379 this._assertActivationState(true);
28380 for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
28381 var tag = tags_1[_i];
28382 this._add(tag, transform);
28384 this._notifyChanged$.next(this);
28386 TagSet.prototype.addDeactivated = function (tags) {
28387 this._assertActivationState(false);
28388 for (var _i = 0, tags_2 = tags; _i < tags_2.length; _i++) {
28389 var tag = tags_2[_i];
28390 if (!(tag instanceof Component_1.OutlineTag || tag instanceof Component_1.SpotTag)) {
28391 throw new Error("Tag type not supported");
28393 this._hashDeactivated[tag.id] = tag;
28396 TagSet.prototype.get = function (id) {
28397 return this.has(id) ? this._hash[id] : undefined;
28399 TagSet.prototype.getAll = function () {
28400 var hash = this._hash;
28401 return Object.keys(hash)
28402 .map(function (id) {
28406 TagSet.prototype.getAllDeactivated = function () {
28407 var hashDeactivated = this._hashDeactivated;
28408 return Object.keys(hashDeactivated)
28409 .map(function (id) {
28410 return hashDeactivated[id];
28413 TagSet.prototype.getDeactivated = function (id) {
28414 return this.hasDeactivated(id) ? this._hashDeactivated[id] : undefined;
28416 TagSet.prototype.has = function (id) {
28417 return id in this._hash;
28419 TagSet.prototype.hasDeactivated = function (id) {
28420 return id in this._hashDeactivated;
28422 TagSet.prototype.remove = function (ids) {
28423 this._assertActivationState(true);
28424 var hash = this._hash;
28425 for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
28426 var id = ids_1[_i];
28427 if (!(id in hash)) {
28432 this._notifyChanged$.next(this);
28434 TagSet.prototype.removeAll = function () {
28435 this._assertActivationState(true);
28437 this._notifyChanged$.next(this);
28439 TagSet.prototype.removeAllDeactivated = function () {
28440 this._assertActivationState(false);
28441 this._hashDeactivated = {};
28443 TagSet.prototype.removeDeactivated = function (ids) {
28444 this._assertActivationState(false);
28445 var hashDeactivated = this._hashDeactivated;
28446 for (var _i = 0, ids_2 = ids; _i < ids_2.length; _i++) {
28447 var id = ids_2[_i];
28448 if (!(id in hashDeactivated)) {
28451 delete hashDeactivated[id];
28454 TagSet.prototype._add = function (tag, transform) {
28455 if (tag instanceof Component_1.OutlineTag) {
28456 this._hash[tag.id] = new Component_1.OutlineRenderTag(tag, transform);
28458 else if (tag instanceof Component_1.SpotTag) {
28459 this._hash[tag.id] = new Component_1.SpotRenderTag(tag, transform);
28462 throw new Error("Tag type not supported");
28465 TagSet.prototype._assertActivationState = function (should) {
28466 if (should !== this._active) {
28467 throw new Error("Tag set not in correct state for operation.");
28472 exports.TagSet = TagSet;
28473 exports.default = TagSet;
28475 },{"../../Component":226,"rxjs/Subject":34,"rxjs/add/operator/map":65,"rxjs/add/operator/scan":73,"rxjs/add/operator/share":74}],295:[function(require,module,exports){
28477 var __extends = (this && this.__extends) || (function () {
28478 var extendStatics = Object.setPrototypeOf ||
28479 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28480 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28481 return function (d, b) {
28482 extendStatics(d, b);
28483 function __() { this.constructor = d; }
28484 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28487 Object.defineProperty(exports, "__esModule", { value: true });
28488 var Error_1 = require("../../../Error");
28489 var GeometryTagError = (function (_super) {
28490 __extends(GeometryTagError, _super);
28491 function GeometryTagError(message) {
28492 var _this = _super.call(this, message != null ? message : "The provided geometry value is incorrect") || this;
28493 _this.name = "GeometryTagError";
28496 return GeometryTagError;
28497 }(Error_1.MapillaryError));
28498 exports.GeometryTagError = GeometryTagError;
28499 exports.default = Error_1.MapillaryError;
28501 },{"../../../Error":228}],296:[function(require,module,exports){
28503 Object.defineProperty(exports, "__esModule", { value: true });
28504 var Subject_1 = require("rxjs/Subject");
28508 * @classdesc Represents a geometry.
28510 var Geometry = (function () {
28512 * Create a geometry.
28516 function Geometry() {
28517 this._notifyChanged$ = new Subject_1.Subject();
28519 Object.defineProperty(Geometry.prototype, "changed$", {
28521 * Get changed observable.
28523 * @description Emits the geometry itself every time the geometry
28526 * @returns {Observable<Geometry>} Observable emitting the geometry instance.
28530 return this._notifyChanged$;
28537 exports.Geometry = Geometry;
28538 exports.default = Geometry;
28540 },{"rxjs/Subject":34}],297:[function(require,module,exports){
28542 var __extends = (this && this.__extends) || (function () {
28543 var extendStatics = Object.setPrototypeOf ||
28544 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28545 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28546 return function (d, b) {
28547 extendStatics(d, b);
28548 function __() { this.constructor = d; }
28549 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28552 Object.defineProperty(exports, "__esModule", { value: true });
28553 var Component_1 = require("../../../Component");
28555 * @class PointGeometry
28557 * @classdesc Represents a point geometry in the 2D basic image coordinate system.
28561 * var basicPoint = [0.5, 0.7];
28562 * var pointGeometry = new Mapillary.TagComponent.PointGeometry(basicPoint);
28565 var PointGeometry = (function (_super) {
28566 __extends(PointGeometry, _super);
28568 * Create a point geometry.
28571 * @param {Array<number>} point - An array representing the basic coordinates of
28574 * @throws {GeometryTagError} Point coordinates must be valid basic coordinates.
28576 function PointGeometry(point) {
28577 var _this = _super.call(this) || this;
28580 if (x < 0 || x > 1 || y < 0 || y > 1) {
28581 throw new Component_1.GeometryTagError("Basic coordinates must be on the interval [0, 1].");
28583 _this._point = point.slice();
28586 Object.defineProperty(PointGeometry.prototype, "point", {
28588 * Get point property.
28589 * @returns {Array<number>} Array representing the basic coordinates of the point.
28592 return this._point;
28598 * Get the 2D basic coordinates for the centroid of the point, i.e. the 2D
28599 * basic coordinates of the point itself.
28601 * @returns {Array<number>} 2D basic coordinates representing the centroid.
28603 PointGeometry.prototype.getCentroid2d = function () {
28604 return this._point.slice();
28607 * Get the 3D world coordinates for the centroid of the point, i.e. the 3D
28608 * world coordinates of the point itself.
28610 * @param {Transform} transform - The transform of the node related to the point.
28611 * @returns {Array<number>} 3D world coordinates representing the centroid.
28613 PointGeometry.prototype.getCentroid3d = function (transform) {
28614 return transform.unprojectBasic(this._point, 200);
28617 * Set the centroid of the point, i.e. the point coordinates.
28619 * @param {Array<number>} value - The new value of the centroid.
28620 * @param {Transform} transform - The transform of the node related to the point.
28622 PointGeometry.prototype.setCentroid2d = function (value, transform) {
28624 Math.max(0, Math.min(1, value[0])),
28625 Math.max(0, Math.min(1, value[1])),
28627 this._point[0] = changed[0];
28628 this._point[1] = changed[1];
28629 this._notifyChanged$.next(this);
28631 return PointGeometry;
28632 }(Component_1.Geometry));
28633 exports.PointGeometry = PointGeometry;
28635 },{"../../../Component":226}],298:[function(require,module,exports){
28637 var __extends = (this && this.__extends) || (function () {
28638 var extendStatics = Object.setPrototypeOf ||
28639 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28640 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28641 return function (d, b) {
28642 extendStatics(d, b);
28643 function __() { this.constructor = d; }
28644 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28647 Object.defineProperty(exports, "__esModule", { value: true });
28648 var Component_1 = require("../../../Component");
28650 * @class PolygonGeometry
28652 * @classdesc Represents a polygon geometry in the 2D basic image coordinate system.
28653 * All polygons and holes provided to the constructor needs to be closed.
28657 * var basicPolygon = [[0.5, 0.3], [0.7, 0.3], [0.6, 0.5], [0.5, 0.3]];
28658 * var polygonGeometry = new Mapillary.TagComponent.PointGeometry(basicPolygon);
28661 var PolygonGeometry = (function (_super) {
28662 __extends(PolygonGeometry, _super);
28664 * Create a polygon geometry.
28667 * @param {Array<Array<number>>} polygon - Array of polygon vertices. Must be closed.
28668 * @param {Array<Array<Array<number>>>} [holes] - Array of arrays of hole vertices.
28669 * Each array of holes vertices must be closed.
28671 * @throws {GeometryTagError} Polygon coordinates must be valid basic coordinates.
28673 function PolygonGeometry(polygon, holes) {
28674 var _this = _super.call(this) || this;
28675 var polygonLength = polygon.length;
28676 if (polygonLength < 3) {
28677 throw new Component_1.GeometryTagError("A polygon must have three or more positions.");
28679 if (polygon[0][0] !== polygon[polygonLength - 1][0] ||
28680 polygon[0][1] !== polygon[polygonLength - 1][1]) {
28681 throw new Component_1.GeometryTagError("First and last positions must be equivalent.");
28683 _this._polygon = [];
28684 for (var _i = 0, polygon_1 = polygon; _i < polygon_1.length; _i++) {
28685 var vertex = polygon_1[_i];
28686 if (vertex[0] < 0 || vertex[0] > 1 ||
28687 vertex[1] < 0 || vertex[1] > 1) {
28688 throw new Component_1.GeometryTagError("Basic coordinates of polygon must be on the interval [0, 1].");
28690 _this._polygon.push(vertex.slice());
28693 if (holes == null) {
28696 for (var i = 0; i < holes.length; i++) {
28697 var hole = holes[i];
28698 var holeLength = hole.length;
28699 if (holeLength < 3) {
28700 throw new Component_1.GeometryTagError("A polygon hole must have three or more positions.");
28702 if (hole[0][0] !== hole[holeLength - 1][0] ||
28703 hole[0][1] !== hole[holeLength - 1][1]) {
28704 throw new Component_1.GeometryTagError("First and last positions of hole must be equivalent.");
28706 _this._holes.push([]);
28707 for (var _a = 0, hole_1 = hole; _a < hole_1.length; _a++) {
28708 var vertex = hole_1[_a];
28709 if (vertex[0] < 0 || vertex[0] > 1 ||
28710 vertex[1] < 0 || vertex[1] > 1) {
28711 throw new Component_1.GeometryTagError("Basic coordinates of hole must be on the interval [0, 1].");
28713 _this._holes[i].push(vertex.slice());
28718 Object.defineProperty(PolygonGeometry.prototype, "polygon", {
28720 * Get polygon property.
28721 * @returns {Array<Array<number>>} Closed 2d polygon.
28724 return this._polygon;
28729 Object.defineProperty(PolygonGeometry.prototype, "holes", {
28731 * Get holes property.
28732 * @returns {Array<Array<Array<number>>>} Holes of 2d polygon.
28735 return this._holes;
28741 * Add a vertex to the polygon by appending it after the last vertex.
28743 * @param {Array<number>} vertex - Vertex to add.
28745 PolygonGeometry.prototype.addVertex2d = function (vertex) {
28747 Math.max(0, Math.min(1, vertex[0])),
28748 Math.max(0, Math.min(1, vertex[1])),
28750 this._polygon.splice(this._polygon.length - 1, 0, clamped);
28751 this._notifyChanged$.next(this);
28754 * Get the coordinates of a vertex from the polygon representation of the geometry.
28756 * @description The first vertex represents the bottom-left corner with the rest of
28757 * the vertices following in clockwise order.
28759 * @param {number} index - Vertex index.
28760 * @returns {Array<number>} Array representing the 2D basic coordinates of the vertex.
28762 PolygonGeometry.prototype.getVertex2d = function (index) {
28763 return this._polygon[index].slice();
28766 * Remove a vertex from the polygon.
28768 * @param {number} index - The index of the vertex to remove.
28770 PolygonGeometry.prototype.removeVertex2d = function (index) {
28772 index >= this._polygon.length ||
28773 this._polygon.length < 4) {
28774 throw new Component_1.GeometryTagError("Index for removed vertex must be valid.");
28776 if (index > 0 && index < this._polygon.length - 1) {
28777 this._polygon.splice(index, 1);
28780 this._polygon.splice(0, 1);
28781 this._polygon.pop();
28782 var closing = this._polygon[0].slice();
28783 this._polygon.push(closing);
28785 this._notifyChanged$.next(this);
28788 PolygonGeometry.prototype.setVertex2d = function (index, value, transform) {
28790 Math.max(0, Math.min(1, value[0])),
28791 Math.max(0, Math.min(1, value[1])),
28793 if (index === 0 || index === this._polygon.length - 1) {
28794 this._polygon[0] = changed.slice();
28795 this._polygon[this._polygon.length - 1] = changed.slice();
28798 this._polygon[index] = changed.slice();
28800 this._notifyChanged$.next(this);
28803 PolygonGeometry.prototype.setCentroid2d = function (value, transform) {
28804 var xs = this._polygon.map(function (point) { return point[0]; });
28805 var ys = this._polygon.map(function (point) { return point[1]; });
28806 var minX = Math.min.apply(Math, xs);
28807 var maxX = Math.max.apply(Math, xs);
28808 var minY = Math.min.apply(Math, ys);
28809 var maxY = Math.max.apply(Math, ys);
28810 var centroid = this.getCentroid2d();
28811 var minTranslationX = -minX;
28812 var maxTranslationX = 1 - maxX;
28813 var minTranslationY = -minY;
28814 var maxTranslationY = 1 - maxY;
28815 var translationX = Math.max(minTranslationX, Math.min(maxTranslationX, value[0] - centroid[0]));
28816 var translationY = Math.max(minTranslationY, Math.min(maxTranslationY, value[1] - centroid[1]));
28817 for (var _i = 0, _a = this._polygon; _i < _a.length; _i++) {
28818 var point = _a[_i];
28819 point[0] += translationX;
28820 point[1] += translationY;
28822 this._notifyChanged$.next(this);
28825 PolygonGeometry.prototype.getPoints3d = function (transform) {
28826 return this.getVertices3d(transform);
28829 PolygonGeometry.prototype.getVertex3d = function (index, transform) {
28830 return transform.unprojectBasic(this._polygon[index], 200);
28833 PolygonGeometry.prototype.getVertices2d = function () {
28834 return this._polygon.slice();
28837 PolygonGeometry.prototype.getVertices3d = function (transform) {
28838 return this._polygon
28839 .map(function (point) {
28840 return transform.unprojectBasic(point, 200);
28844 * Get a polygon representation of the 3D coordinates for the vertices of each hole
28847 * @param {Transform} transform - The transform of the node related to the geometry.
28848 * @returns {Array<Array<Array<number>>>} Array of hole polygons in 3D world coordinates
28849 * representing the vertices of each hole of the geometry.
28851 PolygonGeometry.prototype.getHoleVertices3d = function (transform) {
28853 for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
28856 .map(function (point) {
28857 return transform.unprojectBasic(point, 200);
28859 holes3d.push(hole3d);
28864 PolygonGeometry.prototype.getCentroid2d = function () {
28865 var polygon = this._polygon;
28869 for (var i = 0; i < polygon.length - 1; i++) {
28870 var xi = polygon[i][0];
28871 var yi = polygon[i][1];
28872 var xi1 = polygon[i + 1][0];
28873 var yi1 = polygon[i + 1][1];
28874 var a = xi * yi1 - xi1 * yi;
28876 centroidX += (xi + xi1) * a;
28877 centroidY += (yi + yi1) * a;
28880 centroidX /= 6 * area;
28881 centroidY /= 6 * area;
28882 return [centroidX, centroidY];
28885 PolygonGeometry.prototype.getCentroid3d = function (transform) {
28886 var centroid2d = this.getCentroid2d();
28887 return transform.unprojectBasic(centroid2d, 200);
28890 PolygonGeometry.prototype.getTriangles3d = function (transform) {
28891 return this._triangulate(this._polygon, this.getPoints3d(transform), this._holes, this.getHoleVertices3d(transform));
28894 PolygonGeometry.prototype.getPoleOfAccessibility2d = function () {
28895 return this._getPoleOfInaccessibility2d(this._polygon.slice());
28898 PolygonGeometry.prototype.getPoleOfAccessibility3d = function (transform) {
28899 var pole2d = this._getPoleOfInaccessibility2d(this._polygon.slice());
28900 return transform.unprojectBasic(pole2d, 200);
28902 return PolygonGeometry;
28903 }(Component_1.VertexGeometry));
28904 exports.PolygonGeometry = PolygonGeometry;
28905 exports.default = PolygonGeometry;
28907 },{"../../../Component":226}],299:[function(require,module,exports){
28909 var __extends = (this && this.__extends) || (function () {
28910 var extendStatics = Object.setPrototypeOf ||
28911 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28912 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28913 return function (d, b) {
28914 extendStatics(d, b);
28915 function __() { this.constructor = d; }
28916 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28919 Object.defineProperty(exports, "__esModule", { value: true });
28920 var Component_1 = require("../../../Component");
28922 * @class RectGeometry
28924 * @classdesc Represents a rectangle geometry in the 2D basic image coordinate system.
28928 * var basicRect = [0.5, 0.3, 0.7, 0.4];
28929 * var rectGeometry = new Mapillary.TagComponent.RectGeometry(basicRect);
28932 var RectGeometry = (function (_super) {
28933 __extends(RectGeometry, _super);
28935 * Create a rectangle geometry.
28938 * @param {Array<number>} rect - An array representing the top-left and bottom-right
28939 * corners of the rectangle in basic coordinates. Ordered according to [x0, y0, x1, y1].
28941 * @throws {GeometryTagError} Rectangle coordinates must be valid basic coordinates.
28943 function RectGeometry(rect) {
28944 var _this = _super.call(this) || this;
28945 if (rect[1] > rect[3]) {
28946 throw new Component_1.GeometryTagError("Basic Y coordinates values can not be inverted.");
28948 for (var _i = 0, rect_1 = rect; _i < rect_1.length; _i++) {
28949 var coord = rect_1[_i];
28950 if (coord < 0 || coord > 1) {
28951 throw new Component_1.GeometryTagError("Basic coordinates must be on the interval [0, 1].");
28954 _this._rect = rect.slice(0, 4);
28955 if (_this._rect[0] > _this._rect[2]) {
28956 _this._inverted = true;
28960 Object.defineProperty(RectGeometry.prototype, "rect", {
28962 * Get rect property.
28963 * @returns {Array<number>} Array representing the top-left and bottom-right
28964 * corners of the rectangle in basic coordinates.
28973 * Set the value of a vertex in the polygon representation of the rectangle.
28975 * @description The polygon is defined to have the first vertex at the
28976 * bottom-left corner with the rest of the vertices following in clockwise order.
28978 * @param {number} index - The index of the vertex to be set.
28979 * @param {Array<number>} value - The new value of the vertex.
28980 * @param {Transform} transform - The transform of the node related to the rectangle.
28982 RectGeometry.prototype.setVertex2d = function (index, value, transform) {
28983 var original = this._rect.slice();
28985 Math.max(0, Math.min(1, value[0])),
28986 Math.max(0, Math.min(1, value[1])),
28990 rect[0] = changed[0];
28991 rect[1] = original[1];
28992 rect[2] = original[2];
28993 rect[3] = changed[1];
28995 else if (index === 1) {
28996 rect[0] = changed[0];
28997 rect[1] = changed[1];
28998 rect[2] = original[2];
28999 rect[3] = original[3];
29001 else if (index === 2) {
29002 rect[0] = original[0];
29003 rect[1] = changed[1];
29004 rect[2] = changed[0];
29005 rect[3] = original[3];
29007 else if (index === 3) {
29008 rect[0] = original[0];
29009 rect[1] = original[1];
29010 rect[2] = changed[0];
29011 rect[3] = changed[1];
29013 if (transform.gpano) {
29014 var passingBoundaryLeft = index < 2 && changed[0] > 0.75 && original[0] < 0.25 ||
29015 index >= 2 && this._inverted && changed[0] > 0.75 && original[2] < 0.25;
29016 var passingBoundaryRight = index < 2 && this._inverted && changed[0] < 0.25 && original[0] > 0.75 ||
29017 index >= 2 && changed[0] < 0.25 && original[2] > 0.75;
29018 if (passingBoundaryLeft || passingBoundaryRight) {
29019 this._inverted = !this._inverted;
29022 if (rect[0] - original[0] < -0.25) {
29023 rect[0] = original[0];
29025 if (rect[2] - original[2] > 0.25) {
29026 rect[2] = original[2];
29029 if (!this._inverted && rect[0] > rect[2] ||
29030 this._inverted && rect[0] < rect[2]) {
29031 rect[0] = original[0];
29032 rect[2] = original[2];
29036 if (rect[0] > rect[2]) {
29037 rect[0] = original[0];
29038 rect[2] = original[2];
29041 if (rect[1] > rect[3]) {
29042 rect[1] = original[1];
29043 rect[3] = original[3];
29045 this._rect[0] = rect[0];
29046 this._rect[1] = rect[1];
29047 this._rect[2] = rect[2];
29048 this._rect[3] = rect[3];
29049 this._notifyChanged$.next(this);
29052 RectGeometry.prototype.setCentroid2d = function (value, transform) {
29053 var original = this._rect.slice();
29054 var x0 = original[0];
29055 var x1 = this._inverted ? original[2] + 1 : original[2];
29056 var y0 = original[1];
29057 var y1 = original[3];
29058 var centerX = x0 + (x1 - x0) / 2;
29059 var centerY = y0 + (y1 - y0) / 2;
29060 var translationX = 0;
29061 if (transform.gpano != null &&
29062 transform.gpano.CroppedAreaImageWidthPixels === transform.gpano.FullPanoWidthPixels) {
29063 translationX = this._inverted ? value[0] + 1 - centerX : value[0] - centerX;
29066 var minTranslationX = -x0;
29067 var maxTranslationX = 1 - x1;
29068 translationX = Math.max(minTranslationX, Math.min(maxTranslationX, value[0] - centerX));
29070 var minTranslationY = -y0;
29071 var maxTranslationY = 1 - y1;
29072 var translationY = Math.max(minTranslationY, Math.min(maxTranslationY, value[1] - centerY));
29073 this._rect[0] = original[0] + translationX;
29074 this._rect[1] = original[1] + translationY;
29075 this._rect[2] = original[2] + translationX;
29076 this._rect[3] = original[3] + translationY;
29077 if (this._rect[0] < 0) {
29078 this._rect[0] += 1;
29079 this._inverted = !this._inverted;
29081 else if (this._rect[0] > 1) {
29082 this._rect[0] -= 1;
29083 this._inverted = !this._inverted;
29085 if (this._rect[2] < 0) {
29086 this._rect[2] += 1;
29087 this._inverted = !this._inverted;
29089 else if (this._rect[2] > 1) {
29090 this._rect[2] -= 1;
29091 this._inverted = !this._inverted;
29093 this._notifyChanged$.next(this);
29096 * Get the 3D coordinates for the vertices of the rectangle with
29097 * interpolated points along the lines.
29099 * @param {Transform} transform - The transform of the node related to
29101 * @returns {Array<Array<number>>} Polygon array of 3D world coordinates
29102 * representing the rectangle.
29104 RectGeometry.prototype.getPoints3d = function (transform) {
29105 return this._getPoints2d(transform)
29106 .map(function (point) {
29107 return transform.unprojectBasic(point, 200);
29111 * Get the coordinates of a vertex from the polygon representation of the geometry.
29113 * @description The first vertex represents the bottom-left corner with the rest of
29114 * the vertices following in clockwise order.
29116 * @param {number} index - Vertex index.
29117 * @returns {Array<number>} Array representing the 2D basic coordinates of the vertex.
29119 RectGeometry.prototype.getVertex2d = function (index) {
29120 return this._rectToVertices2d(this._rect)[index];
29123 * Get a vertex from the polygon representation of the 3D coordinates for the
29124 * vertices of the geometry.
29126 * @description The first vertex represents the bottom-left corner with the rest of
29127 * the vertices following in clockwise order.
29129 * @param {number} index - Vertex index.
29130 * @param {Transform} transform - The transform of the node related to the geometry.
29131 * @returns {Array<Array<number>>} Polygon array of 3D world coordinates representing
29132 * the vertices of the geometry.
29134 RectGeometry.prototype.getVertex3d = function (index, transform) {
29135 return transform.unprojectBasic(this._rectToVertices2d(this._rect)[index], 200);
29138 * Get a polygon representation of the 2D basic coordinates for the vertices of the rectangle.
29140 * @description The first vertex represents the bottom-left corner with the rest of
29141 * the vertices following in clockwise order.
29143 * @returns {Array<Array<number>>} Polygon array of 2D basic coordinates representing
29144 * the rectangle vertices.
29146 RectGeometry.prototype.getVertices2d = function () {
29147 return this._rectToVertices2d(this._rect);
29150 * Get a polygon representation of the 3D coordinates for the vertices of the rectangle.
29152 * @description The first vertex represents the bottom-left corner with the rest of
29153 * the vertices following in clockwise order.
29155 * @param {Transform} transform - The transform of the node related to the rectangle.
29156 * @returns {Array<Array<number>>} Polygon array of 3D world coordinates representing
29157 * the rectangle vertices.
29159 RectGeometry.prototype.getVertices3d = function (transform) {
29160 return this._rectToVertices2d(this._rect)
29161 .map(function (vertex) {
29162 return transform.unprojectBasic(vertex, 200);
29166 RectGeometry.prototype.getCentroid2d = function () {
29167 var rect = this._rect;
29169 var x1 = this._inverted ? rect[2] + 1 : rect[2];
29172 var centroidX = x0 + (x1 - x0) / 2;
29173 var centroidY = y0 + (y1 - y0) / 2;
29174 return [centroidX, centroidY];
29177 RectGeometry.prototype.getCentroid3d = function (transform) {
29178 var centroid2d = this.getCentroid2d();
29179 return transform.unprojectBasic(centroid2d, 200);
29182 RectGeometry.prototype.getPoleOfAccessibility2d = function () {
29183 return this._getPoleOfInaccessibility2d(this._rectToVertices2d(this._rect));
29186 RectGeometry.prototype.getPoleOfAccessibility3d = function (transform) {
29187 var pole2d = this._getPoleOfInaccessibility2d(this._rectToVertices2d(this._rect));
29188 return transform.unprojectBasic(pole2d, 200);
29191 RectGeometry.prototype.getTriangles3d = function (transform) {
29192 return this._triangulate(this._rectToVertices2d(this._rect), this.getVertices3d(transform));
29195 * Check if a particular bottom-right value is valid according to the current
29196 * rectangle coordinates.
29198 * @param {Array<number>} bottomRight - The bottom-right coordinates to validate
29199 * @returns {boolean} Value indicating whether the provided bottom-right coordinates
29202 RectGeometry.prototype.validate = function (bottomRight) {
29203 var rect = this._rect;
29204 if (!this._inverted && bottomRight[0] < rect[0] ||
29205 bottomRight[0] - rect[2] > 0.25 ||
29206 bottomRight[1] < rect[1]) {
29212 * Get the 2D coordinates for the vertices of the rectangle with
29213 * interpolated points along the lines.
29215 * @param {Transform} transform - The transform of the node related to
29217 * @returns {Array<Array<number>>} Polygon array of 2D basic coordinates
29218 * representing the rectangle.
29220 RectGeometry.prototype._getPoints2d = function (transform) {
29221 var vertices2d = this._rectToVertices2d(this._rect);
29222 var sides = vertices2d.length - 1;
29225 for (var i = 0; i < sides; ++i) {
29226 var startX = vertices2d[i][0];
29227 var startY = vertices2d[i][1];
29228 var endX = vertices2d[i + 1][0];
29229 var endY = vertices2d[i + 1][1];
29230 var intervalX = (endX - startX) / (sections - 1);
29231 var intervalY = (endY - startY) / (sections - 1);
29232 for (var j = 0; j < sections; ++j) {
29234 startX + j * intervalX,
29235 startY + j * intervalY,
29237 points2d.push(point);
29243 * Convert the top-left, bottom-right representation of a rectangle to a polygon
29244 * representation of the vertices starting at the bottom-right corner going
29247 * @param {Array<number>} rect - Top-left, bottom-right representation of a
29249 * @returns {Array<Array<number>>} Polygon representation of the vertices of the
29252 RectGeometry.prototype._rectToVertices2d = function (rect) {
29254 [rect[0], rect[3]],
29255 [rect[0], rect[1]],
29256 [this._inverted ? rect[2] + 1 : rect[2], rect[1]],
29257 [this._inverted ? rect[2] + 1 : rect[2], rect[3]],
29258 [rect[0], rect[3]],
29261 return RectGeometry;
29262 }(Component_1.VertexGeometry));
29263 exports.RectGeometry = RectGeometry;
29264 exports.default = RectGeometry;
29266 },{"../../../Component":226}],300:[function(require,module,exports){
29268 /// <reference path="../../../../typings/index.d.ts" />
29269 var __extends = (this && this.__extends) || (function () {
29270 var extendStatics = Object.setPrototypeOf ||
29271 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
29272 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
29273 return function (d, b) {
29274 extendStatics(d, b);
29275 function __() { this.constructor = d; }
29276 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
29279 Object.defineProperty(exports, "__esModule", { value: true });
29280 var earcut = require("earcut");
29281 var polylabel = require("@mapbox/polylabel");
29282 var Component_1 = require("../../../Component");
29284 * @class VertexGeometry
29286 * @classdesc Represents a vertex geometry.
29288 var VertexGeometry = (function (_super) {
29289 __extends(VertexGeometry, _super);
29291 * Create a vertex geometry.
29295 function VertexGeometry() {
29296 return _super.call(this) || this;
29299 * Finds the polygon pole of inaccessibility, the most distant internal
29300 * point from the polygon outline.
29302 * @param {Array<Array<number>>} points2d - 2d points of outline to triangulate.
29303 * @returns {Array<number>} Point of inaccessibility.
29306 VertexGeometry.prototype._getPoleOfInaccessibility2d = function (points2d) {
29307 var pole2d = polylabel([points2d], 3e-2);
29311 * Triangulates a 2d polygon and returns the triangle
29312 * representation as a flattened array of 3d points.
29314 * @param {Array<Array<number>>} points2d - 2d points of outline to triangulate.
29315 * @param {Array<Array<number>>} points3d - 3d points of outline corresponding to the 2d points.
29316 * @param {Array<Array<Array<number>>>} [holes2d] - 2d points of holes to triangulate.
29317 * @param {Array<Array<Array<number>>>} [holes3d] - 3d points of holes corresponding to the 2d points.
29318 * @returns {Array<number>} Flattened array of 3d points ordered based on the triangles.
29321 VertexGeometry.prototype._triangulate = function (points2d, points3d, holes2d, holes3d) {
29322 var data = [points2d.slice(0, -1)];
29323 for (var _i = 0, _a = holes2d != null ? holes2d : []; _i < _a.length; _i++) {
29324 var hole2d = _a[_i];
29325 data.push(hole2d.slice(0, -1));
29327 var points = points3d.slice(0, -1);
29328 for (var _b = 0, _c = holes3d != null ? holes3d : []; _b < _c.length; _b++) {
29329 var hole3d = _c[_b];
29330 points = points.concat(hole3d.slice(0, -1));
29332 var flattened = earcut.flatten(data);
29333 var indices = earcut(flattened.vertices, flattened.holes, flattened.dimensions);
29334 var triangles = [];
29335 for (var i = 0; i < indices.length; ++i) {
29336 var point = points[indices[i]];
29337 triangles.push(point[0]);
29338 triangles.push(point[1]);
29339 triangles.push(point[2]);
29343 return VertexGeometry;
29344 }(Component_1.Geometry));
29345 exports.VertexGeometry = VertexGeometry;
29346 exports.default = VertexGeometry;
29348 },{"../../../Component":226,"@mapbox/polylabel":1,"earcut":8}],301:[function(require,module,exports){
29350 /// <reference path="../../../../typings/index.d.ts" />
29351 Object.defineProperty(exports, "__esModule", { value: true });
29352 var THREE = require("three");
29353 var vd = require("virtual-dom");
29354 var Subject_1 = require("rxjs/Subject");
29355 var Component_1 = require("../../../Component");
29356 var Geo_1 = require("../../../Geo");
29357 var OutlineCreateTag = (function () {
29358 function OutlineCreateTag(geometry, options, transform, viewportCoords) {
29360 this._geometry = geometry;
29361 this._options = { color: options.color == null ? 0xFFFFFF : options.color };
29362 this._transform = transform;
29363 this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
29364 this._outline = this._createOutine();
29365 this._glObjects = [this._outline];
29366 this._aborted$ = new Subject_1.Subject();
29367 this._created$ = new Subject_1.Subject();
29368 this._glObjectsChanged$ = new Subject_1.Subject();
29369 this._geometryChangedSubscription = this._geometry.changed$
29370 .subscribe(function (vertexGeometry) {
29371 _this._disposeOutline();
29372 _this._outline = _this._createOutine();
29373 _this._glObjects = [_this._outline];
29374 _this._glObjectsChanged$.next(_this);
29377 Object.defineProperty(OutlineCreateTag.prototype, "geometry", {
29379 return this._geometry;
29384 Object.defineProperty(OutlineCreateTag.prototype, "glObjects", {
29386 return this._glObjects;
29391 Object.defineProperty(OutlineCreateTag.prototype, "aborted$", {
29393 return this._aborted$;
29398 Object.defineProperty(OutlineCreateTag.prototype, "created$", {
29400 return this._created$;
29405 Object.defineProperty(OutlineCreateTag.prototype, "glObjectsChanged$", {
29407 return this._glObjectsChanged$;
29412 Object.defineProperty(OutlineCreateTag.prototype, "geometryChanged$", {
29415 return this._geometry.changed$
29416 .map(function (geometry) {
29423 OutlineCreateTag.prototype.dispose = function () {
29424 this._disposeOutline();
29425 this._geometryChangedSubscription.unsubscribe();
29427 OutlineCreateTag.prototype.getDOMObjects = function (camera, size) {
29431 offsetHeight: size.height, offsetWidth: size.width,
29433 var abort = function (e) {
29434 e.stopPropagation();
29435 _this._aborted$.next(_this);
29437 if (this._geometry instanceof Component_1.RectGeometry) {
29438 var _a = this._geometry.getVertex2d(1), basicX = _a[0], basicY = _a[1];
29439 var canvasPoint = this._viewportCoords.basicToCanvasSafe(basicX, basicY, container, this._transform, camera);
29440 if (canvasPoint != null) {
29441 var background = this._colorToBackground(this._options.color);
29442 var transform = this._canvasToTransform(canvasPoint);
29443 var pointProperties = {
29444 style: { background: background, transform: transform },
29446 var completerProperties = {
29448 style: { transform: transform },
29450 vNodes.push(vd.h("div.TagInteractor", completerProperties, []));
29451 vNodes.push(vd.h("div.TagVertex", pointProperties, []));
29454 else if (this._geometry instanceof Component_1.PolygonGeometry) {
29455 var polygonGeometry_1 = this._geometry;
29456 var _b = polygonGeometry_1.getVertex2d(0), firstVertexBasicX = _b[0], firstVertexBasicY = _b[1];
29457 var firstVertexCanvas = this._viewportCoords.basicToCanvasSafe(firstVertexBasicX, firstVertexBasicY, container, this._transform, camera);
29458 if (firstVertexCanvas != null) {
29459 var firstOnclick = polygonGeometry_1.polygon.length > 4 ?
29461 e.stopPropagation();
29462 polygonGeometry_1.removeVertex2d(polygonGeometry_1.polygon.length - 2);
29463 _this._created$.next(_this);
29466 var transform = this._canvasToTransform(firstVertexCanvas);
29467 var completerProperties = {
29468 onclick: firstOnclick,
29469 style: { transform: transform },
29471 var firstClass = polygonGeometry_1.polygon.length > 4 ?
29474 vNodes.push(vd.h("div." + firstClass, completerProperties, []));
29476 if (polygonGeometry_1.polygon.length > 3) {
29477 var _c = polygonGeometry_1.getVertex2d(polygonGeometry_1.polygon.length - 3), lastVertexBasicX = _c[0], lastVertexBasicY = _c[1];
29478 var lastVertexCanvas = this._viewportCoords.basicToCanvasSafe(lastVertexBasicX, lastVertexBasicY, container, this._transform, camera);
29479 if (lastVertexCanvas != null) {
29480 var remove = function (e) {
29481 e.stopPropagation();
29482 polygonGeometry_1.removeVertex2d(polygonGeometry_1.polygon.length - 3);
29484 var transform = this._canvasToTransform(lastVertexCanvas);
29485 var completerProperties = {
29487 style: { transform: transform },
29489 vNodes.push(vd.h("div.TagInteractor", completerProperties, []));
29492 var verticesBasic = polygonGeometry_1.polygon.slice();
29493 verticesBasic.splice(-2, 2);
29494 for (var _i = 0, verticesBasic_1 = verticesBasic; _i < verticesBasic_1.length; _i++) {
29495 var vertexBasic = verticesBasic_1[_i];
29496 var vertexCanvas = this._viewportCoords.basicToCanvasSafe(vertexBasic[0], vertexBasic[1], container, this._transform, camera);
29497 if (vertexCanvas != null) {
29498 var background = this._colorToBackground(this._options.color);
29499 var transform = this._canvasToTransform(vertexCanvas);
29500 var pointProperties = {
29502 background: background,
29503 transform: transform,
29506 vNodes.push(vd.h("div.TagVertex", pointProperties, []));
29512 OutlineCreateTag.prototype.addPoint = function (point) {
29513 if (this._geometry instanceof Component_1.RectGeometry) {
29514 var rectGeometry = this._geometry;
29515 if (!rectGeometry.validate(point)) {
29518 this._created$.next(this);
29520 else if (this._geometry instanceof Component_1.PolygonGeometry) {
29521 var polygonGeometry = this._geometry;
29522 polygonGeometry.addVertex2d(point);
29525 OutlineCreateTag.prototype._canvasToTransform = function (canvas) {
29526 var canvasX = Math.round(canvas[0]);
29527 var canvasY = Math.round(canvas[1]);
29528 var transform = "translate(-50%,-50%) translate(" + canvasX + "px," + canvasY + "px)";
29531 OutlineCreateTag.prototype._colorToBackground = function (color) {
29532 return "#" + ("000000" + color.toString(16)).substr(-6);
29534 OutlineCreateTag.prototype._createOutine = function () {
29535 var polygon3d = this._geometry.getPoints3d(this._transform);
29536 var positions = this._getLinePositions(polygon3d);
29537 var geometry = new THREE.BufferGeometry();
29538 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
29539 var material = new THREE.LineBasicMaterial({
29540 color: this._options.color,
29543 return new THREE.Line(geometry, material);
29545 OutlineCreateTag.prototype._disposeOutline = function () {
29546 if (this._outline == null) {
29549 var line = this._outline;
29550 line.geometry.dispose();
29551 line.material.dispose();
29552 this._outline = null;
29553 this._glObjects = [];
29555 OutlineCreateTag.prototype._getLinePositions = function (polygon3d) {
29556 var length = polygon3d.length;
29557 var positions = new Float32Array(length * 3);
29558 for (var i = 0; i < length; ++i) {
29560 var position = polygon3d[i];
29561 positions[index] = position[0];
29562 positions[index + 1] = position[1];
29563 positions[index + 2] = position[2];
29567 return OutlineCreateTag;
29569 exports.OutlineCreateTag = OutlineCreateTag;
29570 exports.default = OutlineCreateTag;
29572 },{"../../../Component":226,"../../../Geo":229,"rxjs/Subject":34,"three":176,"virtual-dom":182}],302:[function(require,module,exports){
29574 /// <reference path="../../../../typings/index.d.ts" />
29575 var __extends = (this && this.__extends) || (function () {
29576 var extendStatics = Object.setPrototypeOf ||
29577 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
29578 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
29579 return function (d, b) {
29580 extendStatics(d, b);
29581 function __() { this.constructor = d; }
29582 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
29585 Object.defineProperty(exports, "__esModule", { value: true });
29586 var THREE = require("three");
29587 var vd = require("virtual-dom");
29588 var Component_1 = require("../../../Component");
29590 * @class OutlineRenderTag
29591 * @classdesc Tag visualizing the properties of an OutlineTag.
29593 var OutlineRenderTag = (function (_super) {
29594 __extends(OutlineRenderTag, _super);
29595 function OutlineRenderTag(tag, transform) {
29596 var _this = _super.call(this, tag, transform) || this;
29597 _this._fill = !transform.gpano ?
29598 _this._createFill() :
29600 _this._holes = _this._tag.lineWidth >= 1 ?
29601 _this._createHoles() :
29603 _this._outline = _this._tag.lineWidth >= 1 ?
29604 _this._createOutline() :
29606 _this._geometryChangedSubscription = _this._tag.geometry.changed$
29607 .subscribe(function (geometry) {
29608 if (_this._fill != null) {
29609 _this._updateFillGeometry();
29611 if (_this._holes.length > 0) {
29612 _this._updateHoleGeometries();
29614 if (_this._outline != null) {
29615 _this._updateOulineGeometry();
29618 _this._changedSubscription = _this._tag.changed$
29619 .subscribe(function (changedTag) {
29620 var glObjectsChanged = false;
29621 if (_this._fill != null) {
29622 _this._updateFillMaterial(_this._fill.material);
29624 if (_this._outline == null) {
29625 if (_this._tag.lineWidth >= 1) {
29626 _this._holes = _this._createHoles();
29627 _this._outline = _this._createOutline();
29628 glObjectsChanged = true;
29632 _this._updateHoleMaterials();
29633 _this._updateOutlineMaterial();
29635 if (glObjectsChanged) {
29636 _this._glObjectsChanged$.next(_this);
29641 OutlineRenderTag.prototype.dispose = function () {
29642 this._disposeFill();
29643 this._disposeHoles();
29644 this._disposeOutline();
29645 this._changedSubscription.unsubscribe();
29646 this._geometryChangedSubscription.unsubscribe();
29648 OutlineRenderTag.prototype.getDOMObjects = function (atlas, camera, size) {
29651 var isRect = this._tag.geometry instanceof Component_1.RectGeometry;
29652 var isPerspective = !this._transform.gpano;
29654 offsetHeight: size.height, offsetWidth: size.width,
29656 if (this._tag.icon != null && (isRect || isPerspective)) {
29657 var _a = this._tag.geometry instanceof Component_1.RectGeometry ?
29658 this._tag.geometry.getVertex2d(this._tag.iconIndex) :
29659 this._tag.geometry.getPoleOfAccessibility2d(), iconBasicX = _a[0], iconBasicY = _a[1];
29660 var iconCanvas = this._viewportCoords.basicToCanvasSafe(iconBasicX, iconBasicY, container, this._transform, camera);
29661 if (iconCanvas != null) {
29662 var interact = function (e) {
29663 _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
29665 if (atlas.loaded) {
29666 var sprite = atlas.getDOMSprite(this._tag.icon, this._tag.iconFloat);
29667 var iconCanvasX = Math.round(iconCanvas[0]);
29668 var iconCanvasY = Math.round(iconCanvas[1]);
29669 var transform = "translate(" + iconCanvasX + "px," + iconCanvasY + "px)";
29670 var click = function (e) {
29671 e.stopPropagation();
29672 _this._tag.click$.next(_this._tag);
29676 onmousedown: interact,
29677 style: { transform: transform },
29679 vNodes.push(vd.h("div.TagSymbol", properties, [sprite]));
29683 else if (this._tag.text != null && (isRect || isPerspective)) {
29684 var _b = this._tag.geometry instanceof Component_1.RectGeometry ?
29685 this._tag.geometry.getVertex2d(3) :
29686 this._tag.geometry.getPoleOfAccessibility2d(), textBasicX = _b[0], textBasicY = _b[1];
29687 var textCanvas = this._viewportCoords.basicToCanvasSafe(textBasicX, textBasicY, container, this._transform, camera);
29688 if (textCanvas != null) {
29689 var textCanvasX = Math.round(textCanvas[0]);
29690 var textCanvasY = Math.round(textCanvas[1]);
29691 var transform = this._tag.geometry instanceof Component_1.RectGeometry ?
29692 "translate(" + textCanvasX + "px," + textCanvasY + "px)" :
29693 "translate(-50%, -50%) translate(" + textCanvasX + "px," + textCanvasY + "px)";
29694 var interact = function (e) {
29695 _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
29698 onmousedown: interact,
29700 color: this._colorToCss(this._tag.textColor),
29701 transform: transform,
29703 textContent: this._tag.text,
29705 vNodes.push(vd.h("span.TagSymbol", properties, []));
29708 if (!this._tag.editable) {
29711 var lineColor = this._colorToCss(this._tag.lineColor);
29712 if (this._tag.geometry instanceof Component_1.RectGeometry) {
29713 var _c = this._tag.geometry.getCentroid2d(), centroidBasicX = _c[0], centroidBasicY = _c[1];
29714 var centroidCanvas = this._viewportCoords.basicToCanvasSafe(centroidBasicX, centroidBasicY, container, this._transform, camera);
29715 if (centroidCanvas != null) {
29716 var interact = this._interact(Component_1.TagOperation.Centroid);
29717 var centroidCanvasX = Math.round(centroidCanvas[0]);
29718 var centroidCanvasY = Math.round(centroidCanvas[1]);
29719 var transform = "translate(-50%, -50%) translate(" + centroidCanvasX + "px," + centroidCanvasY + "px)";
29721 onmousedown: interact,
29722 style: { background: lineColor, transform: transform },
29724 vNodes.push(vd.h("div.TagMover", properties, []));
29727 var vertices2d = this._tag.geometry.getVertices2d();
29728 for (var i = 0; i < vertices2d.length - 1; i++) {
29730 ((this._tag.icon != null && i === this._tag.iconIndex) ||
29731 (this._tag.icon == null && this._tag.text != null && i === 3))) {
29734 var _d = vertices2d[i], vertexBasicX = _d[0], vertexBasicY = _d[1];
29735 var vertexCanvas = this._viewportCoords.basicToCanvasSafe(vertexBasicX, vertexBasicY, container, this._transform, camera);
29736 if (vertexCanvas == null) {
29739 var interact = this._interact(Component_1.TagOperation.Vertex, i);
29740 var vertexCanvasX = Math.round(vertexCanvas[0]);
29741 var vertexCanvasY = Math.round(vertexCanvas[1]);
29742 var transform = "translate(-50%, -50%) translate(" + vertexCanvasX + "px," + vertexCanvasY + "px)";
29744 onmousedown: interact,
29745 style: { background: lineColor, transform: transform },
29748 properties.style.cursor = i % 2 === 0 ? "nesw-resize" : "nwse-resize";
29750 vNodes.push(vd.h("div.TagResizer", properties, []));
29751 if (!this._tag.indicateVertices) {
29754 var pointProperties = {
29755 style: { background: lineColor, transform: transform },
29757 vNodes.push(vd.h("div.TagVertex", pointProperties, []));
29761 OutlineRenderTag.prototype.getGLObjects = function () {
29762 var glObjects = [];
29763 if (this._fill != null) {
29764 glObjects.push(this._fill);
29766 for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
29768 glObjects.push(hole);
29770 if (this._outline != null) {
29771 glObjects.push(this._outline);
29775 OutlineRenderTag.prototype.getRetrievableObjects = function () {
29776 return this._fill != null ? [this._fill] : [];
29778 OutlineRenderTag.prototype._colorToCss = function (color) {
29779 return "#" + ("000000" + color.toString(16)).substr(-6);
29781 OutlineRenderTag.prototype._createFill = function () {
29782 var triangles = this._tag.geometry.getTriangles3d(this._transform);
29783 var positions = new Float32Array(triangles);
29784 var geometry = new THREE.BufferGeometry();
29785 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
29786 geometry.computeBoundingSphere();
29787 var material = new THREE.MeshBasicMaterial({ side: THREE.DoubleSide, transparent: true });
29788 this._updateFillMaterial(material);
29789 return new THREE.Mesh(geometry, material);
29791 OutlineRenderTag.prototype._createHoles = function () {
29793 if (this._tag.geometry instanceof Component_1.PolygonGeometry) {
29794 var polygonGeometry = this._tag.geometry;
29795 var holes3d = polygonGeometry.getHoleVertices3d(this._transform);
29796 for (var _i = 0, holes3d_1 = holes3d; _i < holes3d_1.length; _i++) {
29797 var holePoints3d = holes3d_1[_i];
29798 var hole = this._createLine(holePoints3d);
29804 OutlineRenderTag.prototype._createLine = function (points3d) {
29805 var positions = this._getLinePositions(points3d);
29806 var geometry = new THREE.BufferGeometry();
29807 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
29808 geometry.computeBoundingSphere();
29809 var material = new THREE.LineBasicMaterial();
29810 this._updateLineBasicMaterial(material);
29811 var line = new THREE.Line(geometry, material);
29812 line.renderOrder = 1;
29815 OutlineRenderTag.prototype._createOutline = function () {
29816 var points3d = this._tag.geometry.getPoints3d(this._transform);
29817 return this._createLine(points3d);
29819 OutlineRenderTag.prototype._disposeFill = function () {
29820 if (this._fill == null) {
29823 this._fill.geometry.dispose();
29824 this._fill.material.dispose();
29827 OutlineRenderTag.prototype._disposeHoles = function () {
29828 for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
29830 hole.geometry.dispose();
29831 hole.material.dispose();
29835 OutlineRenderTag.prototype._disposeOutline = function () {
29836 if (this._outline == null) {
29839 this._outline.geometry.dispose();
29840 this._outline.material.dispose();
29841 this._outline = null;
29843 OutlineRenderTag.prototype._getLinePositions = function (points3d) {
29844 var length = points3d.length;
29845 var positions = new Float32Array(length * 3);
29846 for (var i = 0; i < length; ++i) {
29848 var position = points3d[i];
29849 positions[index + 0] = position[0];
29850 positions[index + 1] = position[1];
29851 positions[index + 2] = position[2];
29855 OutlineRenderTag.prototype._interact = function (operation, vertexIndex) {
29857 return function (e) {
29858 var offsetX = e.offsetX - e.target.offsetWidth / 2;
29859 var offsetY = e.offsetY - e.target.offsetHeight / 2;
29860 _this._interact$.next({
29863 operation: operation,
29865 vertexIndex: vertexIndex,
29869 OutlineRenderTag.prototype._updateFillGeometry = function () {
29870 var triangles = this._tag.geometry.getTriangles3d(this._transform);
29871 var positions = new Float32Array(triangles);
29872 var geometry = this._fill.geometry;
29873 var attribute = geometry.getAttribute("position");
29874 if (attribute.array.length === positions.length) {
29875 attribute.set(positions);
29876 attribute.needsUpdate = true;
29879 geometry.removeAttribute("position");
29880 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
29882 geometry.computeBoundingSphere();
29884 OutlineRenderTag.prototype._updateFillMaterial = function (material) {
29885 material.color = new THREE.Color(this._tag.fillColor);
29886 material.opacity = this._tag.fillOpacity;
29887 material.needsUpdate = true;
29889 OutlineRenderTag.prototype._updateHoleGeometries = function () {
29890 var polygonGeometry = this._tag.geometry;
29891 var holes3d = polygonGeometry.getHoleVertices3d(this._transform);
29892 if (holes3d.length !== this._holes.length) {
29893 throw new Error("Changing the number of holes is not supported.");
29895 for (var i = 0; i < this._holes.length; i++) {
29896 var holePoints3d = holes3d[i];
29897 var hole = this._holes[i];
29898 this._updateLine(hole, holePoints3d);
29901 OutlineRenderTag.prototype._updateHoleMaterials = function () {
29902 for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
29904 var material = hole.material;
29905 this._updateLineBasicMaterial(material);
29908 OutlineRenderTag.prototype._updateLine = function (line, points3d) {
29909 var positions = this._getLinePositions(points3d);
29910 var geometry = line.geometry;
29911 var attribute = geometry.getAttribute("position");
29912 attribute.set(positions);
29913 attribute.needsUpdate = true;
29914 geometry.computeBoundingSphere();
29916 OutlineRenderTag.prototype._updateOulineGeometry = function () {
29917 var points3d = this._tag.geometry.getPoints3d(this._transform);
29918 this._updateLine(this._outline, points3d);
29920 OutlineRenderTag.prototype._updateOutlineMaterial = function () {
29921 var material = this._outline.material;
29922 this._updateLineBasicMaterial(material);
29924 OutlineRenderTag.prototype._updateLineBasicMaterial = function (material) {
29925 material.color = new THREE.Color(this._tag.lineColor);
29926 material.linewidth = Math.max(this._tag.lineWidth, 1);
29927 material.visible = this._tag.lineWidth >= 1 && this._tag.lineOpacity > 0;
29928 material.opacity = this._tag.lineOpacity;
29929 material.transparent = this._tag.lineOpacity < 1;
29930 material.needsUpdate = true;
29932 return OutlineRenderTag;
29933 }(Component_1.RenderTag));
29934 exports.OutlineRenderTag = OutlineRenderTag;
29936 },{"../../../Component":226,"three":176,"virtual-dom":182}],303:[function(require,module,exports){
29938 var __extends = (this && this.__extends) || (function () {
29939 var extendStatics = Object.setPrototypeOf ||
29940 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
29941 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
29942 return function (d, b) {
29943 extendStatics(d, b);
29944 function __() { this.constructor = d; }
29945 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
29948 Object.defineProperty(exports, "__esModule", { value: true });
29949 var Subject_1 = require("rxjs/Subject");
29950 var Component_1 = require("../../../Component");
29951 var Viewer_1 = require("../../../Viewer");
29953 * @class OutlineTag
29955 * @classdesc Tag holding properties for visualizing a geometry outline.
29959 * var geometry = new Mapillary.TagComponent.RectGeometry([0.3, 0.3, 0.5, 0.4]);
29960 * var tag = new Mapillary.TagComponent.OutlineTag(
29963 * { editable: true, lineColor: 0xff0000 });
29965 * tagComponent.add([tag]);
29968 var OutlineTag = (function (_super) {
29969 __extends(OutlineTag, _super);
29971 * Create an outline tag.
29975 * @param {string} id - Unique identifier of the tag.
29976 * @param {VertexGeometry} geometry - Geometry defining vertices of tag.
29977 * @param {IOutlineTagOptions} options - Options defining the visual appearance and
29978 * behavior of the outline tag.
29980 function OutlineTag(id, geometry, options) {
29981 var _this = _super.call(this, id, geometry) || this;
29982 options = !!options ? options : {};
29983 _this._editable = options.editable == null ? false : options.editable;
29984 _this._fillColor = options.fillColor == null ? 0xFFFFFF : options.fillColor;
29985 _this._fillOpacity = options.fillOpacity == null ? 0.0 : options.fillOpacity;
29986 _this._icon = options.icon === undefined ? null : options.icon;
29987 _this._iconFloat = options.iconFloat == null ? Viewer_1.Alignment.Center : options.iconFloat;
29988 _this._iconIndex = options.iconIndex == null ? 3 : options.iconIndex;
29989 _this._indicateVertices = options.indicateVertices == null ? true : options.indicateVertices;
29990 _this._lineColor = options.lineColor == null ? 0xFFFFFF : options.lineColor;
29991 _this._lineOpacity = options.lineOpacity == null ? 1 : options.lineOpacity;
29992 _this._lineWidth = options.lineWidth == null ? 1 : options.lineWidth;
29993 _this._text = options.text === undefined ? null : options.text;
29994 _this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor;
29995 _this._click$ = new Subject_1.Subject();
29997 .subscribe(function (t) {
29998 _this.fire(OutlineTag.click, _this);
30002 Object.defineProperty(OutlineTag.prototype, "click$", {
30004 * Click observable.
30006 * @description An observable emitting the tag when the icon of the
30007 * tag has been clicked.
30009 * @returns {Observable<Tag>}
30012 return this._click$;
30017 Object.defineProperty(OutlineTag.prototype, "editable", {
30019 * Get editable property.
30020 * @returns {boolean} Value indicating if tag is editable.
30023 return this._editable;
30026 * Set editable property.
30029 * @fires Tag#changed
30031 set: function (value) {
30032 this._editable = value;
30033 this._notifyChanged$.next(this);
30038 Object.defineProperty(OutlineTag.prototype, "fillColor", {
30040 * Get fill color property.
30041 * @returns {number}
30044 return this._fillColor;
30047 * Set fill color property.
30050 * @fires Tag#changed
30052 set: function (value) {
30053 this._fillColor = value;
30054 this._notifyChanged$.next(this);
30059 Object.defineProperty(OutlineTag.prototype, "fillOpacity", {
30061 * Get fill opacity property.
30062 * @returns {number}
30065 return this._fillOpacity;
30068 * Set fill opacity property.
30071 * @fires Tag#changed
30073 set: function (value) {
30074 this._fillOpacity = value;
30075 this._notifyChanged$.next(this);
30080 Object.defineProperty(OutlineTag.prototype, "geometry", {
30083 return this._geometry;
30088 Object.defineProperty(OutlineTag.prototype, "icon", {
30090 * Get icon property.
30091 * @returns {string}
30097 * Set icon property.
30100 * @fires Tag#changed
30102 set: function (value) {
30103 this._icon = value;
30104 this._notifyChanged$.next(this);
30109 Object.defineProperty(OutlineTag.prototype, "iconFloat", {
30111 * Get icon float property.
30112 * @returns {Alignment}
30115 return this._iconFloat;
30118 * Set icon float property.
30119 * @param {Alignment}
30121 * @fires Tag#changed
30123 set: function (value) {
30124 this._iconFloat = value;
30125 this._notifyChanged$.next(this);
30130 Object.defineProperty(OutlineTag.prototype, "iconIndex", {
30132 * Get icon index property.
30133 * @returns {number}
30136 return this._iconIndex;
30139 * Set icon index property.
30142 * @fires Tag#changed
30144 set: function (value) {
30145 this._iconIndex = value;
30146 this._notifyChanged$.next(this);
30151 Object.defineProperty(OutlineTag.prototype, "indicateVertices", {
30153 * Get indicate vertices property.
30154 * @returns {boolean} Value indicating if vertices should be indicated
30155 * when tag is editable.
30158 return this._indicateVertices;
30161 * Set indicate vertices property.
30164 * @fires Tag#changed
30166 set: function (value) {
30167 this._indicateVertices = value;
30168 this._notifyChanged$.next(this);
30173 Object.defineProperty(OutlineTag.prototype, "lineColor", {
30175 * Get line color property.
30176 * @returns {number}
30179 return this._lineColor;
30182 * Set line color property.
30185 * @fires Tag#changed
30187 set: function (value) {
30188 this._lineColor = value;
30189 this._notifyChanged$.next(this);
30194 Object.defineProperty(OutlineTag.prototype, "lineOpacity", {
30196 * Get line opacity property.
30197 * @returns {number}
30200 return this._lineOpacity;
30203 * Set line opacity property.
30206 * @fires Tag#changed
30208 set: function (value) {
30209 this._lineOpacity = value;
30210 this._notifyChanged$.next(this);
30215 Object.defineProperty(OutlineTag.prototype, "lineWidth", {
30217 * Get line width property.
30218 * @returns {number}
30221 return this._lineWidth;
30224 * Set line width property.
30227 * @fires Tag#changed
30229 set: function (value) {
30230 this._lineWidth = value;
30231 this._notifyChanged$.next(this);
30236 Object.defineProperty(OutlineTag.prototype, "text", {
30238 * Get text property.
30239 * @returns {string}
30245 * Set text property.
30248 * @fires Tag#changed
30250 set: function (value) {
30251 this._text = value;
30252 this._notifyChanged$.next(this);
30257 Object.defineProperty(OutlineTag.prototype, "textColor", {
30259 * Get text color property.
30260 * @returns {number}
30263 return this._textColor;
30266 * Set text color property.
30269 * @fires Tag#changed
30271 set: function (value) {
30272 this._textColor = value;
30273 this._notifyChanged$.next(this);
30279 * Set options for tag.
30281 * @description Sets all the option properties provided and keeps
30282 * the rest of the values as is.
30284 * @param {IOutlineTagOptions} options - Outline tag options
30286 * @fires {Tag#changed}
30288 OutlineTag.prototype.setOptions = function (options) {
30289 this._editable = options.editable == null ? this._editable : options.editable;
30290 this._icon = options.icon === undefined ? this._icon : options.icon;
30291 this._iconFloat = options.iconFloat == null ? this._iconFloat : options.iconFloat;
30292 this._iconIndex = options.iconIndex == null ? this._iconIndex : options.iconIndex;
30293 this._indicateVertices = options.indicateVertices == null ? this._indicateVertices : options.indicateVertices;
30294 this._lineColor = options.lineColor == null ? this._lineColor : options.lineColor;
30295 this._lineWidth = options.lineWidth == null ? this._lineWidth : options.lineWidth;
30296 this._fillColor = options.fillColor == null ? this._fillColor : options.fillColor;
30297 this._fillOpacity = options.fillOpacity == null ? this._fillOpacity : options.fillOpacity;
30298 this._text = options.text === undefined ? this._text : options.text;
30299 this._textColor = options.textColor == null ? this._textColor : options.textColor;
30300 this._notifyChanged$.next(this);
30303 * Event fired when the icon of the outline tag is clicked.
30305 * @event OutlineTag#click
30306 * @type {OutlineTag} The tag instance that was clicked.
30308 OutlineTag.click = "click";
30310 }(Component_1.Tag));
30311 exports.OutlineTag = OutlineTag;
30312 exports.default = OutlineTag;
30314 },{"../../../Component":226,"../../../Viewer":237,"rxjs/Subject":34}],304:[function(require,module,exports){
30316 /// <reference path="../../../../typings/index.d.ts" />
30317 Object.defineProperty(exports, "__esModule", { value: true });
30318 var Subject_1 = require("rxjs/Subject");
30319 var Geo_1 = require("../../../Geo");
30320 var RenderTag = (function () {
30321 function RenderTag(tag, transform, viewportCoords) {
30323 this._transform = transform;
30324 this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
30325 this._glObjectsChanged$ = new Subject_1.Subject();
30326 this._interact$ = new Subject_1.Subject();
30328 Object.defineProperty(RenderTag.prototype, "glObjectsChanged$", {
30330 return this._glObjectsChanged$;
30335 Object.defineProperty(RenderTag.prototype, "interact$", {
30337 return this._interact$;
30342 Object.defineProperty(RenderTag.prototype, "tag", {
30351 exports.RenderTag = RenderTag;
30352 exports.default = RenderTag;
30354 },{"../../../Geo":229,"rxjs/Subject":34}],305:[function(require,module,exports){
30356 /// <reference path="../../../../typings/index.d.ts" />
30357 var __extends = (this && this.__extends) || (function () {
30358 var extendStatics = Object.setPrototypeOf ||
30359 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30360 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30361 return function (d, b) {
30362 extendStatics(d, b);
30363 function __() { this.constructor = d; }
30364 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30367 Object.defineProperty(exports, "__esModule", { value: true });
30368 var vd = require("virtual-dom");
30369 var Component_1 = require("../../../Component");
30370 var Viewer_1 = require("../../../Viewer");
30372 * @class SpotRenderTag
30373 * @classdesc Tag visualizing the properties of a SpotTag.
30375 var SpotRenderTag = (function (_super) {
30376 __extends(SpotRenderTag, _super);
30377 function SpotRenderTag() {
30378 return _super !== null && _super.apply(this, arguments) || this;
30380 SpotRenderTag.prototype.dispose = function () { };
30381 SpotRenderTag.prototype.getDOMObjects = function (atlas, camera, size) {
30383 var tag = this._tag;
30385 offsetHeight: size.height, offsetWidth: size.width,
30388 var _a = tag.geometry.getCentroid2d(), centroidBasicX = _a[0], centroidBasicY = _a[1];
30389 var centroidCanvas = this._viewportCoords.basicToCanvasSafe(centroidBasicX, centroidBasicY, container, this._transform, camera);
30390 if (centroidCanvas != null) {
30391 var interactNone = function (e) {
30392 _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: tag });
30394 var canvasX = Math.round(centroidCanvas[0]);
30395 var canvasY = Math.round(centroidCanvas[1]);
30396 if (tag.icon != null) {
30397 if (atlas.loaded) {
30398 var sprite = atlas.getDOMSprite(tag.icon, Viewer_1.Alignment.Bottom);
30399 var transform_1 = "translate(" + canvasX + "px," + (canvasY + 8) + "px)";
30401 onmousedown: interactNone,
30403 pointerEvents: "all",
30404 transform: transform_1,
30407 vNodes.push(vd.h("div", properties, [sprite]));
30410 else if (tag.text != null) {
30411 var transform_2 = "translate(-50%,0%) translate(" + canvasX + "px," + (canvasY + 8) + "px)";
30413 onmousedown: interactNone,
30415 color: this._colorToCss(tag.textColor),
30416 transform: transform_2,
30418 textContent: tag.text,
30420 vNodes.push(vd.h("span.TagSymbol", properties, []));
30422 var interact = this._interact(Component_1.TagOperation.Centroid, tag);
30423 var background = this._colorToCss(tag.color);
30424 var transform = "translate(-50%,-50%) translate(" + canvasX + "px," + canvasY + "px)";
30425 if (tag.editable) {
30426 var interactorProperties = {
30427 onmousedown: interact,
30429 background: background,
30430 transform: transform,
30433 vNodes.push(vd.h("div.TagSpotInteractor", interactorProperties, []));
30435 var pointProperties = {
30437 background: background,
30438 transform: transform,
30441 vNodes.push(vd.h("div.TagVertex", pointProperties, []));
30445 SpotRenderTag.prototype.getGLObjects = function () { return []; };
30446 SpotRenderTag.prototype.getRetrievableObjects = function () { return []; };
30447 SpotRenderTag.prototype._colorToCss = function (color) {
30448 return "#" + ("000000" + color.toString(16)).substr(-6);
30450 SpotRenderTag.prototype._interact = function (operation, tag, vertexIndex) {
30452 return function (e) {
30453 var offsetX = e.offsetX - e.target.offsetWidth / 2;
30454 var offsetY = e.offsetY - e.target.offsetHeight / 2;
30455 _this._interact$.next({
30458 operation: operation,
30460 vertexIndex: vertexIndex,
30464 return SpotRenderTag;
30465 }(Component_1.RenderTag));
30466 exports.SpotRenderTag = SpotRenderTag;
30468 },{"../../../Component":226,"../../../Viewer":237,"virtual-dom":182}],306:[function(require,module,exports){
30470 var __extends = (this && this.__extends) || (function () {
30471 var extendStatics = Object.setPrototypeOf ||
30472 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30473 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30474 return function (d, b) {
30475 extendStatics(d, b);
30476 function __() { this.constructor = d; }
30477 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30480 Object.defineProperty(exports, "__esModule", { value: true });
30481 var Component_1 = require("../../../Component");
30485 * @classdesc Tag holding properties for visualizing the centroid of a geometry.
30489 * var geometry = new Mapillary.TagComponent.PointGeometry([0.3, 0.3]);
30490 * var tag = new Mapillary.TagComponent.SpotTag(
30493 * { editable: true, color: 0xff0000 });
30495 * tagComponent.add([tag]);
30498 var SpotTag = (function (_super) {
30499 __extends(SpotTag, _super);
30501 * Create a spot tag.
30505 * @param {string} id
30506 * @param {Geometry} geometry
30507 * @param {IOutlineTagOptions} options - Options defining the visual appearance and
30508 * behavior of the spot tag.
30510 function SpotTag(id, geometry, options) {
30511 var _this = _super.call(this, id, geometry) || this;
30512 options = !!options ? options : {};
30513 _this._color = options.color == null ? 0xFFFFFF : options.color;
30514 _this._editable = options.editable == null ? false : options.editable;
30515 _this._icon = options.icon === undefined ? null : options.icon;
30516 _this._text = options.text === undefined ? null : options.text;
30517 _this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor;
30520 Object.defineProperty(SpotTag.prototype, "color", {
30522 * Get color property.
30523 * @returns {number} The color of the spot as a hexagonal number;
30526 return this._color;
30529 * Set color property.
30532 * @fires Tag#changed
30534 set: function (value) {
30535 this._color = value;
30536 this._notifyChanged$.next(this);
30541 Object.defineProperty(SpotTag.prototype, "editable", {
30543 * Get editable property.
30544 * @returns {boolean} Value indicating if tag is editable.
30547 return this._editable;
30550 * Set editable property.
30553 * @fires Tag#changed
30555 set: function (value) {
30556 this._editable = value;
30557 this._notifyChanged$.next(this);
30562 Object.defineProperty(SpotTag.prototype, "icon", {
30564 * Get icon property.
30565 * @returns {string}
30571 * Set icon property.
30574 * @fires Tag#changed
30576 set: function (value) {
30577 this._icon = value;
30578 this._notifyChanged$.next(this);
30583 Object.defineProperty(SpotTag.prototype, "text", {
30585 * Get text property.
30586 * @returns {string}
30592 * Set text property.
30595 * @fires Tag#changed
30597 set: function (value) {
30598 this._text = value;
30599 this._notifyChanged$.next(this);
30604 Object.defineProperty(SpotTag.prototype, "textColor", {
30606 * Get text color property.
30607 * @returns {number}
30610 return this._textColor;
30613 * Set text color property.
30616 * @fires Tag#changed
30618 set: function (value) {
30619 this._textColor = value;
30620 this._notifyChanged$.next(this);
30626 * Set options for tag.
30628 * @description Sets all the option properties provided and keps
30629 * the rest of the values as is.
30631 * @param {ISpotTagOptions} options - Spot tag options
30633 * @fires {Tag#changed}
30635 SpotTag.prototype.setOptions = function (options) {
30636 this._color = options.color == null ? this._color : options.color;
30637 this._editable = options.editable == null ? this._editable : options.editable;
30638 this._icon = options.icon === undefined ? this._icon : options.icon;
30639 this._text = options.text === undefined ? this._text : options.text;
30640 this._textColor = options.textColor == null ? this._textColor : options.textColor;
30641 this._notifyChanged$.next(this);
30644 }(Component_1.Tag));
30645 exports.SpotTag = SpotTag;
30646 exports.default = SpotTag;
30648 },{"../../../Component":226}],307:[function(require,module,exports){
30650 var __extends = (this && this.__extends) || (function () {
30651 var extendStatics = Object.setPrototypeOf ||
30652 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30653 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30654 return function (d, b) {
30655 extendStatics(d, b);
30656 function __() { this.constructor = d; }
30657 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30660 Object.defineProperty(exports, "__esModule", { value: true });
30661 var Subject_1 = require("rxjs/Subject");
30662 require("rxjs/add/operator/map");
30663 require("rxjs/add/operator/share");
30664 var Utils_1 = require("../../../Utils");
30668 * @classdesc Abstract class representing the basic functionality of for a tag.
30670 var Tag = (function (_super) {
30671 __extends(Tag, _super);
30676 * @param {string} id
30677 * @param {Geometry} geometry
30679 function Tag(id, geometry) {
30680 var _this = _super.call(this) || this;
30682 _this._geometry = geometry;
30683 _this._notifyChanged$ = new Subject_1.Subject();
30684 _this._notifyChanged$
30685 .subscribe(function (t) {
30686 _this.fire(Tag.changed, _this);
30688 _this._geometry.changed$
30689 .subscribe(function (g) {
30690 _this.fire(Tag.geometrychanged, _this);
30694 Object.defineProperty(Tag.prototype, "id", {
30697 * @returns {string}
30705 Object.defineProperty(Tag.prototype, "geometry", {
30707 * Get geometry property.
30708 * @returns {Geometry} The geometry of the tag.
30711 return this._geometry;
30716 Object.defineProperty(Tag.prototype, "changed$", {
30718 * Get changed observable.
30719 * @returns {Observable<Tag>}
30723 return this._notifyChanged$;
30728 Object.defineProperty(Tag.prototype, "geometryChanged$", {
30730 * Get geometry changed observable.
30731 * @returns {Observable<Tag>}
30736 return this._geometry.changed$
30737 .map(function (geometry) {
30746 * Event fired when a property related to the visual appearance of the
30749 * @event Tag#changed
30750 * @type {Tag} The tag instance that has changed.
30752 Tag.changed = "changed";
30754 * Event fired when the geometry of the tag has changed.
30756 * @event Tag#geometrychanged
30757 * @type {Tag} The tag instance whose geometry has changed.
30759 Tag.geometrychanged = "geometrychanged";
30761 }(Utils_1.EventEmitter));
30763 exports.default = Tag;
30765 },{"../../../Utils":236,"rxjs/Subject":34,"rxjs/add/operator/map":65,"rxjs/add/operator/share":74}],308:[function(require,module,exports){
30767 Object.defineProperty(exports, "__esModule", { value: true });
30768 var HandlerBase = (function () {
30769 function HandlerBase(component, container, navigator) {
30770 this._component = component;
30771 this._container = container;
30772 this._navigator = navigator;
30773 this._enabled = false;
30775 Object.defineProperty(HandlerBase.prototype, "isEnabled", {
30777 * Returns a Boolean indicating whether the interaction is enabled.
30779 * @returns {boolean} `true` if the interaction is enabled.
30782 return this._enabled;
30788 * Enables the interaction.
30790 * @example ```<component-name>.<handler-name>.enable();```
30792 HandlerBase.prototype.enable = function () {
30793 if (this._enabled || !this._component.activated) {
30797 this._enabled = true;
30798 this._component.configure(this._getConfiguration(true));
30801 * Disables the interaction.
30803 * @example ```<component-name>.<handler-name>.disable();```
30805 HandlerBase.prototype.disable = function () {
30806 if (!this._enabled) {
30810 this._enabled = false;
30811 if (this._component.activated) {
30812 this._component.configure(this._getConfiguration(false));
30815 return HandlerBase;
30817 exports.HandlerBase = HandlerBase;
30818 exports.default = HandlerBase;
30820 },{}],309:[function(require,module,exports){
30822 var __extends = (this && this.__extends) || (function () {
30823 var extendStatics = Object.setPrototypeOf ||
30824 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30825 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30826 return function (d, b) {
30827 extendStatics(d, b);
30828 function __() { this.constructor = d; }
30829 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30832 Object.defineProperty(exports, "__esModule", { value: true });
30833 var MapillaryError_1 = require("./MapillaryError");
30834 var ArgumentMapillaryError = (function (_super) {
30835 __extends(ArgumentMapillaryError, _super);
30836 function ArgumentMapillaryError(message) {
30837 var _this = _super.call(this, message != null ? message : "The argument is not valid.") || this;
30838 _this.name = "ArgumentMapillaryError";
30841 return ArgumentMapillaryError;
30842 }(MapillaryError_1.MapillaryError));
30843 exports.ArgumentMapillaryError = ArgumentMapillaryError;
30844 exports.default = ArgumentMapillaryError;
30846 },{"./MapillaryError":311}],310:[function(require,module,exports){
30848 var __extends = (this && this.__extends) || (function () {
30849 var extendStatics = Object.setPrototypeOf ||
30850 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30851 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30852 return function (d, b) {
30853 extendStatics(d, b);
30854 function __() { this.constructor = d; }
30855 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30858 Object.defineProperty(exports, "__esModule", { value: true });
30859 var MapillaryError_1 = require("./MapillaryError");
30860 var GraphMapillaryError = (function (_super) {
30861 __extends(GraphMapillaryError, _super);
30862 function GraphMapillaryError(message) {
30863 var _this = _super.call(this, message) || this;
30864 _this.name = "GraphMapillaryError";
30867 return GraphMapillaryError;
30868 }(MapillaryError_1.MapillaryError));
30869 exports.GraphMapillaryError = GraphMapillaryError;
30870 exports.default = GraphMapillaryError;
30872 },{"./MapillaryError":311}],311:[function(require,module,exports){
30874 var __extends = (this && this.__extends) || (function () {
30875 var extendStatics = Object.setPrototypeOf ||
30876 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30877 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30878 return function (d, b) {
30879 extendStatics(d, b);
30880 function __() { this.constructor = d; }
30881 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30884 Object.defineProperty(exports, "__esModule", { value: true });
30885 var MapillaryError = (function (_super) {
30886 __extends(MapillaryError, _super);
30887 function MapillaryError(message) {
30888 var _this = _super.call(this, message) || this;
30889 _this.name = "MapillaryError";
30892 return MapillaryError;
30894 exports.MapillaryError = MapillaryError;
30895 exports.default = MapillaryError;
30897 },{}],312:[function(require,module,exports){
30899 /// <reference path="../../typings/index.d.ts" />
30900 Object.defineProperty(exports, "__esModule", { value: true });
30901 var THREE = require("three");
30905 * @classdesc Holds information about a camera.
30907 var Camera = (function () {
30909 * Create a new camera instance.
30910 * @param {Transform} [transform] - Optional transform instance.
30912 function Camera(transform) {
30913 if (transform != null) {
30914 this._position = new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 0));
30915 this._lookat = new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 10));
30916 this._up = transform.upVector();
30917 this._focal = this._getFocal(transform);
30920 this._position = new THREE.Vector3(0, 0, 0);
30921 this._lookat = new THREE.Vector3(0, 0, 1);
30922 this._up = new THREE.Vector3(0, -1, 0);
30926 Object.defineProperty(Camera.prototype, "position", {
30929 * @returns {THREE.Vector3} The position vector.
30932 return this._position;
30937 Object.defineProperty(Camera.prototype, "lookat", {
30940 * @returns {THREE.Vector3} The lookat vector.
30943 return this._lookat;
30948 Object.defineProperty(Camera.prototype, "up", {
30951 * @returns {THREE.Vector3} The up vector.
30959 Object.defineProperty(Camera.prototype, "focal", {
30962 * @returns {number} The focal length.
30965 return this._focal;
30970 set: function (value) {
30971 this._focal = value;
30977 * Update this camera to the linearly interpolated value of two other cameras.
30979 * @param {Camera} a - First camera.
30980 * @param {Camera} b - Second camera.
30981 * @param {number} alpha - Interpolation value on the interval [0, 1].
30983 Camera.prototype.lerpCameras = function (a, b, alpha) {
30984 this._position.subVectors(b.position, a.position).multiplyScalar(alpha).add(a.position);
30985 this._lookat.subVectors(b.lookat, a.lookat).multiplyScalar(alpha).add(a.lookat);
30986 this._up.subVectors(b.up, a.up).multiplyScalar(alpha).add(a.up);
30987 this._focal = (1 - alpha) * a.focal + alpha * b.focal;
30990 * Copy the properties of another camera to this camera.
30992 * @param {Camera} other - Another camera.
30994 Camera.prototype.copy = function (other) {
30995 this._position.copy(other.position);
30996 this._lookat.copy(other.lookat);
30997 this._up.copy(other.up);
30998 this._focal = other.focal;
31001 * Clone this camera.
31003 * @returns {Camera} A camera with cloned properties equal to this camera.
31005 Camera.prototype.clone = function () {
31006 var camera = new Camera();
31007 camera.position.copy(this._position);
31008 camera.lookat.copy(this._lookat);
31009 camera.up.copy(this._up);
31010 camera.focal = this._focal;
31014 * Determine the distance between this camera and another camera.
31016 * @param {Camera} other - Another camera.
31017 * @returns {number} The distance between the cameras.
31019 Camera.prototype.diff = function (other) {
31020 var pd = this._position.distanceToSquared(other.position);
31021 var ld = this._lookat.distanceToSquared(other.lookat);
31022 var ud = this._up.distanceToSquared(other.up);
31023 var fd = 100 * Math.abs(this._focal - other.focal);
31024 return Math.max(pd, ld, ud, fd);
31027 * Get the focal length based on the transform.
31029 * @description Returns the focal length of the transform if gpano info is not available.
31030 * Returns a focal length corresponding to a vertical fov clamped to [45, 90] degrees based on
31031 * the gpano information if available.
31033 * @returns {number} Focal length.
31035 Camera.prototype._getFocal = function (transform) {
31036 if (transform.gpano == null) {
31037 return transform.focal;
31039 var vFov = Math.PI * transform.gpano.CroppedAreaImageHeightPixels / transform.gpano.FullPanoHeightPixels;
31040 var focal = 0.5 / Math.tan(vFov / 2);
31041 return Math.min(1 / (2 * (Math.sqrt(2) - 1)), Math.max(0.5, focal));
31045 exports.Camera = Camera;
31047 },{"three":176}],313:[function(require,module,exports){
31049 Object.defineProperty(exports, "__esModule", { value: true });
31053 * @classdesc Converts coordinates between the geodetic (WGS84),
31054 * Earth-Centered, Earth-Fixed (ECEF) and local topocentric
31055 * East, North, Up (ENU) reference frames.
31057 * The WGS84 has latitude (degrees), longitude (degrees) and
31058 * altitude (meters) values.
31060 * The ECEF Z-axis pierces the north pole and the
31061 * XY-axis defines the equatorial plane. The X-axis extends
31062 * from the geocenter to the intersection of the Equator and
31063 * the Greenwich Meridian. All values in meters.
31065 * The WGS84 parameters are:
31069 * f = 1 / 298.257223563
31070 * e = Math.sqrt((a^2 - b^2) / a^2)
31071 * e' = Math.sqrt((a^2 - b^2) / b^2)
31073 * The WGS84 to ECEF conversion is performed using the following:
31075 * X = (N - h) * cos(phi) * cos(lambda)
31076 * Y = (N + h) * cos(phi) * sin(lambda)
31077 * Z = (b^2 * N / a^2 + h) * sin(phi)
31082 * lambda = longitude
31083 * h = height above ellipsoid (altitude)
31084 * N = Radius of curvature (meters)
31085 * = a / Math.sqrt(1 - e^2 * sin(phi)^2)
31087 * The ECEF to WGS84 conversion is performed using the following:
31089 * phi = arctan((Z + e'^2 * b * sin(theta)^3) / (p - e^2 * a * cos(theta)^3))
31090 * lambda = arctan(Y / X)
31091 * h = p / cos(phi) - N
31095 * p = Math.sqrt(X^2 + Y^2)
31096 * theta = arctan(Z * a / p * b)
31098 * In the ENU reference frame the x-axis points to the
31099 * East, the y-axis to the North and the z-axis Up. All values
31102 * The ECEF to ENU conversion is performed using the following:
31104 * | x | | -sin(lambda_r) cos(lambda_r) 0 | | X - X_r |
31105 * | y | = | -sin(phi_r) * cos(lambda_r) -sin(phi_r) * sin(lambda_r) cos(phi_r) | | Y - Y_r |
31106 * | z | | cos(phi_r) * cos(lambda_r) cos(phi_r) * sin(lambda_r) sin(phi_r) | | Z - Z_r |
31110 * phi_r = latitude of reference
31111 * lambda_r = longitude of reference
31112 * X_r, Y_r, Z_r = ECEF coordinates of reference
31114 * The ENU to ECEF conversion is performed by solving the above equation for X, Y, Z.
31116 * WGS84 to ENU and ENU to WGS84 are two step conversions with ECEF calculated in
31117 * the first step for both conversions.
31119 var GeoCoords = (function () {
31120 function GeoCoords() {
31121 this._wgs84a = 6378137.0;
31122 this._wgs84b = 6356752.31424518;
31125 * Convert coordinates from geodetic (WGS84) reference to local topocentric
31128 * @param {number} lat Latitude in degrees.
31129 * @param {number} lon Longitude in degrees.
31130 * @param {number} alt Altitude in meters.
31131 * @param {number} refLat Reference latitude in degrees.
31132 * @param {number} refLon Reference longitude in degrees.
31133 * @param {number} refAlt Reference altitude in meters.
31134 * @returns {Array<number>} The x, y, z local topocentric ENU coordinates.
31136 GeoCoords.prototype.geodeticToEnu = function (lat, lon, alt, refLat, refLon, refAlt) {
31137 var ecef = this.geodeticToEcef(lat, lon, alt);
31138 return this.ecefToEnu(ecef[0], ecef[1], ecef[2], refLat, refLon, refAlt);
31141 * Convert coordinates from local topocentric (ENU) reference to
31142 * geodetic (WGS84) reference.
31144 * @param {number} x Topocentric ENU coordinate in East direction.
31145 * @param {number} y Topocentric ENU coordinate in North direction.
31146 * @param {number} z Topocentric ENU coordinate in Up direction.
31147 * @param {number} refLat Reference latitude in degrees.
31148 * @param {number} refLon Reference longitude in degrees.
31149 * @param {number} refAlt Reference altitude in meters.
31150 * @returns {Array<number>} The latitude and longitude in degrees
31151 * as well as altitude in meters.
31153 GeoCoords.prototype.enuToGeodetic = function (x, y, z, refLat, refLon, refAlt) {
31154 var ecef = this.enuToEcef(x, y, z, refLat, refLon, refAlt);
31155 return this.ecefToGeodetic(ecef[0], ecef[1], ecef[2]);
31158 * Convert coordinates from Earth-Centered, Earth-Fixed (ECEF) reference
31159 * to local topocentric (ENU) reference.
31161 * @param {number} X ECEF X-value.
31162 * @param {number} Y ECEF Y-value.
31163 * @param {number} Z ECEF Z-value.
31164 * @param {number} refLat Reference latitude in degrees.
31165 * @param {number} refLon Reference longitude in degrees.
31166 * @param {number} refAlt Reference altitude in meters.
31167 * @returns {Array<number>} The x, y, z topocentric ENU coordinates in East, North
31168 * and Up directions respectively.
31170 GeoCoords.prototype.ecefToEnu = function (X, Y, Z, refLat, refLon, refAlt) {
31171 var refEcef = this.geodeticToEcef(refLat, refLon, refAlt);
31172 var V = [X - refEcef[0], Y - refEcef[1], Z - refEcef[2]];
31173 refLat = refLat * Math.PI / 180.0;
31174 refLon = refLon * Math.PI / 180.0;
31175 var cosLat = Math.cos(refLat);
31176 var sinLat = Math.sin(refLat);
31177 var cosLon = Math.cos(refLon);
31178 var sinLon = Math.sin(refLon);
31179 var x = -sinLon * V[0] + cosLon * V[1];
31180 var y = -sinLat * cosLon * V[0] - sinLat * sinLon * V[1] + cosLat * V[2];
31181 var z = cosLat * cosLon * V[0] + cosLat * sinLon * V[1] + sinLat * V[2];
31185 * Convert coordinates from local topocentric (ENU) reference
31186 * to Earth-Centered, Earth-Fixed (ECEF) reference.
31188 * @param {number} x Topocentric ENU coordinate in East direction.
31189 * @param {number} y Topocentric ENU coordinate in North direction.
31190 * @param {number} z Topocentric ENU coordinate in Up direction.
31191 * @param {number} refLat Reference latitude in degrees.
31192 * @param {number} refLon Reference longitude in degrees.
31193 * @param {number} refAlt Reference altitude in meters.
31194 * @returns {Array<number>} The X, Y, Z ECEF coordinates.
31196 GeoCoords.prototype.enuToEcef = function (x, y, z, refLat, refLon, refAlt) {
31197 var refEcef = this.geodeticToEcef(refLat, refLon, refAlt);
31198 refLat = refLat * Math.PI / 180.0;
31199 refLon = refLon * Math.PI / 180.0;
31200 var cosLat = Math.cos(refLat);
31201 var sinLat = Math.sin(refLat);
31202 var cosLon = Math.cos(refLon);
31203 var sinLon = Math.sin(refLon);
31204 var X = -sinLon * x - sinLat * cosLon * y + cosLat * cosLon * z + refEcef[0];
31205 var Y = cosLon * x - sinLat * sinLon * y + cosLat * sinLon * z + refEcef[1];
31206 var Z = cosLat * y + sinLat * z + refEcef[2];
31210 * Convert coordinates from geodetic reference (WGS84) to Earth-Centered,
31211 * Earth-Fixed (ECEF) reference.
31213 * @param {number} lat Latitude in degrees.
31214 * @param {number} lon Longitude in degrees.
31215 * @param {number} alt Altitude in meters.
31216 * @returns {Array<number>} The X, Y, Z ECEF coordinates.
31218 GeoCoords.prototype.geodeticToEcef = function (lat, lon, alt) {
31219 var a = this._wgs84a;
31220 var b = this._wgs84b;
31221 lat = lat * Math.PI / 180.0;
31222 lon = lon * Math.PI / 180.0;
31223 var cosLat = Math.cos(lat);
31224 var sinLat = Math.sin(lat);
31225 var cosLon = Math.cos(lon);
31226 var sinLon = Math.sin(lon);
31229 var L = 1.0 / Math.sqrt(a2 * cosLat * cosLat + b2 * sinLat * sinLat);
31230 var nhcl = (a2 * L + alt) * cosLat;
31231 var X = nhcl * cosLon;
31232 var Y = nhcl * sinLon;
31233 var Z = (b2 * L + alt) * sinLat;
31237 * Convert coordinates from Earth-Centered, Earth-Fixed (ECEF) reference
31238 * to geodetic reference (WGS84).
31240 * @param {number} X ECEF X-value.
31241 * @param {number} Y ECEF Y-value.
31242 * @param {number} Z ECEF Z-value.
31243 * @returns {Array<number>} The latitude and longitude in degrees
31244 * as well as altitude in meters.
31246 GeoCoords.prototype.ecefToGeodetic = function (X, Y, Z) {
31247 var a = this._wgs84a;
31248 var b = this._wgs84b;
31251 var a2mb2 = a2 - b2;
31252 var ea = Math.sqrt(a2mb2 / a2);
31253 var eb = Math.sqrt(a2mb2 / b2);
31254 var p = Math.sqrt(X * X + Y * Y);
31255 var theta = Math.atan2(Z * a, p * b);
31256 var sinTheta = Math.sin(theta);
31257 var cosTheta = Math.cos(theta);
31258 var lon = Math.atan2(Y, X);
31259 var lat = Math.atan2(Z + eb * eb * b * sinTheta * sinTheta * sinTheta, p - ea * ea * a * cosTheta * cosTheta * cosTheta);
31260 var sinLat = Math.sin(lat);
31261 var cosLat = Math.cos(lat);
31262 var N = a / Math.sqrt(1 - ea * ea * sinLat * sinLat);
31263 var alt = p / cosLat - N;
31264 return [lat * 180.0 / Math.PI, lon * 180.0 / Math.PI, alt];
31268 exports.GeoCoords = GeoCoords;
31269 exports.default = GeoCoords;
31271 },{}],314:[function(require,module,exports){
31273 /// <reference path="../../typings/index.d.ts" />
31274 Object.defineProperty(exports, "__esModule", { value: true });
31275 var THREE = require("three");
31279 * @classdesc Provides methods for scalar, vector and matrix calculations.
31281 var Spatial = (function () {
31282 function Spatial() {
31283 this._epsilon = 1e-9;
31286 * Converts azimuthal phi rotation (counter-clockwise with origin on X-axis) to
31287 * bearing (clockwise with origin at north or Y-axis).
31289 * @param {number} phi - Azimuthal phi angle in radians.
31290 * @returns {number} Bearing in radians.
31292 Spatial.prototype.azimuthalToBearing = function (phi) {
31293 return -phi + Math.PI / 2;
31296 * Converts degrees to radians.
31298 * @param {number} deg - Degrees.
31299 * @returns {number} Radians.
31301 Spatial.prototype.degToRad = function (deg) {
31302 return Math.PI * deg / 180;
31305 * Converts radians to degrees.
31307 * @param {number} rad - Radians.
31308 * @returns {number} Degrees.
31310 Spatial.prototype.radToDeg = function (rad) {
31311 return 180 * rad / Math.PI;
31314 * Creates a rotation matrix from an angle-axis vector.
31316 * @param {Array<number>} angleAxis - Angle-axis representation of a rotation.
31317 * @returns {THREE.Matrix4} Rotation matrix.
31319 Spatial.prototype.rotationMatrix = function (angleAxis) {
31320 var axis = new THREE.Vector3(angleAxis[0], angleAxis[1], angleAxis[2]);
31321 var angle = axis.length();
31325 return new THREE.Matrix4().makeRotationAxis(axis, angle);
31328 * Rotates a vector according to a angle-axis rotation vector.
31330 * @param {Array<number>} vector - Vector to rotate.
31331 * @param {Array<number>} angleAxis - Angle-axis representation of a rotation.
31332 * @returns {THREE.Vector3} Rotated vector.
31334 Spatial.prototype.rotate = function (vector, angleAxis) {
31335 var v = new THREE.Vector3(vector[0], vector[1], vector[2]);
31336 var rotationMatrix = this.rotationMatrix(angleAxis);
31337 v.applyMatrix4(rotationMatrix);
31341 * Calculates the optical center from a rotation vector
31342 * on the angle-axis representation and a translation vector
31343 * according to C = -R^T t.
31345 * @param {Array<number>} rotation - Angle-axis representation of a rotation.
31346 * @param {Array<number>} translation - Translation vector.
31347 * @returns {THREE.Vector3} Optical center.
31349 Spatial.prototype.opticalCenter = function (rotation, translation) {
31350 var angleAxis = [-rotation[0], -rotation[1], -rotation[2]];
31351 var vector = [-translation[0], -translation[1], -translation[2]];
31352 return this.rotate(vector, angleAxis);
31355 * Calculates the viewing direction from a rotation vector
31356 * on the angle-axis representation.
31358 * @param {number[]} rotation - Angle-axis representation of a rotation.
31359 * @returns {THREE.Vector3} Viewing direction.
31361 Spatial.prototype.viewingDirection = function (rotation) {
31362 var angleAxis = [-rotation[0], -rotation[1], -rotation[2]];
31363 return this.rotate([0, 0, 1], angleAxis);
31366 * Wrap a number on the interval [min, max].
31368 * @param {number} value - Value to wrap.
31369 * @param {number} min - Lower endpoint of interval.
31370 * @param {number} max - Upper endpoint of interval.
31371 * @returns {number} The wrapped number.
31373 Spatial.prototype.wrap = function (value, min, max) {
31375 throw new Error("Invalid arguments: max must be larger than min.");
31377 var interval = (max - min);
31378 while (value > max || value < min) {
31380 value = value - interval;
31382 else if (value < min) {
31383 value = value + interval;
31389 * Wrap an angle on the interval [-Pi, Pi].
31391 * @param {number} angle - Value to wrap.
31392 * @returns {number} Wrapped angle.
31394 Spatial.prototype.wrapAngle = function (angle) {
31395 return this.wrap(angle, -Math.PI, Math.PI);
31398 * Limit the value to the interval [min, max] by changing the value to
31399 * the nearest available one when it is outside the interval.
31401 * @param {number} value - Value to clamp.
31402 * @param {number} min - Minimum of the interval.
31403 * @param {number} max - Maximum of the interval.
31404 * @returns {number} Clamped value.
31406 Spatial.prototype.clamp = function (value, min, max) {
31416 * Calculates the counter-clockwise angle from the first
31417 * vector (x1, y1)^T to the second (x2, y2)^T.
31419 * @param {number} x1 - X coordinate of first vector.
31420 * @param {number} y1 - Y coordinate of first vector.
31421 * @param {number} x2 - X coordinate of second vector.
31422 * @param {number} y2 - Y coordinate of second vector.
31423 * @returns {number} Counter clockwise angle between the vectors.
31425 Spatial.prototype.angleBetweenVector2 = function (x1, y1, x2, y2) {
31426 var angle = Math.atan2(y2, x2) - Math.atan2(y1, x1);
31427 return this.wrapAngle(angle);
31430 * Calculates the minimum (absolute) angle change for rotation
31431 * from one angle to another on the [-Pi, Pi] interval.
31433 * @param {number} angle1 - Start angle.
31434 * @param {number} angle2 - Destination angle.
31435 * @returns {number} Absolute angle change between angles.
31437 Spatial.prototype.angleDifference = function (angle1, angle2) {
31438 var angle = angle2 - angle1;
31439 return this.wrapAngle(angle);
31442 * Calculates the relative rotation angle between two
31443 * angle-axis vectors.
31445 * @param {number} rotation1 - First angle-axis vector.
31446 * @param {number} rotation2 - Second angle-axis vector.
31447 * @returns {number} Relative rotation angle.
31449 Spatial.prototype.relativeRotationAngle = function (rotation1, rotation2) {
31450 var R1T = this.rotationMatrix([-rotation1[0], -rotation1[1], -rotation1[2]]);
31451 var R2 = this.rotationMatrix(rotation2);
31452 var R = R1T.multiply(R2);
31453 var elements = R.elements;
31454 // from Tr(R) = 1 + 2*cos(theta)
31455 var theta = Math.acos((elements[0] + elements[5] + elements[10] - 1) / 2);
31459 * Calculates the angle from a vector to a plane.
31461 * @param {Array<number>} vector - The vector.
31462 * @param {Array<number>} planeNormal - Normal of the plane.
31463 * @returns {number} Angle from between plane and vector.
31465 Spatial.prototype.angleToPlane = function (vector, planeNormal) {
31466 var v = new THREE.Vector3().fromArray(vector);
31467 var norm = v.length();
31468 if (norm < this._epsilon) {
31471 var projection = v.dot(new THREE.Vector3().fromArray(planeNormal));
31472 return Math.asin(projection / norm);
31475 * Calculates the distance between two coordinates
31476 * (latitude longitude pairs) in meters according to
31477 * the haversine formula.
31479 * @param {number} lat1 - Latitude of the first coordinate.
31480 * @param {number} lon1 - Longitude of the first coordinate.
31481 * @param {number} lat2 - Latitude of the second coordinate.
31482 * @param {number} lon2 - Longitude of the second coordinate.
31483 * @returns {number} Distance between lat lon positions.
31485 Spatial.prototype.distanceFromLatLon = function (lat1, lon1, lat2, lon2) {
31487 var dLat = this.degToRad(lat2 - lat1);
31488 var dLon = this.degToRad(lon2 - lon1);
31489 var hav = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
31490 Math.cos(lat1) * Math.cos(lat2) *
31491 Math.sin(dLon / 2) * Math.sin(dLon / 2);
31492 var d = 2 * r * Math.atan2(Math.sqrt(hav), Math.sqrt(1 - hav));
31497 exports.Spatial = Spatial;
31498 exports.default = Spatial;
31500 },{"three":176}],315:[function(require,module,exports){
31502 /// <reference path="../../typings/index.d.ts" />
31503 Object.defineProperty(exports, "__esModule", { value: true });
31504 var THREE = require("three");
31508 * @classdesc Class used for calculating coordinate transformations
31511 var Transform = (function () {
31513 * Create a new transform instance.
31514 * @param {Node} apiNavImIm - Node properties.
31515 * @param {HTMLImageElement} image - Node image.
31516 * @param {Array<number>} translation - Node translation vector in three dimensions.
31518 function Transform(node, image, translation) {
31519 this._orientation = this._getValue(node.orientation, 1);
31520 var imageWidth = image != null ? image.width : 4;
31521 var imageHeight = image != null ? image.height : 3;
31522 var keepOrientation = this._orientation < 5;
31523 this._width = this._getValue(node.width, keepOrientation ? imageWidth : imageHeight);
31524 this._height = this._getValue(node.height, keepOrientation ? imageHeight : imageWidth);
31525 this._basicAspect = keepOrientation ?
31526 this._width / this._height :
31527 this._height / this._width;
31528 this._basicWidth = keepOrientation ? node.width : node.height;
31529 this._basicHeight = keepOrientation ? node.height : node.width;
31530 this._focal = this._getValue(node.focal, 1);
31531 this._scale = this._getValue(node.scale, 0);
31532 this._gpano = node.gpano != null ? node.gpano : null;
31533 this._rt = this._getRt(node.rotation, translation);
31534 this._srt = this._getSrt(this._rt, this._scale);
31536 Object.defineProperty(Transform.prototype, "basicAspect", {
31538 * Get basic aspect.
31539 * @returns {number} The orientation adjusted aspect ratio.
31542 return this._basicAspect;
31547 Object.defineProperty(Transform.prototype, "basicHeight", {
31549 * Get basic height.
31551 * @description Does not fall back to node image height but
31552 * uses original value from API so can be faulty.
31554 * @returns {number} The height of the basic version image
31555 * (adjusted for orientation).
31558 return this._basicHeight;
31563 Object.defineProperty(Transform.prototype, "basicWidth", {
31567 * @description Does not fall back to node image width but
31568 * uses original value from API so can be faulty.
31570 * @returns {number} The width of the basic version image
31571 * (adjusted for orientation).
31574 return this._basicWidth;
31579 Object.defineProperty(Transform.prototype, "focal", {
31582 * @returns {number} The node focal length.
31585 return this._focal;
31590 Object.defineProperty(Transform.prototype, "fullPano", {
31594 * @returns {boolean} Value indicating whether the node is a complete
31598 return this._gpano != null &&
31599 this._gpano.CroppedAreaLeftPixels === 0 &&
31600 this._gpano.CroppedAreaTopPixels === 0 &&
31601 this._gpano.CroppedAreaImageWidthPixels === this._gpano.FullPanoWidthPixels &&
31602 this._gpano.CroppedAreaImageHeightPixels === this._gpano.FullPanoHeightPixels;
31607 Object.defineProperty(Transform.prototype, "gpano", {
31610 * @returns {number} The node gpano information.
31613 return this._gpano;
31618 Object.defineProperty(Transform.prototype, "height", {
31622 * @description Falls back to the node image height if
31623 * the API data is faulty.
31625 * @returns {number} The orientation adjusted image height.
31628 return this._height;
31633 Object.defineProperty(Transform.prototype, "orientation", {
31636 * @returns {number} The image orientation.
31639 return this._orientation;
31644 Object.defineProperty(Transform.prototype, "rt", {
31647 * @returns {THREE.Matrix4} The extrinsic camera matrix.
31655 Object.defineProperty(Transform.prototype, "srt", {
31658 * @returns {THREE.Matrix4} The scaled extrinsic camera matrix.
31666 Object.defineProperty(Transform.prototype, "scale", {
31669 * @returns {number} The node atomic reconstruction scale.
31672 return this._scale;
31677 Object.defineProperty(Transform.prototype, "hasValidScale", {
31679 * Get has valid scale.
31680 * @returns {boolean} Value indicating if the scale of the transform is valid.
31683 return this._scale > 1e-2 && this._scale < 50;
31688 Object.defineProperty(Transform.prototype, "width", {
31692 * @description Falls back to the node image width if
31693 * the API data is faulty.
31695 * @returns {number} The orientation adjusted image width.
31698 return this._width;
31704 * Calculate the up vector for the node transform.
31706 * @returns {THREE.Vector3} Normalized and orientation adjusted up vector.
31708 Transform.prototype.upVector = function () {
31709 var rte = this._rt.elements;
31710 switch (this._orientation) {
31712 return new THREE.Vector3(-rte[1], -rte[5], -rte[9]);
31714 return new THREE.Vector3(rte[1], rte[5], rte[9]);
31716 return new THREE.Vector3(-rte[0], -rte[4], -rte[8]);
31718 return new THREE.Vector3(rte[0], rte[4], rte[8]);
31720 return new THREE.Vector3(-rte[1], -rte[5], -rte[9]);
31724 * Calculate projector matrix for projecting 3D points to texture map
31725 * coordinates (u and v).
31727 * @returns {THREE.Matrix4} Projection matrix for 3D point to texture
31728 * map coordinate calculations.
31730 Transform.prototype.projectorMatrix = function () {
31731 var projector = this._normalizedToTextureMatrix();
31732 var f = this._focal;
31733 var projection = new THREE.Matrix4().set(f, 0, 0, 0, 0, f, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0);
31734 projector.multiply(projection);
31735 projector.multiply(this._rt);
31739 * Project 3D world coordinates to basic coordinates.
31741 * @param {Array<number>} point3d - 3D world coordinates.
31742 * @return {Array<number>} 2D basic coordinates.
31744 Transform.prototype.projectBasic = function (point3d) {
31745 var sfm = this.projectSfM(point3d);
31746 return this._sfmToBasic(sfm);
31749 * Unproject basic coordinates to 3D world coordinates.
31751 * @param {Array<number>} basic - 2D basic coordinates.
31752 * @param {Array<number>} distance - Depth to unproject from camera center.
31753 * @returns {Array<number>} Unprojected 3D world coordinates.
31755 Transform.prototype.unprojectBasic = function (basic, distance) {
31756 var sfm = this._basicToSfm(basic);
31757 return this.unprojectSfM(sfm, distance);
31760 * Project 3D world coordinates to SfM coordinates.
31762 * @param {Array<number>} point3d - 3D world coordinates.
31763 * @return {Array<number>} 2D SfM coordinates.
31765 Transform.prototype.projectSfM = function (point3d) {
31766 var v = new THREE.Vector4(point3d[0], point3d[1], point3d[2], 1);
31767 v.applyMatrix4(this._rt);
31768 return this._bearingToSfm([v.x, v.y, v.z]);
31771 * Unproject SfM coordinates to a 3D world coordinates.
31773 * @param {Array<number>} sfm - 2D SfM coordinates.
31774 * @param {Array<number>} distance - Depth to unproject from camera center.
31775 * @returns {Array<number>} Unprojected 3D world coordinates.
31777 Transform.prototype.unprojectSfM = function (sfm, distance) {
31778 var bearing = this._sfmToBearing(sfm);
31779 var v = new THREE.Vector4(distance * bearing[0], distance * bearing[1], distance * bearing[2], 1);
31780 v.applyMatrix4(new THREE.Matrix4().getInverse(this._rt));
31781 return [v.x / v.w, v.y / v.w, v.z / v.w];
31784 * Transform SfM coordinates to bearing vector (3D cartesian
31785 * coordinates on the unit sphere).
31787 * @param {Array<number>} sfm - 2D SfM coordinates.
31788 * @returns {Array<number>} Bearing vector (3D cartesian coordinates
31789 * on the unit sphere).
31791 Transform.prototype._sfmToBearing = function (sfm) {
31792 if (this._fullPano()) {
31793 var lon = sfm[0] * 2 * Math.PI;
31794 var lat = -sfm[1] * 2 * Math.PI;
31795 var x = Math.cos(lat) * Math.sin(lon);
31796 var y = -Math.sin(lat);
31797 var z = Math.cos(lat) * Math.cos(lon);
31800 else if (this._gpano) {
31801 var size = Math.max(this.gpano.CroppedAreaImageWidthPixels, this.gpano.CroppedAreaImageHeightPixels);
31802 var fullPanoPixel = [
31803 sfm[0] * size + this.gpano.CroppedAreaImageWidthPixels / 2 + this.gpano.CroppedAreaLeftPixels,
31804 sfm[1] * size + this.gpano.CroppedAreaImageHeightPixels / 2 + this.gpano.CroppedAreaTopPixels,
31806 var lon = 2 * Math.PI * (fullPanoPixel[0] / this.gpano.FullPanoWidthPixels - 0.5);
31807 var lat = -Math.PI * (fullPanoPixel[1] / this.gpano.FullPanoHeightPixels - 0.5);
31808 var x = Math.cos(lat) * Math.sin(lon);
31809 var y = -Math.sin(lat);
31810 var z = Math.cos(lat) * Math.cos(lon);
31814 var v = new THREE.Vector3(sfm[0], sfm[1], this._focal);
31816 return [v.x, v.y, v.z];
31820 * Transform bearing vector (3D cartesian coordiantes on the unit sphere) to
31823 * @param {Array<number>} bearing - Bearing vector (3D cartesian coordinates on the
31825 * @returns {Array<number>} 2D SfM coordinates.
31827 Transform.prototype._bearingToSfm = function (bearing) {
31828 if (this._fullPano()) {
31829 var x = bearing[0];
31830 var y = bearing[1];
31831 var z = bearing[2];
31832 var lon = Math.atan2(x, z);
31833 var lat = Math.atan2(-y, Math.sqrt(x * x + z * z));
31834 return [lon / (2 * Math.PI), -lat / (2 * Math.PI)];
31836 else if (this._gpano) {
31837 var x = bearing[0];
31838 var y = bearing[1];
31839 var z = bearing[2];
31840 var lon = Math.atan2(x, z);
31841 var lat = Math.atan2(-y, Math.sqrt(x * x + z * z));
31842 var fullPanoPixel = [
31843 (lon / (2 * Math.PI) + 0.5) * this.gpano.FullPanoWidthPixels,
31844 (-lat / Math.PI + 0.5) * this.gpano.FullPanoHeightPixels,
31846 var size = Math.max(this.gpano.CroppedAreaImageWidthPixels, this.gpano.CroppedAreaImageHeightPixels);
31848 (fullPanoPixel[0] - this.gpano.CroppedAreaLeftPixels - this.gpano.CroppedAreaImageWidthPixels / 2) / size,
31849 (fullPanoPixel[1] - this.gpano.CroppedAreaTopPixels - this.gpano.CroppedAreaImageHeightPixels / 2) / size,
31853 if (bearing[2] > 0) {
31855 bearing[0] * this._focal / bearing[2],
31856 bearing[1] * this._focal / bearing[2],
31861 bearing[0] < 0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
31862 bearing[1] < 0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
31868 * Convert basic coordinates to SfM coordinates.
31870 * @param {Array<number>} basic - 2D basic coordinates.
31871 * @returns {Array<number>} 2D SfM coordinates.
31873 Transform.prototype._basicToSfm = function (basic) {
31876 switch (this._orientation) {
31878 rotatedX = basic[0];
31879 rotatedY = basic[1];
31882 rotatedX = 1 - basic[0];
31883 rotatedY = 1 - basic[1];
31886 rotatedX = basic[1];
31887 rotatedY = 1 - basic[0];
31890 rotatedX = 1 - basic[1];
31891 rotatedY = basic[0];
31894 rotatedX = basic[0];
31895 rotatedY = basic[1];
31898 var w = this._width;
31899 var h = this._height;
31900 var s = Math.max(w, h);
31901 var sfmX = rotatedX * w / s - w / s / 2;
31902 var sfmY = rotatedY * h / s - h / s / 2;
31903 return [sfmX, sfmY];
31906 * Convert SfM coordinates to basic coordinates.
31908 * @param {Array<number>} sfm - 2D SfM coordinates.
31909 * @returns {Array<number>} 2D basic coordinates.
31911 Transform.prototype._sfmToBasic = function (sfm) {
31912 var w = this._width;
31913 var h = this._height;
31914 var s = Math.max(w, h);
31915 var rotatedX = (sfm[0] + w / s / 2) / w * s;
31916 var rotatedY = (sfm[1] + h / s / 2) / h * s;
31919 switch (this._orientation) {
31925 basicX = 1 - rotatedX;
31926 basicY = 1 - rotatedY;
31929 basicX = 1 - rotatedY;
31934 basicY = 1 - rotatedX;
31941 return [basicX, basicY];
31944 * Determines if the gpano information indicates a full panorama.
31946 * @returns {boolean} Value determining if the gpano information indicates
31949 Transform.prototype._fullPano = function () {
31950 return this.gpano != null &&
31951 this.gpano.CroppedAreaLeftPixels === 0 &&
31952 this.gpano.CroppedAreaTopPixels === 0 &&
31953 this.gpano.CroppedAreaImageWidthPixels === this.gpano.FullPanoWidthPixels &&
31954 this.gpano.CroppedAreaImageHeightPixels === this.gpano.FullPanoHeightPixels;
31957 * Checks a value and returns it if it exists and is larger than 0.
31958 * Fallbacks if it is null.
31960 * @param {number} value - Value to check.
31961 * @param {number} fallback - Value to fall back to.
31962 * @returns {number} The value or its fallback value if it is not defined or negative.
31964 Transform.prototype._getValue = function (value, fallback) {
31965 return value != null && value > 0 ? value : fallback;
31968 * Creates the extrinsic camera matrix [ R | t ].
31970 * @param {Array<number>} rotation - Rotation vector in angle axis representation.
31971 * @param {Array<number>} translation - Translation vector.
31972 * @returns {THREE.Matrix4} Extrisic camera matrix.
31974 Transform.prototype._getRt = function (rotation, translation) {
31975 var axis = new THREE.Vector3(rotation[0], rotation[1], rotation[2]);
31976 var angle = axis.length();
31980 var rt = new THREE.Matrix4();
31981 rt.makeRotationAxis(axis, angle);
31982 rt.setPosition(new THREE.Vector3(translation[0], translation[1], translation[2]));
31986 * Calculates the scaled extrinsic camera matrix scale * [ R | t ].
31988 * @param {THREE.Matrix4} rt - Extrisic camera matrix.
31989 * @param {number} scale - Scale factor.
31990 * @returns {THREE.Matrix4} Scaled extrisic camera matrix.
31992 Transform.prototype._getSrt = function (rt, scale) {
31993 var srt = rt.clone();
31994 var elements = srt.elements;
31995 elements[12] = scale * elements[12];
31996 elements[13] = scale * elements[13];
31997 elements[14] = scale * elements[14];
31998 srt.scale(new THREE.Vector3(scale, scale, scale));
32002 * Calculate a transformation matrix from normalized coordinates for
32003 * texture map coordinates.
32005 * @returns {THREE.Matrix4} Normalized coordinates to texture map
32006 * coordinates transformation matrix.
32008 Transform.prototype._normalizedToTextureMatrix = function () {
32009 var size = Math.max(this._width, this._height);
32010 var w = size / this._width;
32011 var h = size / this._height;
32012 switch (this._orientation) {
32014 return new THREE.Matrix4().set(w, 0, 0, 0.5, 0, -h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
32016 return new THREE.Matrix4().set(-w, 0, 0, 0.5, 0, h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
32018 return new THREE.Matrix4().set(0, -h, 0, 0.5, -w, 0, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
32020 return new THREE.Matrix4().set(0, h, 0, 0.5, w, 0, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
32022 return new THREE.Matrix4().set(w, 0, 0, 0.5, 0, -h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
32027 exports.Transform = Transform;
32029 },{"three":176}],316:[function(require,module,exports){
32031 /// <reference path="../../typings/index.d.ts" />
32032 Object.defineProperty(exports, "__esModule", { value: true });
32033 var THREE = require("three");
32035 * @class ViewportCoords
32037 * @classdesc Provides methods for calculating 2D coordinate conversions
32038 * as well as 3D projection and unprojection.
32040 * Basic coordinates are 2D coordinates on the [0, 1] interval and
32041 * have the origin point, (0, 0), at the top left corner and the
32042 * maximum value, (1, 1), at the bottom right corner of the original
32045 * Viewport coordinates are 2D coordinates on the [-1, 1] interval and
32046 * have the origin point in the center. The bottom left corner point is
32047 * (-1, -1) and the top right corner point is (1, 1).
32049 * Canvas coordiantes are 2D pixel coordinates on the [0, canvasWidth] and
32050 * [0, canvasHeight] intervals. The origin point (0, 0) is in the top left
32051 * corner and the maximum value is (canvasWidth, canvasHeight) is in the
32052 * bottom right corner.
32054 * 3D coordinates are in the topocentric world reference frame.
32056 var ViewportCoords = (function () {
32057 function ViewportCoords() {
32058 this._unprojectDepth = 200;
32061 * Convert basic coordinates to canvas coordinates.
32063 * @description Transform origin and camera position needs to be the
32064 * equal for reliable return value.
32066 * @param {number} basicX - Basic X coordinate.
32067 * @param {number} basicY - Basic Y coordinate.
32068 * @param {HTMLElement} container - The viewer container.
32069 * @param {Transform} transform - Transform of the node to unproject from.
32070 * @param {THREE.Camera} camera - Camera used in rendering.
32071 * @returns {Array<number>} 2D canvas coordinates.
32073 ViewportCoords.prototype.basicToCanvas = function (basicX, basicY, container, transform, camera) {
32074 var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
32075 var canvas = this.projectToCanvas(point3d, container, camera);
32079 * Convert basic coordinates to canvas coordinates safely. If 3D point is
32080 * behind camera null will be returned.
32082 * @description Transform origin and camera position needs to be the
32083 * equal for reliable return value.
32085 * @param {number} basicX - Basic X coordinate.
32086 * @param {number} basicY - Basic Y coordinate.
32087 * @param {HTMLElement} container - The viewer container.
32088 * @param {Transform} transform - Transform of the node to unproject from.
32089 * @param {THREE.Camera} camera - Camera used in rendering.
32090 * @returns {Array<number>} 2D canvas coordinates if the basic point represents a 3D point
32091 * in front of the camera, otherwise null.
32093 ViewportCoords.prototype.basicToCanvasSafe = function (basicX, basicY, container, transform, camera) {
32094 var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
32095 var pointCamera = this.worldToCamera(point3d, camera);
32096 if (pointCamera[2] > 0) {
32099 var _a = this.cameraToViewport(pointCamera, camera), viewportX = _a[0], viewportY = _a[1];
32100 var canvas = this.viewportToCanvas(viewportX, viewportY, container);
32104 * Convert basic coordinates to viewport coordinates.
32106 * @description Transform origin and camera position needs to be the
32107 * equal for reliable return value.
32109 * @param {number} basicX - Basic X coordinate.
32110 * @param {number} basicY - Basic Y coordinate.
32111 * @param {Transform} transform - Transform of the node to unproject from.
32112 * @param {THREE.Camera} camera - Camera used in rendering.
32113 * @returns {Array<number>} 2D viewport coordinates.
32115 ViewportCoords.prototype.basicToViewport = function (basicX, basicY, transform, camera) {
32116 var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
32117 var viewport = this.projectToViewport(point3d, camera);
32121 * Convert camera 3D coordinates to viewport coordinates.
32123 * @param {number} pointCamera - 3D point in camera coordinate system.
32124 * @param {THREE.Camera} camera - Camera used in rendering.
32125 * @returns {Array<number>} 2D viewport coordinates.
32127 ViewportCoords.prototype.cameraToViewport = function (pointCamera, camera) {
32128 var viewport = new THREE.Vector3().fromArray(pointCamera)
32129 .applyMatrix4(camera.projectionMatrix);
32130 return [viewport.x, viewport.y];
32133 * Get canvas pixel position from event.
32135 * @param {Event} event - Event containing clientX and clientY properties.
32136 * @param {HTMLElement} element - HTML element.
32137 * @returns {Array<number>} 2D canvas coordinates.
32139 ViewportCoords.prototype.canvasPosition = function (event, element) {
32140 var clientRect = element.getBoundingClientRect();
32141 var canvasX = event.clientX - clientRect.left - element.clientLeft;
32142 var canvasY = event.clientY - clientRect.top - element.clientTop;
32143 return [canvasX, canvasY];
32146 * Convert canvas coordinates to basic coordinates.
32148 * @description Transform origin and camera position needs to be the
32149 * equal for reliable return value.
32151 * @param {number} canvasX - Canvas X coordinate.
32152 * @param {number} canvasY - Canvas Y coordinate.
32153 * @param {HTMLElement} container - The viewer container.
32154 * @param {Transform} transform - Transform of the node to unproject from.
32155 * @param {THREE.Camera} camera - Camera used in rendering.
32156 * @returns {Array<number>} 2D basic coordinates.
32158 ViewportCoords.prototype.canvasToBasic = function (canvasX, canvasY, container, transform, camera) {
32159 var point3d = this.unprojectFromCanvas(canvasX, canvasY, container, camera)
32161 var basic = transform.projectBasic(point3d);
32165 * Convert canvas coordinates to viewport coordinates.
32167 * @param {number} canvasX - Canvas X coordinate.
32168 * @param {number} canvasY - Canvas Y coordinate.
32169 * @param {HTMLElement} container - The viewer container.
32170 * @returns {Array<number>} 2D viewport coordinates.
32172 ViewportCoords.prototype.canvasToViewport = function (canvasX, canvasY, container) {
32173 var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
32174 var viewportX = 2 * canvasX / canvasWidth - 1;
32175 var viewportY = 1 - 2 * canvasY / canvasHeight;
32176 return [viewportX, viewportY];
32179 * Determines the width and height of the container in canvas coordinates.
32181 * @param {HTMLElement} container - The viewer container.
32182 * @returns {Array<number>} 2D canvas coordinates.
32184 ViewportCoords.prototype.containerToCanvas = function (container) {
32185 return [container.offsetWidth, container.offsetHeight];
32188 * Determine basic distances from image to canvas corners.
32190 * @description Transform origin and camera position needs to be the
32191 * equal for reliable return value.
32193 * Determines the smallest basic distance for every side of the canvas.
32195 * @param {Transform} transform - Transform of the node to unproject from.
32196 * @param {THREE.Camera} camera - Camera used in rendering.
32197 * @returns {Array<number>} Array of basic distances as [top, right, bottom, left].
32199 ViewportCoords.prototype.getBasicDistances = function (transform, camera) {
32200 var topLeftBasic = this.viewportToBasic(-1, 1, transform, camera);
32201 var topRightBasic = this.viewportToBasic(1, 1, transform, camera);
32202 var bottomRightBasic = this.viewportToBasic(1, -1, transform, camera);
32203 var bottomLeftBasic = this.viewportToBasic(-1, -1, transform, camera);
32204 var topBasicDistance = 0;
32205 var rightBasicDistance = 0;
32206 var bottomBasicDistance = 0;
32207 var leftBasicDistance = 0;
32208 if (topLeftBasic[1] < 0 && topRightBasic[1] < 0) {
32209 topBasicDistance = topLeftBasic[1] > topRightBasic[1] ?
32213 if (topRightBasic[0] > 1 && bottomRightBasic[0] > 1) {
32214 rightBasicDistance = topRightBasic[0] < bottomRightBasic[0] ?
32215 topRightBasic[0] - 1 :
32216 bottomRightBasic[0] - 1;
32218 if (bottomRightBasic[1] > 1 && bottomLeftBasic[1] > 1) {
32219 bottomBasicDistance = bottomRightBasic[1] < bottomLeftBasic[1] ?
32220 bottomRightBasic[1] - 1 :
32221 bottomLeftBasic[1] - 1;
32223 if (bottomLeftBasic[0] < 0 && topLeftBasic[0] < 0) {
32224 leftBasicDistance = bottomLeftBasic[0] > topLeftBasic[0] ?
32225 -bottomLeftBasic[0] :
32228 return [topBasicDistance, rightBasicDistance, bottomBasicDistance, leftBasicDistance];
32231 * Determine pixel distances from image to canvas corners.
32233 * @description Transform origin and camera position needs to be the
32234 * equal for reliable return value.
32236 * Determines the smallest pixel distance for every side of the canvas.
32238 * @param {HTMLElement} container - The viewer container.
32239 * @param {Transform} transform - Transform of the node to unproject from.
32240 * @param {THREE.Camera} camera - Camera used in rendering.
32241 * @returns {Array<number>} Array of pixel distances as [top, right, bottom, left].
32243 ViewportCoords.prototype.getPixelDistances = function (container, transform, camera) {
32244 var topLeftBasic = this.viewportToBasic(-1, 1, transform, camera);
32245 var topRightBasic = this.viewportToBasic(1, 1, transform, camera);
32246 var bottomRightBasic = this.viewportToBasic(1, -1, transform, camera);
32247 var bottomLeftBasic = this.viewportToBasic(-1, -1, transform, camera);
32248 var topPixelDistance = 0;
32249 var rightPixelDistance = 0;
32250 var bottomPixelDistance = 0;
32251 var leftPixelDistance = 0;
32252 var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
32253 if (topLeftBasic[1] < 0 && topRightBasic[1] < 0) {
32254 var basicX = topLeftBasic[1] > topRightBasic[1] ?
32257 var canvas = this.basicToCanvas(basicX, 0, container, transform, camera);
32258 topPixelDistance = canvas[1] > 0 ? canvas[1] : 0;
32260 if (topRightBasic[0] > 1 && bottomRightBasic[0] > 1) {
32261 var basicY = topRightBasic[0] < bottomRightBasic[0] ?
32263 bottomRightBasic[1];
32264 var canvas = this.basicToCanvas(1, basicY, container, transform, camera);
32265 rightPixelDistance = canvas[0] < canvasWidth ? canvasWidth - canvas[0] : 0;
32267 if (bottomRightBasic[1] > 1 && bottomLeftBasic[1] > 1) {
32268 var basicX = bottomRightBasic[1] < bottomLeftBasic[1] ?
32269 bottomRightBasic[0] :
32270 bottomLeftBasic[0];
32271 var canvas = this.basicToCanvas(basicX, 1, container, transform, camera);
32272 bottomPixelDistance = canvas[1] < canvasHeight ? canvasHeight - canvas[1] : 0;
32274 if (bottomLeftBasic[0] < 0 && topLeftBasic[0] < 0) {
32275 var basicY = bottomLeftBasic[0] > topLeftBasic[0] ?
32276 bottomLeftBasic[1] :
32278 var canvas = this.basicToCanvas(0, basicY, container, transform, camera);
32279 leftPixelDistance = canvas[0] > 0 ? canvas[0] : 0;
32281 return [topPixelDistance, rightPixelDistance, bottomPixelDistance, leftPixelDistance];
32284 * Determine if an event occured inside an element.
32286 * @param {Event} event - Event containing clientX and clientY properties.
32287 * @param {HTMLElement} element - HTML element.
32288 * @returns {boolean} Value indicating if the event occured inside the element or not.
32290 ViewportCoords.prototype.insideElement = function (event, element) {
32291 var clientRect = element.getBoundingClientRect();
32292 var minX = clientRect.left + element.clientLeft;
32293 var maxX = minX + element.clientWidth;
32294 var minY = clientRect.top + element.clientTop;
32295 var maxY = minY + element.clientHeight;
32296 return event.clientX > minX &&
32297 event.clientX < maxX &&
32298 event.clientY > minY &&
32299 event.clientY < maxY;
32302 * Project 3D world coordinates to canvas coordinates.
32304 * @param {Array<number>} point3D - 3D world coordinates.
32305 * @param {HTMLElement} container - The viewer container.
32306 * @param {THREE.Camera} camera - Camera used in rendering.
32307 * @returns {Array<number>} 2D canvas coordinates.
32309 ViewportCoords.prototype.projectToCanvas = function (point3d, container, camera) {
32310 var viewport = this.projectToViewport(point3d, camera);
32311 var canvas = this.viewportToCanvas(viewport[0], viewport[1], container);
32315 * Project 3D world coordinates to viewport coordinates.
32317 * @param {Array<number>} point3D - 3D world coordinates.
32318 * @param {THREE.Camera} camera - Camera used in rendering.
32319 * @returns {Array<number>} 2D viewport coordinates.
32321 ViewportCoords.prototype.projectToViewport = function (point3d, camera) {
32322 var viewport = new THREE.Vector3(point3d[0], point3d[1], point3d[2])
32324 return [viewport.x, viewport.y];
32327 * Uproject canvas coordinates to 3D world coordinates.
32329 * @param {number} canvasX - Canvas X coordinate.
32330 * @param {number} canvasY - Canvas Y coordinate.
32331 * @param {HTMLElement} container - The viewer container.
32332 * @param {THREE.Camera} camera - Camera used in rendering.
32333 * @returns {Array<number>} 3D world coordinates.
32335 ViewportCoords.prototype.unprojectFromCanvas = function (canvasX, canvasY, container, camera) {
32336 var viewport = this.canvasToViewport(canvasX, canvasY, container);
32337 var point3d = this.unprojectFromViewport(viewport[0], viewport[1], camera);
32341 * Unproject viewport coordinates to 3D world coordinates.
32343 * @param {number} viewportX - Viewport X coordinate.
32344 * @param {number} viewportY - Viewport Y coordinate.
32345 * @param {THREE.Camera} camera - Camera used in rendering.
32346 * @returns {Array<number>} 3D world coordinates.
32348 ViewportCoords.prototype.unprojectFromViewport = function (viewportX, viewportY, camera) {
32349 var point3d = new THREE.Vector3(viewportX, viewportY, 1)
32350 .unproject(camera);
32354 * Convert viewport coordinates to basic coordinates.
32356 * @description Transform origin and camera position needs to be the
32357 * equal for reliable return value.
32359 * @param {number} viewportX - Viewport X coordinate.
32360 * @param {number} viewportY - Viewport Y coordinate.
32361 * @param {Transform} transform - Transform of the node to unproject from.
32362 * @param {THREE.Camera} camera - Camera used in rendering.
32363 * @returns {Array<number>} 2D basic coordinates.
32365 ViewportCoords.prototype.viewportToBasic = function (viewportX, viewportY, transform, camera) {
32366 var point3d = new THREE.Vector3(viewportX, viewportY, 1)
32369 var basic = transform.projectBasic(point3d);
32373 * Convert viewport coordinates to canvas coordinates.
32375 * @param {number} viewportX - Viewport X coordinate.
32376 * @param {number} viewportY - Viewport Y coordinate.
32377 * @param {HTMLElement} container - The viewer container.
32378 * @returns {Array<number>} 2D canvas coordinates.
32380 ViewportCoords.prototype.viewportToCanvas = function (viewportX, viewportY, container) {
32381 var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
32382 var canvasX = canvasWidth * (viewportX + 1) / 2;
32383 var canvasY = -canvasHeight * (viewportY - 1) / 2;
32384 return [canvasX, canvasY];
32387 * Convert 3D world coordinates to 3D camera coordinates.
32389 * @param {number} point3D - 3D point in world coordinate system.
32390 * @param {THREE.Camera} camera - Camera used in rendering.
32391 * @returns {Array<number>} 3D camera coordinates.
32393 ViewportCoords.prototype.worldToCamera = function (point3d, camera) {
32394 var pointCamera = new THREE.Vector3(point3d[0], point3d[1], point3d[2])
32395 .applyMatrix4(camera.matrixWorldInverse);
32396 return pointCamera.toArray();
32398 return ViewportCoords;
32400 exports.ViewportCoords = ViewportCoords;
32401 exports.default = ViewportCoords;
32403 },{"three":176}],317:[function(require,module,exports){
32405 Object.defineProperty(exports, "__esModule", { value: true });
32409 * @classdesc Represents a class for creating node filters. Implementation and
32410 * definitions based on https://github.com/mapbox/feature-filter.
32412 var FilterCreator = (function () {
32413 function FilterCreator() {
32416 * Create a filter from a filter expression.
32418 * @description The following filters are supported:
32435 * @param {FilterExpression} filter - Comparison, set membership or combinding filter
32437 * @returns {FilterFunction} Function taking a node and returning a boolean that
32438 * indicates whether the node passed the test or not.
32440 FilterCreator.prototype.createFilter = function (filter) {
32441 return new Function("node", "return " + this._compile(filter) + ";");
32443 FilterCreator.prototype._compile = function (filter) {
32444 if (filter == null || filter.length <= 1) {
32447 var operator = filter[0];
32448 var operation = operator === "==" ? this._compileComparisonOp("===", filter[1], filter[2], false) :
32449 operator === "!=" ? this._compileComparisonOp("!==", filter[1], filter[2], false) :
32450 operator === ">" ||
32451 operator === ">=" ||
32452 operator === "<" ||
32453 operator === "<=" ? this._compileComparisonOp(operator, filter[1], filter[2], true) :
32454 operator === "in" ?
32455 this._compileInOp(filter[1], filter.slice(2)) :
32456 operator === "!in" ?
32457 this._compileNegation(this._compileInOp(filter[1], filter.slice(2))) :
32458 operator === "all" ? this._compileLogicalOp(filter.slice(1), "&&") :
32460 return "(" + operation + ")";
32462 FilterCreator.prototype._compare = function (a, b) {
32463 return a < b ? -1 : a > b ? 1 : 0;
32465 FilterCreator.prototype._compileComparisonOp = function (operator, property, value, checkType) {
32466 var left = this._compilePropertyReference(property);
32467 var right = JSON.stringify(value);
32468 return (checkType ? "typeof " + left + "===typeof " + right + "&&" : "") + left + operator + right;
32470 FilterCreator.prototype._compileInOp = function (property, values) {
32471 var compare = this._compare;
32472 var left = JSON.stringify(values.sort(compare));
32473 var right = this._compilePropertyReference(property);
32474 return left + ".indexOf(" + right + ")!==-1";
32476 FilterCreator.prototype._compileLogicalOp = function (filters, operator) {
32477 var compile = this._compile.bind(this);
32478 return filters.map(compile).join(operator);
32480 FilterCreator.prototype._compileNegation = function (expression) {
32481 return "!(" + expression + ")";
32483 FilterCreator.prototype._compilePropertyReference = function (property) {
32484 return "node[" + JSON.stringify(property) + "]";
32486 return FilterCreator;
32488 exports.FilterCreator = FilterCreator;
32489 exports.default = FilterCreator;
32491 },{}],318:[function(require,module,exports){
32493 /// <reference path="../../typings/index.d.ts" />
32494 Object.defineProperty(exports, "__esModule", { value: true });
32495 var rbush = require("rbush");
32496 var Subject_1 = require("rxjs/Subject");
32497 require("rxjs/add/observable/from");
32498 require("rxjs/add/operator/catch");
32499 require("rxjs/add/operator/do");
32500 require("rxjs/add/operator/finally");
32501 require("rxjs/add/operator/map");
32502 require("rxjs/add/operator/publish");
32503 var Edge_1 = require("../Edge");
32504 var Error_1 = require("../Error");
32505 var Graph_1 = require("../Graph");
32509 * @classdesc Represents a graph of nodes with edges.
32511 var Graph = (function () {
32513 * Create a new graph instance.
32515 * @param {APIv3} [apiV3] - API instance for retrieving data.
32516 * @param {rbush.RBush<NodeIndexItem>} [nodeIndex] - Node index for fast spatial retreival.
32517 * @param {GraphCalculator} [graphCalculator] - Instance for graph calculations.
32518 * @param {EdgeCalculator} [edgeCalculator] - Instance for edge calculations.
32519 * @param {FilterCreator} [filterCreator] - Instance for filter creation.
32520 * @param {IGraphConfiguration} [configuration] - Configuration struct.
32522 function Graph(apiV3, nodeIndex, graphCalculator, edgeCalculator, filterCreator, configuration) {
32523 this._apiV3 = apiV3;
32524 this._cachedNodes = {};
32525 this._cachedNodeTiles = {};
32526 this._cachedSpatialEdges = {};
32527 this._cachedTiles = {};
32528 this._cachingFill$ = {};
32529 this._cachingFull$ = {};
32530 this._cachingSequences$ = {};
32531 this._cachingSpatialArea$ = {};
32532 this._cachingTiles$ = {};
32533 this._changed$ = new Subject_1.Subject();
32534 this._defaultAlt = 2;
32535 this._edgeCalculator = edgeCalculator != null ? edgeCalculator : new Edge_1.EdgeCalculator();
32536 this._filterCreator = filterCreator != null ? filterCreator : new Graph_1.FilterCreator();
32537 this._filter = this._filterCreator.createFilter(undefined);
32538 this._graphCalculator = graphCalculator != null ? graphCalculator : new Graph_1.GraphCalculator();
32539 this._configuration = configuration != null ?
32543 maxUnusedNodes: 100,
32544 maxUnusedTiles: 20,
32547 this._nodeIndex = nodeIndex != null ? nodeIndex : rbush(16, [".lat", ".lon", ".lat", ".lon"]);
32548 this._nodeIndexTiles = {};
32549 this._nodeToTile = {};
32550 this._preStored = {};
32551 this._requiredNodeTiles = {};
32552 this._requiredSpatialArea = {};
32553 this._sequences = {};
32554 this._tilePrecision = 7;
32555 this._tileThreshold = 20;
32557 Object.defineProperty(Graph.prototype, "changed$", {
32561 * @returns {Observable<Graph>} Observable emitting
32562 * the graph every time it has changed.
32565 return this._changed$;
32571 * Retrieve and cache node fill properties.
32573 * @param {string} key - Key of node to fill.
32574 * @returns {Observable<Graph>} Observable emitting the graph
32575 * when the node has been updated.
32576 * @throws {GraphMapillaryError} When the operation is not valid on the
32579 Graph.prototype.cacheFill$ = function (key) {
32581 if (key in this._cachingFull$) {
32582 throw new Error_1.GraphMapillaryError("Cannot fill node while caching full (" + key + ").");
32584 if (!this.hasNode(key)) {
32585 throw new Error_1.GraphMapillaryError("Cannot fill node that does not exist in graph (" + key + ").");
32587 if (key in this._cachingFill$) {
32588 return this._cachingFill$[key];
32590 var node = this.getNode(key);
32592 throw new Error_1.GraphMapillaryError("Cannot fill node that is already full (" + key + ").");
32594 this._cachingFill$[key] = this._apiV3.imageByKeyFill$([key])
32595 .do(function (imageByKeyFill) {
32597 _this._makeFull(node, imageByKeyFill[key]);
32599 delete _this._cachingFill$[key];
32601 .map(function (imageByKeyFill) {
32604 .finally(function () {
32605 if (key in _this._cachingFill$) {
32606 delete _this._cachingFill$[key];
32608 _this._changed$.next(_this);
32612 return this._cachingFill$[key];
32615 * Retrieve and cache full node properties.
32617 * @param {string} key - Key of node to fill.
32618 * @returns {Observable<Graph>} Observable emitting the graph
32619 * when the node has been updated.
32620 * @throws {GraphMapillaryError} When the operation is not valid on the
32623 Graph.prototype.cacheFull$ = function (key) {
32625 if (key in this._cachingFull$) {
32626 return this._cachingFull$[key];
32628 if (this.hasNode(key)) {
32629 throw new Error_1.GraphMapillaryError("Cannot cache full node that already exist in graph (" + key + ").");
32631 this._cachingFull$[key] = this._apiV3.imageByKeyFull$([key])
32632 .do(function (imageByKeyFull) {
32633 var fn = imageByKeyFull[key];
32634 if (_this.hasNode(key)) {
32635 var node = _this.getNode(key);
32637 _this._makeFull(node, fn);
32641 if (fn.sequence == null || fn.sequence.key == null) {
32642 throw new Error_1.GraphMapillaryError("Node has no sequence (" + key + ").");
32644 var node = new Graph_1.Node(fn);
32645 _this._makeFull(node, fn);
32646 var h = _this._graphCalculator.encodeH(node.originalLatLon, _this._tilePrecision);
32647 _this._preStore(h, node);
32648 _this._setNode(node);
32649 delete _this._cachingFull$[key];
32652 .map(function (imageByKeyFull) {
32655 .finally(function () {
32656 if (key in _this._cachingFull$) {
32657 delete _this._cachingFull$[key];
32659 _this._changed$.next(_this);
32663 return this._cachingFull$[key];
32666 * Retrieve and cache a node sequence.
32668 * @param {string} key - Key of node for which to retrieve sequence.
32669 * @returns {Observable<Graph>} Observable emitting the graph
32670 * when the sequence has been retrieved.
32671 * @throws {GraphMapillaryError} When the operation is not valid on the
32674 Graph.prototype.cacheNodeSequence$ = function (key) {
32675 if (!this.hasNode(key)) {
32676 throw new Error_1.GraphMapillaryError("Cannot cache sequence edges of node that does not exist in graph (" + key + ").");
32678 var node = this.getNode(key);
32679 if (node.sequenceKey in this._sequences) {
32680 throw new Error_1.GraphMapillaryError("Sequence already cached (" + key + "), (" + node.sequenceKey + ").");
32682 return this._cacheSequence$(node.sequenceKey);
32685 * Retrieve and cache a sequence.
32687 * @param {string} sequenceKey - Key of sequence to cache.
32688 * @returns {Observable<Graph>} Observable emitting the graph
32689 * when the sequence has been retrieved.
32690 * @throws {GraphMapillaryError} When the operation is not valid on the
32693 Graph.prototype.cacheSequence$ = function (sequenceKey) {
32694 if (sequenceKey in this._sequences) {
32695 throw new Error_1.GraphMapillaryError("Sequence already cached (" + sequenceKey + ")");
32697 return this._cacheSequence$(sequenceKey);
32700 * Cache sequence edges for a node.
32702 * @param {string} key - Key of node.
32703 * @throws {GraphMapillaryError} When the operation is not valid on the
32706 Graph.prototype.cacheSequenceEdges = function (key) {
32707 var node = this.getNode(key);
32708 if (!(node.sequenceKey in this._sequences)) {
32709 throw new Error_1.GraphMapillaryError("Sequence is not cached (" + key + "), (" + node.sequenceKey + ")");
32711 var sequence = this._sequences[node.sequenceKey].sequence;
32712 var edges = this._edgeCalculator.computeSequenceEdges(node, sequence);
32713 node.cacheSequenceEdges(edges);
32716 * Retrieve and cache full nodes for a node spatial area.
32718 * @param {string} key - Key of node for which to retrieve sequence.
32719 * @returns {Observable<Graph>} Observable emitting the graph
32720 * when the nodes in the spatial area has been made full.
32721 * @throws {GraphMapillaryError} When the operation is not valid on the
32724 Graph.prototype.cacheSpatialArea$ = function (key) {
32726 if (!this.hasNode(key)) {
32727 throw new Error_1.GraphMapillaryError("Cannot cache spatial area of node that does not exist in graph (" + key + ").");
32729 if (key in this._cachedSpatialEdges) {
32730 throw new Error_1.GraphMapillaryError("Node already spatially cached (" + key + ").");
32732 if (!(key in this._requiredSpatialArea)) {
32733 throw new Error_1.GraphMapillaryError("Spatial area not determined (" + key + ").");
32735 var spatialArea = this._requiredSpatialArea[key];
32736 if (Object.keys(spatialArea.cacheNodes).length === 0) {
32737 throw new Error_1.GraphMapillaryError("Spatial nodes already cached (" + key + ").");
32739 if (key in this._cachingSpatialArea$) {
32740 return this._cachingSpatialArea$[key];
32743 while (spatialArea.cacheKeys.length > 0) {
32744 batches.push(spatialArea.cacheKeys.splice(0, 200));
32746 var batchesToCache = batches.length;
32747 var spatialNodes$ = [];
32748 var _loop_1 = function (batch) {
32749 var spatialNodeBatch$ = this_1._apiV3.imageByKeyFill$(batch)
32750 .do(function (imageByKeyFill) {
32751 for (var fillKey in imageByKeyFill) {
32752 if (!imageByKeyFill.hasOwnProperty(fillKey)) {
32755 var spatialNode = spatialArea.cacheNodes[fillKey];
32756 if (spatialNode.full) {
32757 delete spatialArea.cacheNodes[fillKey];
32760 var fillNode = imageByKeyFill[fillKey];
32761 _this._makeFull(spatialNode, fillNode);
32762 delete spatialArea.cacheNodes[fillKey];
32764 if (--batchesToCache === 0) {
32765 delete _this._cachingSpatialArea$[key];
32768 .map(function (imageByKeyFill) {
32771 .catch(function (error) {
32772 for (var _i = 0, batch_1 = batch; _i < batch_1.length; _i++) {
32773 var batchKey = batch_1[_i];
32774 if (batchKey in spatialArea.all) {
32775 delete spatialArea.all[batchKey];
32777 if (batchKey in spatialArea.cacheNodes) {
32778 delete spatialArea.cacheNodes[batchKey];
32781 if (--batchesToCache === 0) {
32782 delete _this._cachingSpatialArea$[key];
32786 .finally(function () {
32787 if (Object.keys(spatialArea.cacheNodes).length === 0) {
32788 _this._changed$.next(_this);
32793 spatialNodes$.push(spatialNodeBatch$);
32796 for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {
32797 var batch = batches_1[_i];
32800 this._cachingSpatialArea$[key] = spatialNodes$;
32801 return spatialNodes$;
32804 * Cache spatial edges for a node.
32806 * @param {string} key - Key of node.
32807 * @throws {GraphMapillaryError} When the operation is not valid on the
32810 Graph.prototype.cacheSpatialEdges = function (key) {
32811 if (key in this._cachedSpatialEdges) {
32812 throw new Error_1.GraphMapillaryError("Spatial edges already cached (" + key + ").");
32814 var node = this.getNode(key);
32815 var sequence = this._sequences[node.sequenceKey].sequence;
32816 var fallbackKeys = [];
32817 var prevKey = sequence.findPrevKey(node.key);
32818 if (prevKey != null) {
32819 fallbackKeys.push(prevKey);
32821 var nextKey = sequence.findNextKey(node.key);
32822 if (nextKey != null) {
32823 fallbackKeys.push(nextKey);
32825 var allSpatialNodes = this._requiredSpatialArea[key].all;
32826 var potentialNodes = [];
32827 var filter = this._filter;
32828 for (var spatialNodeKey in allSpatialNodes) {
32829 if (!allSpatialNodes.hasOwnProperty(spatialNodeKey)) {
32832 var spatialNode = allSpatialNodes[spatialNodeKey];
32833 if (filter(spatialNode)) {
32834 potentialNodes.push(spatialNode);
32837 var potentialEdges = this._edgeCalculator.getPotentialEdges(node, potentialNodes, fallbackKeys);
32838 var edges = this._edgeCalculator.computeStepEdges(node, potentialEdges, prevKey, nextKey);
32839 edges = edges.concat(this._edgeCalculator.computeTurnEdges(node, potentialEdges));
32840 edges = edges.concat(this._edgeCalculator.computePanoEdges(node, potentialEdges));
32841 edges = edges.concat(this._edgeCalculator.computePerspectiveToPanoEdges(node, potentialEdges));
32842 edges = edges.concat(this._edgeCalculator.computeSimilarEdges(node, potentialEdges));
32843 node.cacheSpatialEdges(edges);
32844 this._cachedSpatialEdges[key] = node;
32845 delete this._requiredSpatialArea[key];
32846 delete this._cachedNodeTiles[key];
32849 * Retrieve and cache geohash tiles for a node.
32851 * @param {string} key - Key of node for which to retrieve tiles.
32852 * @returns {Observable<Graph>} Observable emitting the graph
32853 * when the tiles required for the node has been cached.
32854 * @throws {GraphMapillaryError} When the operation is not valid on the
32857 Graph.prototype.cacheTiles$ = function (key) {
32859 if (key in this._cachedNodeTiles) {
32860 throw new Error_1.GraphMapillaryError("Tiles already cached (" + key + ").");
32862 if (key in this._cachedSpatialEdges) {
32863 throw new Error_1.GraphMapillaryError("Spatial edges already cached so tiles considered cached (" + key + ").");
32865 if (!(key in this._requiredNodeTiles)) {
32866 throw new Error_1.GraphMapillaryError("Tiles have not been determined (" + key + ").");
32868 var nodeTiles = this._requiredNodeTiles[key];
32869 if (nodeTiles.cache.length === 0 &&
32870 nodeTiles.caching.length === 0) {
32871 throw new Error_1.GraphMapillaryError("Tiles already cached (" + key + ").");
32873 if (!this.hasNode(key)) {
32874 throw new Error_1.GraphMapillaryError("Cannot cache tiles of node that does not exist in graph (" + key + ").");
32876 var hs = nodeTiles.cache.slice();
32877 nodeTiles.caching = this._requiredNodeTiles[key].caching.concat(hs);
32878 nodeTiles.cache = [];
32879 var cacheTiles$ = [];
32880 var _loop_2 = function (h) {
32881 var cacheTile$ = null;
32882 if (h in this_2._cachingTiles$) {
32883 cacheTile$ = this_2._cachingTiles$[h];
32886 cacheTile$ = this_2._apiV3.imagesByH$([h])
32887 .do(function (imagesByH) {
32888 var coreNodes = imagesByH[h];
32889 if (h in _this._cachedTiles) {
32892 _this._nodeIndexTiles[h] = [];
32893 _this._cachedTiles[h] = { accessed: new Date().getTime(), nodes: [] };
32894 var hCache = _this._cachedTiles[h].nodes;
32895 var preStored = _this._removeFromPreStore(h);
32896 for (var index in coreNodes) {
32897 if (!coreNodes.hasOwnProperty(index)) {
32900 var coreNode = coreNodes[index];
32901 if (coreNode == null) {
32904 if (coreNode.sequence == null ||
32905 coreNode.sequence.key == null) {
32906 console.warn("Sequence missing, discarding (" + coreNode.key + ")");
32909 if (preStored != null && coreNode.key in preStored) {
32910 var node_1 = preStored[coreNode.key];
32911 delete preStored[coreNode.key];
32912 hCache.push(node_1);
32913 var nodeIndexItem_1 = {
32914 lat: node_1.latLon.lat,
32915 lon: node_1.latLon.lon,
32918 _this._nodeIndex.insert(nodeIndexItem_1);
32919 _this._nodeIndexTiles[h].push(nodeIndexItem_1);
32920 _this._nodeToTile[node_1.key] = h;
32923 var node = new Graph_1.Node(coreNode);
32925 var nodeIndexItem = {
32926 lat: node.latLon.lat,
32927 lon: node.latLon.lon,
32930 _this._nodeIndex.insert(nodeIndexItem);
32931 _this._nodeIndexTiles[h].push(nodeIndexItem);
32932 _this._nodeToTile[node.key] = h;
32933 _this._setNode(node);
32935 delete _this._cachingTiles$[h];
32937 .map(function (imagesByH) {
32940 .catch(function (error) {
32941 delete _this._cachingTiles$[h];
32946 this_2._cachingTiles$[h] = cacheTile$;
32948 cacheTiles$.push(cacheTile$
32949 .do(function (graph) {
32950 var index = nodeTiles.caching.indexOf(h);
32952 nodeTiles.caching.splice(index, 1);
32954 if (nodeTiles.caching.length === 0 &&
32955 nodeTiles.cache.length === 0) {
32956 delete _this._requiredNodeTiles[key];
32957 _this._cachedNodeTiles[key] = true;
32960 .catch(function (error) {
32961 var index = nodeTiles.caching.indexOf(h);
32963 nodeTiles.caching.splice(index, 1);
32965 if (nodeTiles.caching.length === 0 &&
32966 nodeTiles.cache.length === 0) {
32967 delete _this._requiredNodeTiles[key];
32968 _this._cachedNodeTiles[key] = true;
32972 .finally(function () {
32973 _this._changed$.next(_this);
32979 for (var _i = 0, _a = nodeTiles.caching; _i < _a.length; _i++) {
32983 return cacheTiles$;
32986 * Initialize the cache for a node.
32988 * @param {string} key - Key of node.
32989 * @throws {GraphMapillaryError} When the operation is not valid on the
32992 Graph.prototype.initializeCache = function (key) {
32993 if (key in this._cachedNodes) {
32994 throw new Error_1.GraphMapillaryError("Node already in cache (" + key + ").");
32996 var node = this.getNode(key);
32997 node.initializeCache(new Graph_1.NodeCache());
32998 var accessed = new Date().getTime();
32999 this._cachedNodes[key] = { accessed: accessed, node: node };
33000 this._updateCachedTileAccess(key, accessed);
33003 * Get a value indicating if the graph is fill caching a node.
33005 * @param {string} key - Key of node.
33006 * @returns {boolean} Value indicating if the node is being fill cached.
33008 Graph.prototype.isCachingFill = function (key) {
33009 return key in this._cachingFill$;
33012 * Get a value indicating if the graph is fully caching a node.
33014 * @param {string} key - Key of node.
33015 * @returns {boolean} Value indicating if the node is being fully cached.
33017 Graph.prototype.isCachingFull = function (key) {
33018 return key in this._cachingFull$;
33021 * Get a value indicating if the graph is caching a sequence of a node.
33023 * @param {string} key - Key of node.
33024 * @returns {boolean} Value indicating if the sequence of a node is
33027 Graph.prototype.isCachingNodeSequence = function (key) {
33028 var node = this.getNode(key);
33029 return node.sequenceKey in this._cachingSequences$;
33032 * Get a value indicating if the graph is caching a sequence.
33034 * @param {string} sequenceKey - Key of sequence.
33035 * @returns {boolean} Value indicating if the sequence is
33038 Graph.prototype.isCachingSequence = function (sequenceKey) {
33039 return sequenceKey in this._cachingSequences$;
33042 * Get a value indicating if the graph is caching the tiles
33043 * required for calculating spatial edges of a node.
33045 * @param {string} key - Key of node.
33046 * @returns {boolean} Value indicating if the tiles of
33047 * a node are being cached.
33049 Graph.prototype.isCachingTiles = function (key) {
33050 return key in this._requiredNodeTiles &&
33051 this._requiredNodeTiles[key].cache.length === 0 &&
33052 this._requiredNodeTiles[key].caching.length > 0;
33055 * Get a value indicating if the cache has been initialized
33058 * @param {string} key - Key of node.
33059 * @returns {boolean} Value indicating if the cache has been
33060 * initialized for a node.
33062 Graph.prototype.hasInitializedCache = function (key) {
33063 return key in this._cachedNodes;
33066 * Get a value indicating if a node exist in the graph.
33068 * @param {string} key - Key of node.
33069 * @returns {boolean} Value indicating if a node exist in the graph.
33071 Graph.prototype.hasNode = function (key) {
33072 var accessed = new Date().getTime();
33073 this._updateCachedNodeAccess(key, accessed);
33074 this._updateCachedTileAccess(key, accessed);
33075 return key in this._nodes;
33078 * Get a value indicating if a node sequence exist in the graph.
33080 * @param {string} key - Key of node.
33081 * @returns {boolean} Value indicating if a node sequence exist
33084 Graph.prototype.hasNodeSequence = function (key) {
33085 var node = this.getNode(key);
33086 var sequenceKey = node.sequenceKey;
33087 var hasNodeSequence = sequenceKey in this._sequences;
33088 if (hasNodeSequence) {
33089 this._sequences[sequenceKey].accessed = new Date().getTime();
33091 return hasNodeSequence;
33094 * Get a value indicating if a sequence exist in the graph.
33096 * @param {string} sequenceKey - Key of sequence.
33097 * @returns {boolean} Value indicating if a sequence exist
33100 Graph.prototype.hasSequence = function (sequenceKey) {
33101 var hasSequence = sequenceKey in this._sequences;
33103 this._sequences[sequenceKey].accessed = new Date().getTime();
33105 return hasSequence;
33108 * Get a value indicating if the graph has fully cached
33109 * all nodes in the spatial area of a node.
33111 * @param {string} key - Key of node.
33112 * @returns {boolean} Value indicating if the spatial area
33113 * of a node has been cached.
33115 Graph.prototype.hasSpatialArea = function (key) {
33116 if (!this.hasNode(key)) {
33117 throw new Error_1.GraphMapillaryError("Spatial area nodes cannot be determined if node not in graph (" + key + ").");
33119 if (key in this._cachedSpatialEdges) {
33122 if (key in this._requiredSpatialArea) {
33123 return Object.keys(this._requiredSpatialArea[key].cacheNodes).length === 0;
33125 var node = this.getNode(key);
33126 var bbox = this._graphCalculator.boundingBoxCorners(node.latLon, this._tileThreshold);
33127 var spatialItems = this._nodeIndex.search({
33133 var spatialNodes = {
33138 for (var _i = 0, spatialItems_1 = spatialItems; _i < spatialItems_1.length; _i++) {
33139 var spatialItem = spatialItems_1[_i];
33140 spatialNodes.all[spatialItem.node.key] = spatialItem.node;
33141 if (!spatialItem.node.full) {
33142 spatialNodes.cacheKeys.push(spatialItem.node.key);
33143 spatialNodes.cacheNodes[spatialItem.node.key] = spatialItem.node;
33146 this._requiredSpatialArea[key] = spatialNodes;
33147 return spatialNodes.cacheKeys.length === 0;
33150 * Get a value indicating if the graph has a tiles required
33153 * @param {string} key - Key of node.
33154 * @returns {boolean} Value indicating if the the tiles required
33155 * by a node has been cached.
33157 Graph.prototype.hasTiles = function (key) {
33159 if (key in this._cachedNodeTiles) {
33162 if (key in this._cachedSpatialEdges) {
33165 if (!this.hasNode(key)) {
33166 throw new Error_1.GraphMapillaryError("Node does not exist in graph (" + key + ").");
33168 var nodeTiles = { cache: [], caching: [] };
33169 if (!(key in this._requiredNodeTiles)) {
33170 var node = this.getNode(key);
33171 nodeTiles.cache = this._graphCalculator
33172 .encodeHs(node.latLon, this._tilePrecision, this._tileThreshold)
33173 .filter(function (h) {
33174 return !(h in _this._cachedTiles);
33176 if (nodeTiles.cache.length > 0) {
33177 this._requiredNodeTiles[key] = nodeTiles;
33181 nodeTiles = this._requiredNodeTiles[key];
33183 return nodeTiles.cache.length === 0 && nodeTiles.caching.length === 0;
33188 * @param {string} key - Key of node.
33189 * @returns {Node} Retrieved node.
33191 Graph.prototype.getNode = function (key) {
33192 var accessed = new Date().getTime();
33193 this._updateCachedNodeAccess(key, accessed);
33194 this._updateCachedTileAccess(key, accessed);
33195 return this._nodes[key];
33200 * @param {string} sequenceKey - Key of sequence.
33201 * @returns {Node} Retrieved sequence.
33203 Graph.prototype.getSequence = function (sequenceKey) {
33204 var sequenceAccess = this._sequences[sequenceKey];
33205 sequenceAccess.accessed = new Date().getTime();
33206 return sequenceAccess.sequence;
33209 * Reset all spatial edges of the graph nodes.
33211 Graph.prototype.resetSpatialEdges = function () {
33212 var cachedKeys = Object.keys(this._cachedSpatialEdges);
33213 for (var _i = 0, cachedKeys_1 = cachedKeys; _i < cachedKeys_1.length; _i++) {
33214 var cachedKey = cachedKeys_1[_i];
33215 var node = this._cachedSpatialEdges[cachedKey];
33216 node.resetSpatialEdges();
33217 delete this._cachedSpatialEdges[cachedKey];
33221 * Reset the complete graph but keep the nodes corresponding
33222 * to the supplied keys. All other nodes will be disposed.
33224 * @param {Array<string>} keepKeys - Keys for nodes to keep
33225 * in graph after reset.
33227 Graph.prototype.reset = function (keepKeys) {
33229 for (var _i = 0, keepKeys_1 = keepKeys; _i < keepKeys_1.length; _i++) {
33230 var key = keepKeys_1[_i];
33231 if (!this.hasNode(key)) {
33232 throw new Error("Node does not exist " + key);
33234 var node = this.getNode(key);
33235 node.resetSequenceEdges();
33236 node.resetSpatialEdges();
33239 for (var _a = 0, _b = Object.keys(this._cachedNodes); _a < _b.length; _a++) {
33240 var cachedKey = _b[_a];
33241 if (keepKeys.indexOf(cachedKey) !== -1) {
33244 this._cachedNodes[cachedKey].node.dispose();
33245 delete this._cachedNodes[cachedKey];
33247 this._cachedNodeTiles = {};
33248 this._cachedSpatialEdges = {};
33249 this._cachedTiles = {};
33250 this._cachingFill$ = {};
33251 this._cachingFull$ = {};
33252 this._cachingSequences$ = {};
33253 this._cachingSpatialArea$ = {};
33254 this._cachingTiles$ = {};
33256 this._nodeToTile = {};
33257 this._preStored = {};
33258 for (var _c = 0, nodes_1 = nodes; _c < nodes_1.length; _c++) {
33259 var node = nodes_1[_c];
33260 this._nodes[node.key] = node;
33261 var h = this._graphCalculator.encodeH(node.originalLatLon, this._tilePrecision);
33262 this._preStore(h, node);
33264 this._requiredNodeTiles = {};
33265 this._requiredSpatialArea = {};
33266 this._sequences = {};
33267 this._nodeIndexTiles = {};
33268 this._nodeIndex.clear();
33271 * Set the spatial node filter.
33273 * @param {FilterExpression} filter - Filter expression to be applied
33274 * when calculating spatial edges.
33276 Graph.prototype.setFilter = function (filter) {
33277 this._filter = this._filterCreator.createFilter(filter);
33280 * Uncache the graph according to the graph configuration.
33282 * @description Uncaches unused tiles, unused nodes and
33283 * sequences according to the numbers specified in the
33284 * graph configuration. Sequences does not have a direct
33285 * reference to either tiles or nodes and may be uncached
33286 * even if they are related to the nodes that should be kept.
33288 * @param {Array<string>} keepKeys - Keys of nodes to keep in
33289 * graph unrelated to last access. Tiles related to those keys
33290 * will also be kept in graph.
33292 Graph.prototype.uncache = function (keepKeys) {
33293 var keysInUse = {};
33294 this._addNewKeys(keysInUse, this._cachingFull$);
33295 this._addNewKeys(keysInUse, this._cachingFill$);
33296 this._addNewKeys(keysInUse, this._cachingTiles$);
33297 this._addNewKeys(keysInUse, this._cachingSpatialArea$);
33298 this._addNewKeys(keysInUse, this._requiredNodeTiles);
33299 this._addNewKeys(keysInUse, this._requiredSpatialArea);
33300 for (var _i = 0, keepKeys_2 = keepKeys; _i < keepKeys_2.length; _i++) {
33301 var key = keepKeys_2[_i];
33302 if (key in keysInUse) {
33305 keysInUse[key] = true;
33308 for (var key in keysInUse) {
33309 if (!keysInUse.hasOwnProperty(key)) {
33312 var node = this._nodes[key];
33313 var nodeHs = this._graphCalculator.encodeHs(node.latLon);
33314 for (var _a = 0, nodeHs_1 = nodeHs; _a < nodeHs_1.length; _a++) {
33315 var nodeH = nodeHs_1[_a];
33316 if (!(nodeH in keepHs)) {
33317 keepHs[nodeH] = true;
33321 var potentialHs = [];
33322 for (var h in this._cachedTiles) {
33323 if (!this._cachedTiles.hasOwnProperty(h) || h in keepHs) {
33326 potentialHs.push([h, this._cachedTiles[h]]);
33328 var uncacheHs = potentialHs
33329 .sort(function (h1, h2) {
33330 return h2[1].accessed - h1[1].accessed;
33332 .slice(this._configuration.maxUnusedTiles)
33333 .map(function (h) {
33336 for (var _b = 0, uncacheHs_1 = uncacheHs; _b < uncacheHs_1.length; _b++) {
33337 var uncacheH = uncacheHs_1[_b];
33338 this._uncacheTile(uncacheH);
33340 var potentialNodes = [];
33341 for (var key in this._cachedNodes) {
33342 if (!this._cachedNodes.hasOwnProperty(key) || key in keysInUse) {
33345 potentialNodes.push(this._cachedNodes[key]);
33347 var uncacheNodes = potentialNodes
33348 .sort(function (n1, n2) {
33349 return n2.accessed - n1.accessed;
33351 .slice(this._configuration.maxUnusedNodes);
33352 for (var _c = 0, uncacheNodes_1 = uncacheNodes; _c < uncacheNodes_1.length; _c++) {
33353 var nodeAccess = uncacheNodes_1[_c];
33354 nodeAccess.node.uncache();
33355 var key = nodeAccess.node.key;
33356 delete this._cachedNodes[key];
33357 if (key in this._cachedNodeTiles) {
33358 delete this._cachedNodeTiles[key];
33360 if (key in this._cachedSpatialEdges) {
33361 delete this._cachedSpatialEdges[key];
33364 var potentialSequences = [];
33365 for (var sequenceKey in this._sequences) {
33366 if (!this._sequences.hasOwnProperty(sequenceKey) ||
33367 sequenceKey in this._cachingSequences$) {
33370 potentialSequences.push(this._sequences[sequenceKey]);
33372 var uncacheSequences = potentialSequences
33373 .sort(function (s1, s2) {
33374 return s2.accessed - s1.accessed;
33376 .slice(this._configuration.maxSequences);
33377 for (var _d = 0, uncacheSequences_1 = uncacheSequences; _d < uncacheSequences_1.length; _d++) {
33378 var sequenceAccess = uncacheSequences_1[_d];
33379 var sequenceKey = sequenceAccess.sequence.key;
33380 delete this._sequences[sequenceKey];
33381 sequenceAccess.sequence.dispose();
33384 Graph.prototype._addNewKeys = function (keys, dict) {
33385 for (var key in dict) {
33386 if (!dict.hasOwnProperty(key) || !this.hasNode(key)) {
33389 if (!(key in keys)) {
33394 Graph.prototype._cacheSequence$ = function (sequenceKey) {
33396 if (sequenceKey in this._cachingSequences$) {
33397 return this._cachingSequences$[sequenceKey];
33399 this._cachingSequences$[sequenceKey] = this._apiV3.sequenceByKey$([sequenceKey])
33400 .do(function (sequenceByKey) {
33401 if (!(sequenceKey in _this._sequences)) {
33402 _this._sequences[sequenceKey] = {
33403 accessed: new Date().getTime(),
33404 sequence: new Graph_1.Sequence(sequenceByKey[sequenceKey]),
33407 delete _this._cachingSequences$[sequenceKey];
33409 .map(function (sequenceByKey) {
33412 .finally(function () {
33413 if (sequenceKey in _this._cachingSequences$) {
33414 delete _this._cachingSequences$[sequenceKey];
33416 _this._changed$.next(_this);
33420 return this._cachingSequences$[sequenceKey];
33422 Graph.prototype._makeFull = function (node, fillNode) {
33423 if (fillNode.calt == null) {
33424 fillNode.calt = this._defaultAlt;
33426 if (fillNode.c_rotation == null) {
33427 fillNode.c_rotation = this._graphCalculator.rotationFromCompass(fillNode.ca, fillNode.orientation);
33429 node.makeFull(fillNode);
33431 Graph.prototype._preStore = function (h, node) {
33432 if (!(h in this._preStored)) {
33433 this._preStored[h] = {};
33435 this._preStored[h][node.key] = node;
33437 Graph.prototype._removeFromPreStore = function (h) {
33438 var preStored = null;
33439 if (h in this._preStored) {
33440 preStored = this._preStored[h];
33441 delete this._preStored[h];
33445 Graph.prototype._setNode = function (node) {
33446 var key = node.key;
33447 if (this.hasNode(key)) {
33448 throw new Error_1.GraphMapillaryError("Node already exist (" + key + ").");
33450 this._nodes[key] = node;
33452 Graph.prototype._uncacheTile = function (h) {
33453 for (var _i = 0, _a = this._cachedTiles[h].nodes; _i < _a.length; _i++) {
33455 var key = node.key;
33456 delete this._nodes[key];
33457 delete this._nodeToTile[key];
33458 if (key in this._cachedNodes) {
33459 delete this._cachedNodes[key];
33461 if (key in this._cachedNodeTiles) {
33462 delete this._cachedNodeTiles[key];
33464 if (key in this._cachedSpatialEdges) {
33465 delete this._cachedSpatialEdges[key];
33469 for (var _b = 0, _c = this._nodeIndexTiles[h]; _b < _c.length; _b++) {
33470 var nodeIndexItem = _c[_b];
33471 this._nodeIndex.remove(nodeIndexItem);
33473 delete this._nodeIndexTiles[h];
33474 delete this._cachedTiles[h];
33476 Graph.prototype._updateCachedTileAccess = function (key, accessed) {
33477 if (key in this._nodeToTile) {
33478 this._cachedTiles[this._nodeToTile[key]].accessed = accessed;
33481 Graph.prototype._updateCachedNodeAccess = function (key, accessed) {
33482 if (key in this._cachedNodes) {
33483 this._cachedNodes[key].accessed = accessed;
33488 exports.Graph = Graph;
33489 exports.default = Graph;
33491 },{"../Edge":227,"../Error":228,"../Graph":230,"rbush":25,"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}],319:[function(require,module,exports){
33493 /// <reference path="../../typings/index.d.ts" />
33494 Object.defineProperty(exports, "__esModule", { value: true });
33495 var geohash = require("latlon-geohash");
33496 var THREE = require("three");
33497 var Geo_1 = require("../Geo");
33498 var GeoHashDirections = (function () {
33499 function GeoHashDirections() {
33501 GeoHashDirections.n = "n";
33502 GeoHashDirections.nw = "nw";
33503 GeoHashDirections.w = "w";
33504 GeoHashDirections.sw = "sw";
33505 GeoHashDirections.s = "s";
33506 GeoHashDirections.se = "se";
33507 GeoHashDirections.e = "e";
33508 GeoHashDirections.ne = "ne";
33509 return GeoHashDirections;
33512 * @class GraphCalculator
33514 * @classdesc Represents a calculator for graph entities.
33516 var GraphCalculator = (function () {
33518 * Create a new graph calculator instance.
33520 * @param {GeoCoords} geoCoords - Geo coords instance.
33522 function GraphCalculator(geoCoords) {
33523 this._geoCoords = geoCoords != null ? geoCoords : new Geo_1.GeoCoords();
33526 * Encode the geohash tile for geodetic coordinates.
33528 * @param {ILatLon} latlon - Latitude and longitude to encode.
33529 * @param {number} precision - Precision of the encoding.
33531 * @returns {string} The geohash tile for the lat, lon and precision.
33533 GraphCalculator.prototype.encodeH = function (latLon, precision) {
33534 if (precision === void 0) { precision = 7; }
33535 return geohash.encode(latLon.lat, latLon.lon, precision);
33538 * Encode the geohash tiles within a threshold from a position
33539 * using Manhattan distance.
33541 * @param {ILatLon} latlon - Latitude and longitude to encode.
33542 * @param {number} precision - Precision of the encoding.
33543 * @param {number} threshold - Threshold of the encoding in meters.
33545 * @returns {string} The geohash tiles reachable within the threshold.
33547 GraphCalculator.prototype.encodeHs = function (latLon, precision, threshold) {
33548 if (precision === void 0) { precision = 7; }
33549 if (threshold === void 0) { threshold = 20; }
33550 var h = geohash.encode(latLon.lat, latLon.lon, precision);
33551 var bounds = geohash.bounds(h);
33552 var ne = bounds.ne;
33553 var sw = bounds.sw;
33554 var neighbours = geohash.neighbours(h);
33555 var bl = [0, 0, 0];
33556 var tr = this._geoCoords.geodeticToEnu(ne.lat, ne.lon, 0, sw.lat, sw.lon, 0);
33557 var position = this._geoCoords.geodeticToEnu(latLon.lat, latLon.lon, 0, sw.lat, sw.lon, 0);
33558 var left = position[0] - bl[0];
33559 var right = tr[0] - position[0];
33560 var bottom = position[1] - bl[1];
33561 var top = tr[1] - position[1];
33562 var l = left < threshold;
33563 var r = right < threshold;
33564 var b = bottom < threshold;
33565 var t = top < threshold;
33568 hs.push(neighbours[GeoHashDirections.n]);
33571 hs.push(neighbours[GeoHashDirections.nw]);
33574 hs.push(neighbours[GeoHashDirections.w]);
33577 hs.push(neighbours[GeoHashDirections.sw]);
33580 hs.push(neighbours[GeoHashDirections.s]);
33583 hs.push(neighbours[GeoHashDirections.se]);
33586 hs.push(neighbours[GeoHashDirections.e]);
33589 hs.push(neighbours[GeoHashDirections.ne]);
33594 * Get the bounding box corners for a circle with radius of a threshold
33595 * with center in a geodetic position.
33597 * @param {ILatLon} latlon - Latitude and longitude to encode.
33598 * @param {number} threshold - Threshold distance from the position in meters.
33600 * @returns {Array<ILatLon>} The south west and north east corners of the
33603 GraphCalculator.prototype.boundingBoxCorners = function (latLon, threshold) {
33604 var bl = this._geoCoords.enuToGeodetic(-threshold, -threshold, 0, latLon.lat, latLon.lon, 0);
33605 var tr = this._geoCoords.enuToGeodetic(threshold, threshold, 0, latLon.lat, latLon.lon, 0);
33607 { lat: bl[0], lon: bl[1] },
33608 { lat: tr[0], lon: tr[1] },
33612 * Convert a compass angle to an angle axis rotation vector.
33614 * @param {number} compassAngle - The compass angle in degrees.
33615 * @param {number} orientation - The orientation of the original image.
33617 * @returns {Array<number>} Angle axis rotation vector.
33619 GraphCalculator.prototype.rotationFromCompass = function (compassAngle, orientation) {
33623 switch (orientation) {
33642 var rz = new THREE.Matrix4().makeRotationZ(z);
33643 var euler = new THREE.Euler(x, y, compassAngle * Math.PI / 180, "XYZ");
33644 var re = new THREE.Matrix4().makeRotationFromEuler(euler);
33645 var rotation = new THREE.Vector4().setAxisAngleFromRotationMatrix(re.multiply(rz));
33646 return rotation.multiplyScalar(rotation.w).toArray().slice(0, 3);
33648 return GraphCalculator;
33650 exports.GraphCalculator = GraphCalculator;
33651 exports.default = GraphCalculator;
33653 },{"../Geo":229,"latlon-geohash":21,"three":176}],320:[function(require,module,exports){
33655 Object.defineProperty(exports, "__esModule", { value: true });
33656 var Observable_1 = require("rxjs/Observable");
33657 var Subject_1 = require("rxjs/Subject");
33658 require("rxjs/add/operator/catch");
33659 require("rxjs/add/operator/concat");
33660 require("rxjs/add/operator/do");
33661 require("rxjs/add/operator/expand");
33662 require("rxjs/add/operator/finally");
33663 require("rxjs/add/operator/first");
33664 require("rxjs/add/operator/last");
33665 require("rxjs/add/operator/map");
33666 require("rxjs/add/operator/mergeMap");
33667 require("rxjs/add/operator/publishReplay");
33669 * @class GraphService
33671 * @classdesc Represents a service for graph operations.
33673 var GraphService = (function () {
33675 * Create a new graph service instance.
33677 * @param {Graph} graph - Graph instance to be operated on.
33679 function GraphService(graph, imageLoadingService) {
33680 this._graph$ = Observable_1.Observable
33682 .concat(graph.changed$)
33685 this._graph$.subscribe(function () { });
33686 this._imageLoadingService = imageLoadingService;
33687 this._firstGraphSubjects$ = [];
33688 this._initializeCacheSubscriptions = [];
33689 this._sequenceSubscriptions = [];
33690 this._spatialSubscriptions = [];
33693 * Cache a node in the graph and retrieve it.
33695 * @description When called, the full properties of
33696 * the node are retrieved and the node cache is initialized.
33697 * After that the node assets are cached and the node
33698 * is emitted to the observable when.
33699 * In parallel to caching the node assets, the sequence and
33700 * spatial edges of the node are cached. For this, the sequence
33701 * of the node and the required tiles and spatial nodes are
33702 * retrieved. The sequence and spatial edges may be set before
33703 * or after the node is returned.
33705 * @param {string} key - Key of the node to cache.
33706 * @return {Observable<Node>} Observable emitting a single item,
33707 * the node, when it has been retrieved and its assets are cached.
33708 * @throws {Error} Propagates any IO node caching errors to the caller.
33710 GraphService.prototype.cacheNode$ = function (key) {
33712 var firstGraphSubject$ = new Subject_1.Subject();
33713 this._firstGraphSubjects$.push(firstGraphSubject$);
33714 var firstGraph$ = firstGraphSubject$
33717 var node$ = firstGraph$
33718 .map(function (graph) {
33719 return graph.getNode(key);
33721 .mergeMap(function (node) {
33722 return node.assetsCached ?
33723 Observable_1.Observable.of(node) :
33724 node.cacheAssets$();
33728 node$.subscribe(function (node) {
33729 _this._imageLoadingService.loadnode$.next(node);
33730 }, function (error) {
33731 console.error("Failed to cache node (" + key + ")", error);
33733 var initializeCacheSubscription = this._graph$
33735 .mergeMap(function (graph) {
33736 if (graph.isCachingFull(key) || !graph.hasNode(key)) {
33737 return graph.cacheFull$(key);
33739 if (graph.isCachingFill(key) || !graph.getNode(key).full) {
33740 return graph.cacheFill$(key);
33742 return Observable_1.Observable.of(graph);
33744 .do(function (graph) {
33745 if (!graph.hasInitializedCache(key)) {
33746 graph.initializeCache(key);
33749 .finally(function () {
33750 if (initializeCacheSubscription == null) {
33753 _this._removeFromArray(initializeCacheSubscription, _this._initializeCacheSubscriptions);
33754 _this._removeFromArray(firstGraphSubject$, _this._firstGraphSubjects$);
33756 .subscribe(function (graph) {
33757 firstGraphSubject$.next(graph);
33758 firstGraphSubject$.complete();
33759 }, function (error) {
33760 firstGraphSubject$.error(error);
33762 if (!initializeCacheSubscription.closed) {
33763 this._initializeCacheSubscriptions.push(initializeCacheSubscription);
33765 var sequenceSubscription = firstGraph$
33766 .mergeMap(function (graph) {
33767 if (graph.isCachingNodeSequence(key) || !graph.hasNodeSequence(key)) {
33768 return graph.cacheNodeSequence$(key);
33770 return Observable_1.Observable.of(graph);
33772 .do(function (graph) {
33773 if (!graph.getNode(key).sequenceEdges.cached) {
33774 graph.cacheSequenceEdges(key);
33777 .finally(function () {
33778 if (sequenceSubscription == null) {
33781 _this._removeFromArray(sequenceSubscription, _this._sequenceSubscriptions);
33783 .subscribe(function (graph) { return; }, function (error) {
33784 console.error("Failed to cache sequence edges (" + key + ").", error);
33786 if (!sequenceSubscription.closed) {
33787 this._sequenceSubscriptions.push(sequenceSubscription);
33789 var spatialSubscription = firstGraph$
33790 .expand(function (graph) {
33791 if (graph.hasTiles(key)) {
33792 return Observable_1.Observable.empty();
33794 return Observable_1.Observable
33795 .from(graph.cacheTiles$(key))
33796 .mergeMap(function (graph$) {
33798 .mergeMap(function (g) {
33799 if (g.isCachingTiles(key)) {
33800 return Observable_1.Observable.empty();
33802 return Observable_1.Observable.of(g);
33804 .catch(function (error, caught$) {
33805 console.error("Failed to cache tile data (" + key + ").", error);
33806 return Observable_1.Observable.empty();
33811 .mergeMap(function (graph) {
33812 if (graph.hasSpatialArea(key)) {
33813 return Observable_1.Observable.of(graph);
33815 return Observable_1.Observable
33816 .from(graph.cacheSpatialArea$(key))
33817 .mergeMap(function (graph$) {
33819 .catch(function (error, caught$) {
33820 console.error("Failed to cache spatial nodes (" + key + ").", error);
33821 return Observable_1.Observable.empty();
33826 .mergeMap(function (graph) {
33827 return graph.hasNodeSequence(key) ?
33828 Observable_1.Observable.of(graph) :
33829 graph.cacheNodeSequence$(key);
33831 .do(function (graph) {
33832 if (!graph.getNode(key).spatialEdges.cached) {
33833 graph.cacheSpatialEdges(key);
33836 .finally(function () {
33837 if (spatialSubscription == null) {
33840 _this._removeFromArray(spatialSubscription, _this._spatialSubscriptions);
33842 .subscribe(function (graph) { return; }, function (error) {
33843 console.error("Failed to cache spatial edges (" + key + ").", error);
33845 if (!spatialSubscription.closed) {
33846 this._spatialSubscriptions.push(spatialSubscription);
33849 .first(function (node) {
33850 return node.assetsCached;
33854 * Cache a sequence in the graph and retrieve it.
33856 * @param {string} sequenceKey - Sequence key.
33857 * @returns {Observable<Sequence>} Observable emitting a single item,
33858 * the sequence, when it has been retrieved and its assets are cached.
33859 * @throws {Error} Propagates any IO node caching errors to the caller.
33861 GraphService.prototype.cacheSequence$ = function (sequenceKey) {
33862 return this._graph$
33864 .mergeMap(function (graph) {
33865 if (graph.isCachingSequence(sequenceKey) || !graph.hasSequence(sequenceKey)) {
33866 return graph.cacheSequence$(sequenceKey);
33868 return Observable_1.Observable.of(graph);
33870 .map(function (graph) {
33871 return graph.getSequence(sequenceKey);
33875 * Set a spatial edge filter on the graph.
33877 * @description Resets the spatial edges of all cached nodes.
33879 * @param {FilterExpression} filter - Filter expression to be applied.
33880 * @return {Observable<Graph>} Observable emitting a single item,
33881 * the graph, when the spatial edges have been reset.
33883 GraphService.prototype.setFilter$ = function (filter) {
33884 this._resetSubscriptions(this._spatialSubscriptions);
33885 return this._graph$
33887 .do(function (graph) {
33888 graph.resetSpatialEdges();
33889 graph.setFilter(filter);
33895 * @description Resets the graph but keeps the nodes of the
33898 * @param {Array<string>} keepKeys - Keys of nodes to keep in graph.
33899 * @return {Observable<Node>} Observable emitting a single item,
33900 * the graph, when it has been reset.
33902 GraphService.prototype.reset$ = function (keepKeys) {
33903 this._abortSubjects(this._firstGraphSubjects$);
33904 this._resetSubscriptions(this._initializeCacheSubscriptions);
33905 this._resetSubscriptions(this._sequenceSubscriptions);
33906 this._resetSubscriptions(this._spatialSubscriptions);
33907 return this._graph$
33909 .do(function (graph) {
33910 graph.reset(keepKeys);
33914 * Uncache the graph.
33916 * @description Uncaches the graph by removing tiles, nodes and
33917 * sequences. Keeps the nodes of the supplied keys and the tiles
33918 * related to those nodes.
33920 * @param {Array<string>} keepKeys - Keys of nodes to keep in graph.
33921 * @return {Observable<Graph>} Observable emitting a single item,
33922 * the graph, when the graph has been uncached.
33924 GraphService.prototype.uncache$ = function (keepKeys) {
33925 return this._graph$
33927 .do(function (graph) {
33928 graph.uncache(keepKeys);
33931 GraphService.prototype._abortSubjects = function (subjects) {
33932 for (var _i = 0, _a = subjects.slice(); _i < _a.length; _i++) {
33933 var subject = _a[_i];
33934 this._removeFromArray(subject, subjects);
33935 subject.error(new Error("Cache node request was aborted."));
33938 GraphService.prototype._removeFromArray = function (object, objects) {
33939 var index = objects.indexOf(object);
33940 if (index !== -1) {
33941 objects.splice(index, 1);
33944 GraphService.prototype._resetSubscriptions = function (subscriptions) {
33945 for (var _i = 0, _a = subscriptions.slice(); _i < _a.length; _i++) {
33946 var subscription = _a[_i];
33947 this._removeFromArray(subscription, subscriptions);
33948 if (!subscription.closed) {
33949 subscription.unsubscribe();
33953 return GraphService;
33955 exports.GraphService = GraphService;
33956 exports.default = GraphService;
33958 },{"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}],321:[function(require,module,exports){
33960 /// <reference path="../../typings/index.d.ts" />
33961 Object.defineProperty(exports, "__esModule", { value: true });
33962 var Subject_1 = require("rxjs/Subject");
33963 var ImageLoadingService = (function () {
33964 function ImageLoadingService() {
33965 this._loadnode$ = new Subject_1.Subject();
33966 this._loadstatus$ = this._loadnode$
33967 .scan(function (nodes, node) {
33968 nodes[node.key] = node.loadStatus;
33973 this._loadstatus$.subscribe(function () { });
33975 Object.defineProperty(ImageLoadingService.prototype, "loadnode$", {
33977 return this._loadnode$;
33982 Object.defineProperty(ImageLoadingService.prototype, "loadstatus$", {
33984 return this._loadstatus$;
33989 return ImageLoadingService;
33991 exports.ImageLoadingService = ImageLoadingService;
33993 },{"rxjs/Subject":34}],322:[function(require,module,exports){
33995 /// <reference path="../../typings/index.d.ts" />
33996 Object.defineProperty(exports, "__esModule", { value: true });
33997 var Pbf = require("pbf");
33998 var MeshReader = (function () {
33999 function MeshReader() {
34001 MeshReader.read = function (buffer) {
34002 var pbf = new Pbf(buffer);
34003 return pbf.readFields(MeshReader._readMeshField, { faces: [], vertices: [] });
34005 MeshReader._readMeshField = function (tag, mesh, pbf) {
34007 mesh.vertices.push(pbf.readFloat());
34009 else if (tag === 2) {
34010 mesh.faces.push(pbf.readVarint());
34015 exports.MeshReader = MeshReader;
34017 },{"pbf":23}],323:[function(require,module,exports){
34019 Object.defineProperty(exports, "__esModule", { value: true });
34020 require("rxjs/add/observable/combineLatest");
34021 require("rxjs/add/operator/map");
34025 * @classdesc Represents a node in the navigation graph.
34027 * Explanation of position and bearing properties:
34029 * When images are uploaded they will have GPS information in the EXIF, this is what
34030 * is called `originalLatLon`(@link Node#originalLatLon).
34032 * When Structure from Motions has been run for a node a `computedLatLon` that
34033 * differs from the `originalLatLon` will be created. It is different because
34034 * GPS positions are not very exact and SfM aligns the camera positions according
34035 * to the 3D reconstruction (@link Node#computedLatLon).
34037 * At last there exist a `latLon` property which evaluates to
34038 * the `computedLatLon` from SfM if it exists but falls back
34039 * to the `originalLatLon` from the EXIF GPS otherwise (@link Node#latlon).
34041 * Everything that is done in in the Viewer is based on the SfM positions,
34042 * i.e. `computedLatLon`. That is why the smooth transitions go in the right
34043 * direction (nd not in strange directions because of bad GPS).
34045 * E.g. when placing a marker in the Viewer it is relative to the SfM
34046 * position i.e. the `computedLatLon`.
34048 * The same concept as above also applies to the compass angle (or bearing) properties
34049 * `originalCa`, `computedCa` and `ca`.
34051 var Node = (function () {
34053 * Create a new node instance.
34055 * @description Nodes are always created internally by the library.
34056 * Nodes can not be added to the library through any API method.
34058 * @param {ICoreNode} coreNode - Raw core node data.
34060 function Node(core) {
34061 this._cache = null;
34065 Object.defineProperty(Node.prototype, "assetsCached", {
34067 * Get assets cached.
34069 * @description The assets that need to be cached for this property
34070 * to report true are the following: fill properties, image and mesh.
34071 * The library ensures that the current node will always have the
34074 * @returns {boolean} Value indicating whether all assets have been
34078 return this._core != null &&
34079 this._fill != null &&
34080 this._cache != null &&
34081 this._cache.image != null &&
34082 this._cache.mesh != null;
34087 Object.defineProperty(Node.prototype, "alt", {
34091 * @description If SfM has not been run the computed altitude is
34092 * set to a default value of two meters.
34094 * @returns {number} Altitude, in meters.
34097 return this._fill.calt;
34102 Object.defineProperty(Node.prototype, "ca", {
34106 * @description If the SfM computed compass angle exists it will
34107 * be returned, otherwise the original EXIF compass angle.
34109 * @returns {number} Compass angle, measured in degrees.
34112 return this._fill.cca != null ? this._fill.cca : this._fill.ca;
34117 Object.defineProperty(Node.prototype, "capturedAt", {
34121 * @returns {number} Timestamp when the image was captured.
34124 return this._fill.captured_at;
34129 Object.defineProperty(Node.prototype, "computedCA", {
34133 * @description Will not be set if SfM has not been run.
34135 * @returns {number} SfM computed compass angle, measured in degrees.
34138 return this._fill.cca;
34143 Object.defineProperty(Node.prototype, "computedLatLon", {
34145 * Get computedLatLon.
34147 * @description Will not be set if SfM has not been run.
34149 * @returns {ILatLon} SfM computed latitude longitude in WGS84 datum,
34150 * measured in degrees.
34153 return this._core.cl;
34158 Object.defineProperty(Node.prototype, "focal", {
34162 * @description Will not be set if SfM has not been run.
34164 * @returns {number} SfM computed focal length.
34167 return this._fill.cfocal;
34172 Object.defineProperty(Node.prototype, "full", {
34176 * @description The library ensures that the current node will
34179 * @returns {boolean} Value indicating whether the node has all
34180 * properties filled.
34183 return this._fill != null;
34188 Object.defineProperty(Node.prototype, "fullPano", {
34192 * @returns {boolean} Value indicating whether the node is a complete
34196 return this._fill.gpano != null &&
34197 this._fill.gpano.CroppedAreaLeftPixels === 0 &&
34198 this._fill.gpano.CroppedAreaTopPixels === 0 &&
34199 this._fill.gpano.CroppedAreaImageWidthPixels === this._fill.gpano.FullPanoWidthPixels &&
34200 this._fill.gpano.CroppedAreaImageHeightPixels === this._fill.gpano.FullPanoHeightPixels;
34205 Object.defineProperty(Node.prototype, "gpano", {
34209 * @description Will not be set for non panoramic images.
34211 * @returns {IGPano} Panorama information for panorama images.
34214 return this._fill.gpano;
34219 Object.defineProperty(Node.prototype, "height", {
34223 * @returns {number} Height of original image, not adjusted
34227 return this._fill.height;
34232 Object.defineProperty(Node.prototype, "image", {
34236 * @description The image will always be set on the current node.
34238 * @returns {HTMLImageElement} Cached image element of the node.
34241 return this._cache.image;
34246 Object.defineProperty(Node.prototype, "key", {
34250 * @returns {string} Unique key of the node.
34253 return this._core.key;
34258 Object.defineProperty(Node.prototype, "latLon", {
34262 * @description If the SfM computed latitude longitude exist
34263 * it will be returned, otherwise the original EXIF latitude
34266 * @returns {ILatLon} Latitude longitude in WGS84 datum,
34267 * measured in degrees.
34270 return this._core.cl != null ? this._core.cl : this._core.l;
34275 Object.defineProperty(Node.prototype, "loadStatus", {
34279 * @returns {ILoadStatus} Value indicating the load status
34280 * of the mesh and image.
34283 return this._cache.loadStatus;
34288 Object.defineProperty(Node.prototype, "merged", {
34292 * @returns {boolean} Value indicating whether SfM has been
34293 * run on the node and the node has been merged into a
34294 * connected component.
34297 return this._fill != null &&
34298 this._fill.merge_version != null &&
34299 this._fill.merge_version > 0;
34304 Object.defineProperty(Node.prototype, "mergeCC", {
34308 * @description Will not be set if SfM has not yet been run on
34311 * @returns {number} SfM connected component key to which
34315 return this._fill.merge_cc;
34320 Object.defineProperty(Node.prototype, "mergeVersion", {
34322 * Get mergeVersion.
34324 * @returns {number} Version for which SfM was run and image was merged.
34327 return this._fill.merge_version;
34332 Object.defineProperty(Node.prototype, "mesh", {
34336 * @description The mesh will always be set on the current node.
34338 * @returns {IMesh} SfM triangulated mesh of reconstructed
34339 * atomic 3D points.
34342 return this._cache.mesh;
34347 Object.defineProperty(Node.prototype, "orientation", {
34351 * @returns {number} EXIF orientation of original image.
34354 return this._fill.orientation;
34359 Object.defineProperty(Node.prototype, "originalCA", {
34363 * @returns {number} Original EXIF compass angle, measured in
34367 return this._fill.ca;
34372 Object.defineProperty(Node.prototype, "originalLatLon", {
34374 * Get originalLatLon.
34376 * @returns {ILatLon} Original EXIF latitude longitude in
34377 * WGS84 datum, measured in degrees.
34380 return this._core.l;
34385 Object.defineProperty(Node.prototype, "pano", {
34389 * @returns {boolean} Value indicating whether the node is a panorama.
34390 * It could be a cropped or full panorama.
34393 return this._fill.gpano != null &&
34394 this._fill.gpano.FullPanoWidthPixels != null;
34399 Object.defineProperty(Node.prototype, "projectKey", {
34403 * @returns {string} Unique key of the project to which
34404 * the node belongs.
34407 return this._fill.project != null ?
34408 this._fill.project.key :
34414 Object.defineProperty(Node.prototype, "rotation", {
34418 * @description Will not be set if SfM has not been run.
34420 * @returns {Array<number>} Rotation vector in angle axis representation.
34423 return this._fill.c_rotation;
34428 Object.defineProperty(Node.prototype, "scale", {
34432 * @description Will not be set if SfM has not been run.
34434 * @returns {number} Scale of atomic reconstruction.
34437 return this._fill.atomic_scale;
34442 Object.defineProperty(Node.prototype, "sequenceKey", {
34446 * @returns {string} Unique key of the sequence to which
34447 * the node belongs.
34450 return this._core.sequence.key;
34455 Object.defineProperty(Node.prototype, "sequenceEdges", {
34457 * Get sequenceEdges.
34459 * @returns {IEdgeStatus} Value describing the status of the
34463 return this._cache.sequenceEdges;
34468 Object.defineProperty(Node.prototype, "sequenceEdges$", {
34470 * Get sequenceEdges$.
34472 * @returns {Observable<IEdgeStatus>} Observable emitting
34473 * values describing the status of the sequence edges.
34476 return this._cache.sequenceEdges$;
34481 Object.defineProperty(Node.prototype, "spatialEdges", {
34483 * Get spatialEdges.
34485 * @returns {IEdgeStatus} Value describing the status of the
34489 return this._cache.spatialEdges;
34494 Object.defineProperty(Node.prototype, "spatialEdges$", {
34496 * Get spatialEdges$.
34498 * @returns {Observable<IEdgeStatus>} Observable emitting
34499 * values describing the status of the spatial edges.
34502 return this._cache.spatialEdges$;
34507 Object.defineProperty(Node.prototype, "userKey", {
34511 * @returns {string} Unique key of the user who uploaded
34515 return this._fill.user.key;
34520 Object.defineProperty(Node.prototype, "username", {
34524 * @returns {string} Username of the user who uploaded
34528 return this._fill.user.username;
34533 Object.defineProperty(Node.prototype, "width", {
34537 * @returns {number} Width of original image, not
34538 * adjusted for orientation.
34541 return this._fill.width;
34547 * Cache the image and mesh assets.
34549 * @description The assets are always cached internally by the
34550 * library prior to setting a node as the current node.
34552 * @returns {Observable<Node>} Observable emitting this node whenever the
34553 * load status has changed and when the mesh or image has been fully loaded.
34555 Node.prototype.cacheAssets$ = function () {
34557 return this._cache.cacheAssets$(this.key, this.pano, this.merged)
34558 .map(function (cache) {
34562 Node.prototype.cacheImage$ = function (imageSize) {
34564 return this._cache.cacheImage$(this.key, imageSize)
34565 .map(function (cache) {
34570 * Cache the sequence edges.
34572 * @description The sequence edges are cached asynchronously
34573 * internally by the library.
34575 * @param {Array<IEdge>} edges - Sequence edges to cache.
34577 Node.prototype.cacheSequenceEdges = function (edges) {
34578 this._cache.cacheSequenceEdges(edges);
34581 * Cache the spatial edges.
34583 * @description The spatial edges are cached asynchronously
34584 * internally by the library.
34586 * @param {Array<IEdge>} edges - Spatial edges to cache.
34588 Node.prototype.cacheSpatialEdges = function (edges) {
34589 this._cache.cacheSpatialEdges(edges);
34592 * Dispose the node.
34594 * @description Disposes all cached assets.
34596 Node.prototype.dispose = function () {
34597 if (this._cache != null) {
34598 this._cache.dispose();
34599 this._cache = null;
34605 * Initialize the node cache.
34607 * @description The node cache is initialized internally by
34610 * @param {NodeCache} cache - The node cache to set as cache.
34612 Node.prototype.initializeCache = function (cache) {
34613 if (this._cache != null) {
34614 throw new Error("Node cache already initialized (" + this.key + ").");
34616 this._cache = cache;
34619 * Fill the node with all properties.
34621 * @description The node is filled internally by
34624 * @param {IFillNode} fill - The fill node struct.
34626 Node.prototype.makeFull = function (fill) {
34627 if (fill == null) {
34628 throw new Error("Fill can not be null.");
34633 * Reset the sequence edges.
34635 Node.prototype.resetSequenceEdges = function () {
34636 this._cache.resetSequenceEdges();
34639 * Reset the spatial edges.
34641 Node.prototype.resetSpatialEdges = function () {
34642 this._cache.resetSpatialEdges();
34645 * Clears the image and mesh assets, aborts
34646 * any outstanding requests and resets edges.
34648 Node.prototype.uncache = function () {
34649 if (this._cache == null) {
34652 this._cache.dispose();
34653 this._cache = null;
34657 exports.Node = Node;
34658 exports.default = Node;
34660 },{"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/map":65}],324:[function(require,module,exports){
34661 (function (Buffer){
34663 Object.defineProperty(exports, "__esModule", { value: true });
34664 var Subject_1 = require("rxjs/Subject");
34665 var Observable_1 = require("rxjs/Observable");
34666 require("rxjs/add/observable/combineLatest");
34667 require("rxjs/add/operator/publishReplay");
34668 var Graph_1 = require("../Graph");
34669 var Utils_1 = require("../Utils");
34673 * @classdesc Represents the cached properties of a node.
34675 var NodeCache = (function () {
34677 * Create a new node cache instance.
34679 function NodeCache() {
34680 this._disposed = false;
34681 this._image = null;
34682 this._loadStatus = { loaded: 0, total: 0 };
34684 this._sequenceEdges = { cached: false, edges: [] };
34685 this._spatialEdges = { cached: false, edges: [] };
34686 this._sequenceEdgesChanged$ = new Subject_1.Subject();
34687 this._sequenceEdges$ = this._sequenceEdgesChanged$
34688 .startWith(this._sequenceEdges)
34691 this._sequenceEdgesSubscription = this._sequenceEdges$.subscribe(function () { });
34692 this._spatialEdgesChanged$ = new Subject_1.Subject();
34693 this._spatialEdges$ = this._spatialEdgesChanged$
34694 .startWith(this._spatialEdges)
34697 this._spatialEdgesSubscription = this._spatialEdges$.subscribe(function () { });
34698 this._cachingAssets$ = null;
34700 Object.defineProperty(NodeCache.prototype, "image", {
34704 * @description Will not be set when assets have not been cached
34705 * or when the object has been disposed.
34707 * @returns {HTMLImageElement} Cached image element of the node.
34710 return this._image;
34715 Object.defineProperty(NodeCache.prototype, "loadStatus", {
34719 * @returns {ILoadStatus} Value indicating the load status
34720 * of the mesh and image.
34723 return this._loadStatus;
34728 Object.defineProperty(NodeCache.prototype, "mesh", {
34732 * @description Will not be set when assets have not been cached
34733 * or when the object has been disposed.
34735 * @returns {IMesh} SfM triangulated mesh of reconstructed
34736 * atomic 3D points.
34744 Object.defineProperty(NodeCache.prototype, "sequenceEdges", {
34746 * Get sequenceEdges.
34748 * @returns {IEdgeStatus} Value describing the status of the
34752 return this._sequenceEdges;
34757 Object.defineProperty(NodeCache.prototype, "sequenceEdges$", {
34759 * Get sequenceEdges$.
34761 * @returns {Observable<IEdgeStatus>} Observable emitting
34762 * values describing the status of the sequence edges.
34765 return this._sequenceEdges$;
34770 Object.defineProperty(NodeCache.prototype, "spatialEdges", {
34772 * Get spatialEdges.
34774 * @returns {IEdgeStatus} Value describing the status of the
34778 return this._spatialEdges;
34783 Object.defineProperty(NodeCache.prototype, "spatialEdges$", {
34785 * Get spatialEdges$.
34787 * @returns {Observable<IEdgeStatus>} Observable emitting
34788 * values describing the status of the spatial edges.
34791 return this._spatialEdges$;
34797 * Cache the image and mesh assets.
34799 * @param {string} key - Key of the node to cache.
34800 * @param {boolean} pano - Value indicating whether node is a panorama.
34801 * @param {boolean} merged - Value indicating whether node is merged.
34802 * @returns {Observable<NodeCache>} Observable emitting this node
34803 * cache whenever the load status has changed and when the mesh or image
34804 * has been fully loaded.
34806 NodeCache.prototype.cacheAssets$ = function (key, pano, merged) {
34808 if (this._cachingAssets$ != null) {
34809 return this._cachingAssets$;
34811 var imageSize = pano ?
34812 Utils_1.Settings.basePanoramaSize :
34813 Utils_1.Settings.baseImageSize;
34814 this._cachingAssets$ = Observable_1.Observable
34815 .combineLatest(this._cacheImage$(key, imageSize), this._cacheMesh$(key, merged), function (imageStatus, meshStatus) {
34816 _this._loadStatus.loaded = 0;
34817 _this._loadStatus.total = 0;
34819 _this._mesh = meshStatus.object;
34820 _this._loadStatus.loaded += meshStatus.loaded.loaded;
34821 _this._loadStatus.total += meshStatus.loaded.total;
34824 _this._image = imageStatus.object;
34825 _this._loadStatus.loaded += imageStatus.loaded.loaded;
34826 _this._loadStatus.total += imageStatus.loaded.total;
34830 .finally(function () {
34831 _this._cachingAssets$ = null;
34835 return this._cachingAssets$;
34838 * Cache an image with a higher resolution than the current one.
34840 * @param {string} key - Key of the node to cache.
34841 * @param {ImageSize} imageSize - The size to cache.
34842 * @returns {Observable<NodeCache>} Observable emitting a single item,
34843 * the node cache, when the image has been cached. If supplied image
34844 * size is not larger than the current image size the node cache is
34845 * returned immediately.
34847 NodeCache.prototype.cacheImage$ = function (key, imageSize) {
34849 if (this._image != null && imageSize <= Math.max(this._image.width, this._image.height)) {
34850 return Observable_1.Observable.of(this);
34852 return this._cacheImage$(key, imageSize)
34853 .first(function (status) {
34854 return status.object != null;
34856 .do(function (status) {
34857 _this._disposeImage();
34858 _this._image = status.object;
34860 .map(function (imageStatus) {
34865 * Cache the sequence edges.
34867 * @param {Array<IEdge>} edges - Sequence edges to cache.
34869 NodeCache.prototype.cacheSequenceEdges = function (edges) {
34870 this._sequenceEdges = { cached: true, edges: edges };
34871 this._sequenceEdgesChanged$.next(this._sequenceEdges);
34874 * Cache the spatial edges.
34876 * @param {Array<IEdge>} edges - Spatial edges to cache.
34878 NodeCache.prototype.cacheSpatialEdges = function (edges) {
34879 this._spatialEdges = { cached: true, edges: edges };
34880 this._spatialEdgesChanged$.next(this._spatialEdges);
34883 * Dispose the node cache.
34885 * @description Disposes all cached assets and unsubscribes to
34888 NodeCache.prototype.dispose = function () {
34889 this._sequenceEdgesSubscription.unsubscribe();
34890 this._spatialEdgesSubscription.unsubscribe();
34891 this._disposeImage();
34893 this._loadStatus.loaded = 0;
34894 this._loadStatus.total = 0;
34895 this._sequenceEdges = { cached: false, edges: [] };
34896 this._spatialEdges = { cached: false, edges: [] };
34897 this._sequenceEdgesChanged$.next(this._sequenceEdges);
34898 this._spatialEdgesChanged$.next(this._spatialEdges);
34899 this._disposed = true;
34900 if (this._imageRequest != null) {
34901 this._imageRequest.abort();
34903 if (this._meshRequest != null) {
34904 this._meshRequest.abort();
34908 * Reset the sequence edges.
34910 NodeCache.prototype.resetSequenceEdges = function () {
34911 this._sequenceEdges = { cached: false, edges: [] };
34912 this._sequenceEdgesChanged$.next(this._sequenceEdges);
34915 * Reset the spatial edges.
34917 NodeCache.prototype.resetSpatialEdges = function () {
34918 this._spatialEdges = { cached: false, edges: [] };
34919 this._spatialEdgesChanged$.next(this._spatialEdges);
34924 * @param {string} key - Key of the node to cache.
34925 * @param {boolean} pano - Value indicating whether node is a panorama.
34926 * @returns {Observable<ILoadStatusObject<HTMLImageElement>>} Observable
34927 * emitting a load status object every time the load status changes
34928 * and completes when the image is fully loaded.
34930 NodeCache.prototype._cacheImage$ = function (key, imageSize) {
34932 return Observable_1.Observable.create(function (subscriber) {
34933 var xmlHTTP = new XMLHttpRequest();
34934 xmlHTTP.open("GET", Utils_1.Urls.thumbnail(key, imageSize), true);
34935 xmlHTTP.responseType = "arraybuffer";
34936 xmlHTTP.timeout = 15000;
34937 xmlHTTP.onload = function (pe) {
34938 if (xmlHTTP.status !== 200) {
34939 _this._imageRequest = null;
34940 subscriber.error(new Error("Failed to fetch image (" + key + "). Status: " + xmlHTTP.status + ", " + xmlHTTP.statusText));
34943 var image = new Image();
34944 image.crossOrigin = "Anonymous";
34945 image.onload = function (e) {
34946 _this._imageRequest = null;
34947 if (_this._disposed) {
34948 window.URL.revokeObjectURL(image.src);
34949 subscriber.error(new Error("Image load was aborted (" + key + ")"));
34952 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: image });
34953 subscriber.complete();
34955 image.onerror = function (error) {
34956 _this._imageRequest = null;
34957 subscriber.error(new Error("Failed to load image (" + key + ")"));
34959 var blob = new Blob([xmlHTTP.response]);
34960 image.src = window.URL.createObjectURL(blob);
34962 xmlHTTP.onprogress = function (pe) {
34963 if (_this._disposed) {
34966 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: null });
34968 xmlHTTP.onerror = function (error) {
34969 _this._imageRequest = null;
34970 subscriber.error(new Error("Failed to fetch image (" + key + ")"));
34972 xmlHTTP.ontimeout = function (e) {
34973 _this._imageRequest = null;
34974 subscriber.error(new Error("Image request timed out (" + key + ")"));
34976 xmlHTTP.onabort = function (event) {
34977 _this._imageRequest = null;
34978 subscriber.error(new Error("Image request was aborted (" + key + ")"));
34980 _this._imageRequest = xmlHTTP;
34981 xmlHTTP.send(null);
34987 * @param {string} key - Key of the node to cache.
34988 * @param {boolean} merged - Value indicating whether node is merged.
34989 * @returns {Observable<ILoadStatusObject<IMesh>>} Observable emitting
34990 * a load status object every time the load status changes and completes
34991 * when the mesh is fully loaded.
34993 NodeCache.prototype._cacheMesh$ = function (key, merged) {
34995 return Observable_1.Observable.create(function (subscriber) {
34997 subscriber.next(_this._createEmptyMeshLoadStatus());
34998 subscriber.complete();
35001 var xmlHTTP = new XMLHttpRequest();
35002 xmlHTTP.open("GET", Utils_1.Urls.protoMesh(key), true);
35003 xmlHTTP.responseType = "arraybuffer";
35004 xmlHTTP.timeout = 15000;
35005 xmlHTTP.onload = function (pe) {
35006 _this._meshRequest = null;
35007 if (_this._disposed) {
35010 var mesh = xmlHTTP.status === 200 ?
35011 Graph_1.MeshReader.read(new Buffer(xmlHTTP.response)) :
35012 { faces: [], vertices: [] };
35013 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: mesh });
35014 subscriber.complete();
35016 xmlHTTP.onprogress = function (pe) {
35017 if (_this._disposed) {
35020 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: null });
35022 xmlHTTP.onerror = function (e) {
35023 _this._meshRequest = null;
35024 console.error("Failed to cache mesh (" + key + ")");
35025 subscriber.next(_this._createEmptyMeshLoadStatus());
35026 subscriber.complete();
35028 xmlHTTP.ontimeout = function (e) {
35029 _this._meshRequest = null;
35030 console.error("Mesh request timed out (" + key + ")");
35031 subscriber.next(_this._createEmptyMeshLoadStatus());
35032 subscriber.complete();
35034 xmlHTTP.onabort = function (e) {
35035 _this._meshRequest = null;
35036 subscriber.error(new Error("Mesh request was aborted (" + key + ")"));
35038 _this._meshRequest = xmlHTTP;
35039 xmlHTTP.send(null);
35043 * Create a load status object with an empty mesh.
35045 * @returns {ILoadStatusObject<IMesh>} Load status object
35048 NodeCache.prototype._createEmptyMeshLoadStatus = function () {
35050 loaded: { loaded: 0, total: 0 },
35051 object: { faces: [], vertices: [] },
35054 NodeCache.prototype._disposeImage = function () {
35055 if (this._image != null) {
35056 window.URL.revokeObjectURL(this._image.src);
35058 this._image = null;
35062 exports.NodeCache = NodeCache;
35063 exports.default = NodeCache;
35065 }).call(this,require("buffer").Buffer)
35067 },{"../Graph":230,"../Utils":236,"buffer":7,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/publishReplay":72}],325:[function(require,module,exports){
35069 /// <reference path="../../typings/index.d.ts" />
35070 Object.defineProperty(exports, "__esModule", { value: true });
35071 var _ = require("underscore");
35075 * @classdesc Represents a sequence of ordered nodes.
35077 var Sequence = (function () {
35079 * Create a new sequene instance.
35081 * @param {ISequence} sequence - Raw sequence data.
35083 function Sequence(sequence) {
35084 this._key = sequence.key;
35085 this._keys = sequence.keys;
35087 Object.defineProperty(Sequence.prototype, "key", {
35091 * @returns {string} Unique sequence key.
35099 Object.defineProperty(Sequence.prototype, "keys", {
35103 * @returns {Array<string>} Array of ordered node keys in the sequence.
35112 * Dispose the sequence.
35114 * @description Disposes all cached assets.
35116 Sequence.prototype.dispose = function () {
35121 * Find the next node key in the sequence with respect to
35122 * the provided node key.
35124 * @param {string} key - Reference node key.
35125 * @returns {string} Next key in sequence if it exists, null otherwise.
35127 Sequence.prototype.findNextKey = function (key) {
35128 var i = _.indexOf(this._keys, key);
35129 if ((i + 1) >= this._keys.length || i === -1) {
35133 return this._keys[i + 1];
35137 * Find the previous node key in the sequence with respect to
35138 * the provided node key.
35140 * @param {string} key - Reference node key.
35141 * @returns {string} Previous key in sequence if it exists, null otherwise.
35143 Sequence.prototype.findPrevKey = function (key) {
35144 var i = _.indexOf(this._keys, key);
35145 if (i === 0 || i === -1) {
35149 return this._keys[i - 1];
35154 exports.Sequence = Sequence;
35155 exports.default = Sequence;
35157 },{"underscore":178}],326:[function(require,module,exports){
35159 /// <reference path="../../../typings/index.d.ts" />
35160 Object.defineProperty(exports, "__esModule", { value: true });
35161 var THREE = require("three");
35162 var Edge_1 = require("../../Edge");
35163 var Error_1 = require("../../Error");
35164 var Geo_1 = require("../../Geo");
35166 * @class EdgeCalculator
35168 * @classdesc Represents a class for calculating node edges.
35170 var EdgeCalculator = (function () {
35172 * Create a new edge calculator instance.
35174 * @param {EdgeCalculatorSettings} settings - Settings struct.
35175 * @param {EdgeCalculatorDirections} directions - Directions struct.
35176 * @param {EdgeCalculatorCoefficients} coefficients - Coefficients struct.
35178 function EdgeCalculator(settings, directions, coefficients) {
35179 this._spatial = new Geo_1.Spatial();
35180 this._geoCoords = new Geo_1.GeoCoords();
35181 this._settings = settings != null ? settings : new Edge_1.EdgeCalculatorSettings();
35182 this._directions = directions != null ? directions : new Edge_1.EdgeCalculatorDirections();
35183 this._coefficients = coefficients != null ? coefficients : new Edge_1.EdgeCalculatorCoefficients();
35186 * Returns the potential edges to destination nodes for a set
35187 * of nodes with respect to a source node.
35189 * @param {Node} node - Source node.
35190 * @param {Array<Node>} nodes - Potential destination nodes.
35191 * @param {Array<string>} fallbackKeys - Keys for destination nodes that should
35192 * be returned even if they do not meet the criteria for a potential edge.
35193 * @throws {ArgumentMapillaryError} If node is not full.
35195 EdgeCalculator.prototype.getPotentialEdges = function (node, potentialNodes, fallbackKeys) {
35197 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
35199 if (!node.merged) {
35202 var currentDirection = this._spatial.viewingDirection(node.rotation);
35203 var currentVerticalDirection = this._spatial.angleToPlane(currentDirection.toArray(), [0, 0, 1]);
35204 var potentialEdges = [];
35205 for (var _i = 0, potentialNodes_1 = potentialNodes; _i < potentialNodes_1.length; _i++) {
35206 var potential = potentialNodes_1[_i];
35207 if (!potential.merged ||
35208 potential.key === node.key) {
35211 var enu = this._geoCoords.geodeticToEnu(potential.latLon.lat, potential.latLon.lon, potential.alt, node.latLon.lat, node.latLon.lon, node.alt);
35212 var motion = new THREE.Vector3(enu[0], enu[1], enu[2]);
35213 var distance = motion.length();
35214 if (distance > this._settings.maxDistance &&
35215 fallbackKeys.indexOf(potential.key) < 0) {
35218 var motionChange = this._spatial.angleBetweenVector2(currentDirection.x, currentDirection.y, motion.x, motion.y);
35219 var verticalMotion = this._spatial.angleToPlane(motion.toArray(), [0, 0, 1]);
35220 var direction = this._spatial.viewingDirection(potential.rotation);
35221 var directionChange = this._spatial.angleBetweenVector2(currentDirection.x, currentDirection.y, direction.x, direction.y);
35222 var verticalDirection = this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
35223 var verticalDirectionChange = verticalDirection - currentVerticalDirection;
35224 var rotation = this._spatial.relativeRotationAngle(node.rotation, potential.rotation);
35225 var worldMotionAzimuth = this._spatial.angleBetweenVector2(1, 0, motion.x, motion.y);
35226 var sameSequence = potential.sequenceKey != null &&
35227 node.sequenceKey != null &&
35228 potential.sequenceKey === node.sequenceKey;
35229 var sameMergeCC = (potential.mergeCC == null && node.mergeCC == null) ||
35230 potential.mergeCC === node.mergeCC;
35231 var sameUser = potential.userKey === node.userKey;
35232 var potentialEdge = {
35233 capturedAt: potential.capturedAt,
35234 croppedPano: potential.pano && !potential.fullPano,
35235 directionChange: directionChange,
35236 distance: distance,
35237 fullPano: potential.fullPano,
35238 key: potential.key,
35239 motionChange: motionChange,
35240 rotation: rotation,
35241 sameMergeCC: sameMergeCC,
35242 sameSequence: sameSequence,
35243 sameUser: sameUser,
35244 sequenceKey: potential.sequenceKey,
35245 verticalDirectionChange: verticalDirectionChange,
35246 verticalMotion: verticalMotion,
35247 worldMotionAzimuth: worldMotionAzimuth,
35249 potentialEdges.push(potentialEdge);
35251 return potentialEdges;
35254 * Computes the sequence edges for a node.
35256 * @param {Node} node - Source node.
35257 * @throws {ArgumentMapillaryError} If node is not full.
35259 EdgeCalculator.prototype.computeSequenceEdges = function (node, sequence) {
35261 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
35263 if (node.sequenceKey !== sequence.key) {
35264 throw new Error_1.ArgumentMapillaryError("Node and sequence does not correspond.");
35267 var nextKey = sequence.findNextKey(node.key);
35268 if (nextKey != null) {
35271 direction: Edge_1.EdgeDirection.Next,
35272 worldMotionAzimuth: Number.NaN,
35278 var prevKey = sequence.findPrevKey(node.key);
35279 if (prevKey != null) {
35282 direction: Edge_1.EdgeDirection.Prev,
35283 worldMotionAzimuth: Number.NaN,
35292 * Computes the similar edges for a node.
35294 * @description Similar edges for perspective images and cropped panoramas
35295 * look roughly in the same direction and are positioned closed to the node.
35296 * Similar edges for full panoramas only target other full panoramas.
35298 * @param {Node} node - Source node.
35299 * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
35300 * @throws {ArgumentMapillaryError} If node is not full.
35302 EdgeCalculator.prototype.computeSimilarEdges = function (node, potentialEdges) {
35305 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
35307 var nodeFullPano = node.fullPano;
35308 var sequenceGroups = {};
35309 for (var _i = 0, potentialEdges_1 = potentialEdges; _i < potentialEdges_1.length; _i++) {
35310 var potentialEdge = potentialEdges_1[_i];
35311 if (potentialEdge.sequenceKey == null) {
35314 if (potentialEdge.sameSequence ||
35315 !potentialEdge.sameMergeCC) {
35318 if (nodeFullPano) {
35319 if (!potentialEdge.fullPano) {
35324 if (!potentialEdge.fullPano &&
35325 Math.abs(potentialEdge.directionChange) > this._settings.similarMaxDirectionChange) {
35329 if (potentialEdge.distance > this._settings.similarMaxDistance) {
35332 if (potentialEdge.sameUser &&
35333 Math.abs(potentialEdge.capturedAt - node.capturedAt) <
35334 this._settings.similarMinTimeDifference) {
35337 if (sequenceGroups[potentialEdge.sequenceKey] == null) {
35338 sequenceGroups[potentialEdge.sequenceKey] = [];
35340 sequenceGroups[potentialEdge.sequenceKey].push(potentialEdge);
35342 var similarEdges = [];
35343 var calculateScore = node.fullPano ?
35344 function (potentialEdge) {
35345 return potentialEdge.distance;
35347 function (potentialEdge) {
35348 return _this._coefficients.similarDistance * potentialEdge.distance +
35349 _this._coefficients.similarRotation * potentialEdge.rotation;
35351 for (var sequenceKey in sequenceGroups) {
35352 if (!sequenceGroups.hasOwnProperty(sequenceKey)) {
35355 var lowestScore = Number.MAX_VALUE;
35356 var similarEdge = null;
35357 for (var _a = 0, _b = sequenceGroups[sequenceKey]; _a < _b.length; _a++) {
35358 var potentialEdge = _b[_a];
35359 var score = calculateScore(potentialEdge);
35360 if (score < lowestScore) {
35361 lowestScore = score;
35362 similarEdge = potentialEdge;
35365 if (similarEdge == null) {
35368 similarEdges.push(similarEdge);
35370 return similarEdges
35371 .map(function (potentialEdge) {
35374 direction: Edge_1.EdgeDirection.Similar,
35375 worldMotionAzimuth: potentialEdge.worldMotionAzimuth,
35378 to: potentialEdge.key,
35383 * Computes the step edges for a perspective node.
35385 * @description Step edge targets can only be other perspective nodes.
35386 * Returns an empty array for cropped and full panoramas.
35388 * @param {Node} node - Source node.
35389 * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
35390 * @param {string} prevKey - Key of previous node in sequence.
35391 * @param {string} prevKey - Key of next node in sequence.
35392 * @throws {ArgumentMapillaryError} If node is not full.
35394 EdgeCalculator.prototype.computeStepEdges = function (node, potentialEdges, prevKey, nextKey) {
35396 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
35402 for (var k in this._directions.steps) {
35403 if (!this._directions.steps.hasOwnProperty(k)) {
35406 var step = this._directions.steps[k];
35407 var lowestScore = Number.MAX_VALUE;
35409 var fallback = null;
35410 for (var _i = 0, potentialEdges_2 = potentialEdges; _i < potentialEdges_2.length; _i++) {
35411 var potential = potentialEdges_2[_i];
35412 if (potential.croppedPano || potential.fullPano) {
35415 if (Math.abs(potential.directionChange) > this._settings.stepMaxDirectionChange) {
35418 var motionDifference = this._spatial.angleDifference(step.motionChange, potential.motionChange);
35419 var directionMotionDifference = this._spatial.angleDifference(potential.directionChange, motionDifference);
35420 var drift = Math.max(Math.abs(motionDifference), Math.abs(directionMotionDifference));
35421 if (Math.abs(drift) > this._settings.stepMaxDrift) {
35424 var potentialKey = potential.key;
35425 if (step.useFallback && (potentialKey === prevKey || potentialKey === nextKey)) {
35426 fallback = potential;
35428 if (potential.distance > this._settings.stepMaxDistance) {
35431 motionDifference = Math.sqrt(motionDifference * motionDifference +
35432 potential.verticalMotion * potential.verticalMotion);
35433 var score = this._coefficients.stepPreferredDistance *
35434 Math.abs(potential.distance - this._settings.stepPreferredDistance) /
35435 this._settings.stepMaxDistance +
35436 this._coefficients.stepMotion * motionDifference / this._settings.stepMaxDrift +
35437 this._coefficients.stepRotation * potential.rotation / this._settings.stepMaxDirectionChange +
35438 this._coefficients.stepSequencePenalty * (potential.sameSequence ? 0 : 1) +
35439 this._coefficients.stepMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
35440 if (score < lowestScore) {
35441 lowestScore = score;
35445 edge = edge == null ? fallback : edge;
35446 if (edge != null) {
35449 direction: step.direction,
35450 worldMotionAzimuth: edge.worldMotionAzimuth,
35460 * Computes the turn edges for a perspective node.
35462 * @description Turn edge targets can only be other perspective images.
35463 * Returns an empty array for cropped and full panoramas.
35465 * @param {Node} node - Source node.
35466 * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
35467 * @throws {ArgumentMapillaryError} If node is not full.
35469 EdgeCalculator.prototype.computeTurnEdges = function (node, potentialEdges) {
35471 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
35477 for (var k in this._directions.turns) {
35478 if (!this._directions.turns.hasOwnProperty(k)) {
35481 var turn = this._directions.turns[k];
35482 var lowestScore = Number.MAX_VALUE;
35484 for (var _i = 0, potentialEdges_3 = potentialEdges; _i < potentialEdges_3.length; _i++) {
35485 var potential = potentialEdges_3[_i];
35486 if (potential.croppedPano || potential.fullPano) {
35489 if (potential.distance > this._settings.turnMaxDistance) {
35492 var rig = turn.direction !== Edge_1.EdgeDirection.TurnU &&
35493 potential.distance < this._settings.turnMaxRigDistance &&
35494 Math.abs(potential.directionChange) > this._settings.turnMinRigDirectionChange;
35495 var directionDifference = this._spatial.angleDifference(turn.directionChange, potential.directionChange);
35496 var score = void 0;
35498 potential.directionChange * turn.directionChange > 0 &&
35499 Math.abs(potential.directionChange) < Math.abs(turn.directionChange)) {
35500 score = -Math.PI / 2 + Math.abs(potential.directionChange);
35503 if (Math.abs(directionDifference) > this._settings.turnMaxDirectionChange) {
35506 var motionDifference = turn.motionChange ?
35507 this._spatial.angleDifference(turn.motionChange, potential.motionChange) : 0;
35508 motionDifference = Math.sqrt(motionDifference * motionDifference +
35509 potential.verticalMotion * potential.verticalMotion);
35511 this._coefficients.turnDistance * potential.distance /
35512 this._settings.turnMaxDistance +
35513 this._coefficients.turnMotion * motionDifference / Math.PI +
35514 this._coefficients.turnSequencePenalty * (potential.sameSequence ? 0 : 1) +
35515 this._coefficients.turnMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
35517 if (score < lowestScore) {
35518 lowestScore = score;
35522 if (edge != null) {
35525 direction: turn.direction,
35526 worldMotionAzimuth: edge.worldMotionAzimuth,
35536 * Computes the pano edges for a perspective node.
35538 * @description Perspective to pano edge targets can only be
35539 * full pano nodes. Returns an empty array for cropped and full panoramas.
35541 * @param {Node} node - Source node.
35542 * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
35543 * @throws {ArgumentMapillaryError} If node is not full.
35545 EdgeCalculator.prototype.computePerspectiveToPanoEdges = function (node, potentialEdges) {
35547 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
35552 var lowestScore = Number.MAX_VALUE;
35554 for (var _i = 0, potentialEdges_4 = potentialEdges; _i < potentialEdges_4.length; _i++) {
35555 var potential = potentialEdges_4[_i];
35556 if (!potential.fullPano) {
35559 var score = this._coefficients.panoPreferredDistance *
35560 Math.abs(potential.distance - this._settings.panoPreferredDistance) /
35561 this._settings.panoMaxDistance +
35562 this._coefficients.panoMotion * Math.abs(potential.motionChange) / Math.PI +
35563 this._coefficients.panoMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
35564 if (score < lowestScore) {
35565 lowestScore = score;
35569 if (edge == null) {
35575 direction: Edge_1.EdgeDirection.Pano,
35576 worldMotionAzimuth: edge.worldMotionAzimuth,
35584 * Computes the full pano and step edges for a full pano node.
35586 * @description Pano to pano edge targets can only be
35587 * full pano nodes. Pano to step edge targets can only be perspective
35589 * Returns an empty array for cropped panoramas and perspective nodes.
35591 * @param {Node} node - Source node.
35592 * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
35593 * @throws {ArgumentMapillaryError} If node is not full.
35595 EdgeCalculator.prototype.computePanoEdges = function (node, potentialEdges) {
35597 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
35599 if (!node.fullPano) {
35602 var panoEdges = [];
35603 var potentialPanos = [];
35604 var potentialSteps = [];
35605 for (var _i = 0, potentialEdges_5 = potentialEdges; _i < potentialEdges_5.length; _i++) {
35606 var potential = potentialEdges_5[_i];
35607 if (potential.distance > this._settings.panoMaxDistance) {
35610 if (potential.fullPano) {
35611 if (potential.distance < this._settings.panoMinDistance) {
35614 potentialPanos.push(potential);
35617 if (potential.croppedPano) {
35620 for (var k in this._directions.panos) {
35621 if (!this._directions.panos.hasOwnProperty(k)) {
35624 var pano = this._directions.panos[k];
35625 var turn = this._spatial.angleDifference(potential.directionChange, potential.motionChange);
35626 var turnChange = this._spatial.angleDifference(pano.directionChange, turn);
35627 if (Math.abs(turnChange) > this._settings.panoMaxStepTurnChange) {
35630 potentialSteps.push([pano.direction, potential]);
35631 // break if step direction found
35636 var maxRotationDifference = Math.PI / this._settings.panoMaxItems;
35637 var occupiedAngles = [];
35638 var stepAngles = [];
35639 for (var index = 0; index < this._settings.panoMaxItems; index++) {
35640 var rotation = index / this._settings.panoMaxItems * 2 * Math.PI;
35641 var lowestScore = Number.MAX_VALUE;
35643 for (var _a = 0, potentialPanos_1 = potentialPanos; _a < potentialPanos_1.length; _a++) {
35644 var potential = potentialPanos_1[_a];
35645 var motionDifference = this._spatial.angleDifference(rotation, potential.motionChange);
35646 if (Math.abs(motionDifference) > maxRotationDifference) {
35649 var occupiedDifference = Number.MAX_VALUE;
35650 for (var _b = 0, occupiedAngles_1 = occupiedAngles; _b < occupiedAngles_1.length; _b++) {
35651 var occupiedAngle = occupiedAngles_1[_b];
35652 var difference = Math.abs(this._spatial.angleDifference(occupiedAngle, potential.motionChange));
35653 if (difference < occupiedDifference) {
35654 occupiedDifference = difference;
35657 if (occupiedDifference <= maxRotationDifference) {
35660 var score = this._coefficients.panoPreferredDistance *
35661 Math.abs(potential.distance - this._settings.panoPreferredDistance) /
35662 this._settings.panoMaxDistance +
35663 this._coefficients.panoMotion * Math.abs(motionDifference) / maxRotationDifference +
35664 this._coefficients.panoSequencePenalty * (potential.sameSequence ? 0 : 1) +
35665 this._coefficients.panoMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
35666 if (score < lowestScore) {
35667 lowestScore = score;
35671 if (edge != null) {
35672 occupiedAngles.push(edge.motionChange);
35675 direction: Edge_1.EdgeDirection.Pano,
35676 worldMotionAzimuth: edge.worldMotionAzimuth,
35683 stepAngles.push(rotation);
35686 var occupiedStepAngles = {};
35687 occupiedStepAngles[Edge_1.EdgeDirection.Pano] = occupiedAngles;
35688 occupiedStepAngles[Edge_1.EdgeDirection.StepForward] = [];
35689 occupiedStepAngles[Edge_1.EdgeDirection.StepLeft] = [];
35690 occupiedStepAngles[Edge_1.EdgeDirection.StepBackward] = [];
35691 occupiedStepAngles[Edge_1.EdgeDirection.StepRight] = [];
35692 for (var _c = 0, stepAngles_1 = stepAngles; _c < stepAngles_1.length; _c++) {
35693 var stepAngle = stepAngles_1[_c];
35694 var occupations = [];
35695 for (var k in this._directions.panos) {
35696 if (!this._directions.panos.hasOwnProperty(k)) {
35699 var pano = this._directions.panos[k];
35700 var allOccupiedAngles = occupiedStepAngles[Edge_1.EdgeDirection.Pano]
35701 .concat(occupiedStepAngles[pano.direction])
35702 .concat(occupiedStepAngles[pano.prev])
35703 .concat(occupiedStepAngles[pano.next]);
35704 var lowestScore = Number.MAX_VALUE;
35706 for (var _d = 0, potentialSteps_1 = potentialSteps; _d < potentialSteps_1.length; _d++) {
35707 var potential = potentialSteps_1[_d];
35708 if (potential[0] !== pano.direction) {
35711 var motionChange = this._spatial.angleDifference(stepAngle, potential[1].motionChange);
35712 if (Math.abs(motionChange) > maxRotationDifference) {
35715 var minOccupiedDifference = Number.MAX_VALUE;
35716 for (var _e = 0, allOccupiedAngles_1 = allOccupiedAngles; _e < allOccupiedAngles_1.length; _e++) {
35717 var occupiedAngle = allOccupiedAngles_1[_e];
35718 var occupiedDifference = Math.abs(this._spatial.angleDifference(occupiedAngle, potential[1].motionChange));
35719 if (occupiedDifference < minOccupiedDifference) {
35720 minOccupiedDifference = occupiedDifference;
35723 if (minOccupiedDifference <= maxRotationDifference) {
35726 var score = this._coefficients.panoPreferredDistance *
35727 Math.abs(potential[1].distance - this._settings.panoPreferredDistance) /
35728 this._settings.panoMaxDistance +
35729 this._coefficients.panoMotion * Math.abs(motionChange) / maxRotationDifference +
35730 this._coefficients.panoMergeCCPenalty * (potential[1].sameMergeCC ? 0 : 1);
35731 if (score < lowestScore) {
35732 lowestScore = score;
35736 if (edge != null) {
35737 occupations.push(edge);
35740 direction: edge[0],
35741 worldMotionAzimuth: edge[1].worldMotionAzimuth,
35748 for (var _f = 0, occupations_1 = occupations; _f < occupations_1.length; _f++) {
35749 var occupation = occupations_1[_f];
35750 occupiedStepAngles[occupation[0]].push(occupation[1].motionChange);
35755 return EdgeCalculator;
35757 exports.EdgeCalculator = EdgeCalculator;
35758 exports.default = EdgeCalculator;
35760 },{"../../Edge":227,"../../Error":228,"../../Geo":229,"three":176}],327:[function(require,module,exports){
35762 Object.defineProperty(exports, "__esModule", { value: true });
35763 var EdgeCalculatorCoefficients = (function () {
35764 function EdgeCalculatorCoefficients() {
35765 this.panoPreferredDistance = 2;
35766 this.panoMotion = 2;
35767 this.panoSequencePenalty = 1;
35768 this.panoMergeCCPenalty = 4;
35769 this.stepPreferredDistance = 4;
35770 this.stepMotion = 3;
35771 this.stepRotation = 4;
35772 this.stepSequencePenalty = 2;
35773 this.stepMergeCCPenalty = 6;
35774 this.similarDistance = 2;
35775 this.similarRotation = 3;
35776 this.turnDistance = 4;
35777 this.turnMotion = 2;
35778 this.turnSequencePenalty = 1;
35779 this.turnMergeCCPenalty = 4;
35781 return EdgeCalculatorCoefficients;
35783 exports.EdgeCalculatorCoefficients = EdgeCalculatorCoefficients;
35784 exports.default = EdgeCalculatorCoefficients;
35786 },{}],328:[function(require,module,exports){
35788 Object.defineProperty(exports, "__esModule", { value: true });
35789 var Edge_1 = require("../../Edge");
35790 var EdgeCalculatorDirections = (function () {
35791 function EdgeCalculatorDirections() {
35795 this.steps[Edge_1.EdgeDirection.StepForward] = {
35796 direction: Edge_1.EdgeDirection.StepForward,
35800 this.steps[Edge_1.EdgeDirection.StepBackward] = {
35801 direction: Edge_1.EdgeDirection.StepBackward,
35802 motionChange: Math.PI,
35805 this.steps[Edge_1.EdgeDirection.StepLeft] = {
35806 direction: Edge_1.EdgeDirection.StepLeft,
35807 motionChange: Math.PI / 2,
35808 useFallback: false,
35810 this.steps[Edge_1.EdgeDirection.StepRight] = {
35811 direction: Edge_1.EdgeDirection.StepRight,
35812 motionChange: -Math.PI / 2,
35813 useFallback: false,
35815 this.turns[Edge_1.EdgeDirection.TurnLeft] = {
35816 direction: Edge_1.EdgeDirection.TurnLeft,
35817 directionChange: Math.PI / 2,
35818 motionChange: Math.PI / 4,
35820 this.turns[Edge_1.EdgeDirection.TurnRight] = {
35821 direction: Edge_1.EdgeDirection.TurnRight,
35822 directionChange: -Math.PI / 2,
35823 motionChange: -Math.PI / 4,
35825 this.turns[Edge_1.EdgeDirection.TurnU] = {
35826 direction: Edge_1.EdgeDirection.TurnU,
35827 directionChange: Math.PI,
35828 motionChange: null,
35830 this.panos[Edge_1.EdgeDirection.StepForward] = {
35831 direction: Edge_1.EdgeDirection.StepForward,
35832 directionChange: 0,
35833 next: Edge_1.EdgeDirection.StepLeft,
35834 prev: Edge_1.EdgeDirection.StepRight,
35836 this.panos[Edge_1.EdgeDirection.StepBackward] = {
35837 direction: Edge_1.EdgeDirection.StepBackward,
35838 directionChange: Math.PI,
35839 next: Edge_1.EdgeDirection.StepRight,
35840 prev: Edge_1.EdgeDirection.StepLeft,
35842 this.panos[Edge_1.EdgeDirection.StepLeft] = {
35843 direction: Edge_1.EdgeDirection.StepLeft,
35844 directionChange: Math.PI / 2,
35845 next: Edge_1.EdgeDirection.StepBackward,
35846 prev: Edge_1.EdgeDirection.StepForward,
35848 this.panos[Edge_1.EdgeDirection.StepRight] = {
35849 direction: Edge_1.EdgeDirection.StepRight,
35850 directionChange: -Math.PI / 2,
35851 next: Edge_1.EdgeDirection.StepForward,
35852 prev: Edge_1.EdgeDirection.StepBackward,
35855 return EdgeCalculatorDirections;
35857 exports.EdgeCalculatorDirections = EdgeCalculatorDirections;
35859 },{"../../Edge":227}],329:[function(require,module,exports){
35861 Object.defineProperty(exports, "__esModule", { value: true });
35862 var EdgeCalculatorSettings = (function () {
35863 function EdgeCalculatorSettings() {
35864 this.panoMinDistance = 0.1;
35865 this.panoMaxDistance = 20;
35866 this.panoPreferredDistance = 5;
35867 this.panoMaxItems = 4;
35868 this.panoMaxStepTurnChange = Math.PI / 8;
35869 this.rotationMaxDistance = this.turnMaxRigDistance;
35870 this.rotationMaxDirectionChange = Math.PI / 6;
35871 this.rotationMaxVerticalDirectionChange = Math.PI / 8;
35872 this.similarMaxDirectionChange = Math.PI / 8;
35873 this.similarMaxDistance = 12;
35874 this.similarMinTimeDifference = 12 * 3600 * 1000;
35875 this.stepMaxDistance = 20;
35876 this.stepMaxDirectionChange = Math.PI / 6;
35877 this.stepMaxDrift = Math.PI / 6;
35878 this.stepPreferredDistance = 4;
35879 this.turnMaxDistance = 15;
35880 this.turnMaxDirectionChange = 2 * Math.PI / 9;
35881 this.turnMaxRigDistance = 0.65;
35882 this.turnMinRigDirectionChange = Math.PI / 6;
35884 Object.defineProperty(EdgeCalculatorSettings.prototype, "maxDistance", {
35886 return Math.max(this.panoMaxDistance, this.similarMaxDistance, this.stepMaxDistance, this.turnMaxDistance);
35891 return EdgeCalculatorSettings;
35893 exports.EdgeCalculatorSettings = EdgeCalculatorSettings;
35894 exports.default = EdgeCalculatorSettings;
35896 },{}],330:[function(require,module,exports){
35898 Object.defineProperty(exports, "__esModule", { value: true });
35900 * Enumeration for edge directions
35903 * @description Directions for edges in node graph describing
35904 * sequence, spatial and node type relations between nodes.
35907 (function (EdgeDirection) {
35909 * Next node in the sequence.
35911 EdgeDirection[EdgeDirection["Next"] = 0] = "Next";
35913 * Previous node in the sequence.
35915 EdgeDirection[EdgeDirection["Prev"] = 1] = "Prev";
35917 * Step to the left keeping viewing direction.
35919 EdgeDirection[EdgeDirection["StepLeft"] = 2] = "StepLeft";
35921 * Step to the right keeping viewing direction.
35923 EdgeDirection[EdgeDirection["StepRight"] = 3] = "StepRight";
35925 * Step forward keeping viewing direction.
35927 EdgeDirection[EdgeDirection["StepForward"] = 4] = "StepForward";
35929 * Step backward keeping viewing direction.
35931 EdgeDirection[EdgeDirection["StepBackward"] = 5] = "StepBackward";
35933 * Turn 90 degrees counter clockwise.
35935 EdgeDirection[EdgeDirection["TurnLeft"] = 6] = "TurnLeft";
35937 * Turn 90 degrees clockwise.
35939 EdgeDirection[EdgeDirection["TurnRight"] = 7] = "TurnRight";
35941 * Turn 180 degrees.
35943 EdgeDirection[EdgeDirection["TurnU"] = 8] = "TurnU";
35945 * Panorama in general direction.
35947 EdgeDirection[EdgeDirection["Pano"] = 9] = "Pano";
35949 * Looking in roughly the same direction at rougly the same position.
35951 EdgeDirection[EdgeDirection["Similar"] = 10] = "Similar";
35952 })(EdgeDirection = exports.EdgeDirection || (exports.EdgeDirection = {}));
35954 },{}],331:[function(require,module,exports){
35956 /// <reference path="../../typings/index.d.ts" />
35957 Object.defineProperty(exports, "__esModule", { value: true });
35958 var _ = require("underscore");
35959 var vd = require("virtual-dom");
35960 var Subject_1 = require("rxjs/Subject");
35961 require("rxjs/add/operator/combineLatest");
35962 require("rxjs/add/operator/distinctUntilChanged");
35963 require("rxjs/add/operator/filter");
35964 require("rxjs/add/operator/map");
35965 require("rxjs/add/operator/pluck");
35966 require("rxjs/add/operator/scan");
35967 var Render_1 = require("../Render");
35968 var DOMRenderer = (function () {
35969 function DOMRenderer(element, renderService, currentFrame$) {
35970 this._adaptiveOperation$ = new Subject_1.Subject();
35971 this._render$ = new Subject_1.Subject();
35972 this._renderAdaptive$ = new Subject_1.Subject();
35973 this._renderService = renderService;
35974 this._currentFrame$ = currentFrame$;
35975 var rootNode = vd.create(vd.h("div.domRenderer", []));
35976 element.appendChild(rootNode);
35977 this._offset$ = this._adaptiveOperation$
35978 .scan(function (adaptive, operation) {
35979 return operation(adaptive);
35981 elementHeight: element.offsetHeight,
35982 elementWidth: element.offsetWidth,
35984 renderMode: Render_1.RenderMode.Fill,
35986 .filter(function (adaptive) {
35987 return adaptive.imageAspect > 0 && adaptive.elementWidth > 0 && adaptive.elementHeight > 0;
35989 .map(function (adaptive) {
35990 var elementAspect = adaptive.elementWidth / adaptive.elementHeight;
35991 var ratio = adaptive.imageAspect / elementAspect;
35992 var verticalOffset = 0;
35993 var horizontalOffset = 0;
35994 if (adaptive.renderMode === Render_1.RenderMode.Letterbox) {
35995 if (adaptive.imageAspect > elementAspect) {
35996 verticalOffset = adaptive.elementHeight * (1 - 1 / ratio) / 2;
35999 horizontalOffset = adaptive.elementWidth * (1 - ratio) / 2;
36003 if (adaptive.imageAspect > elementAspect) {
36004 horizontalOffset = -adaptive.elementWidth * (ratio - 1) / 2;
36007 verticalOffset = -adaptive.elementHeight * (1 / ratio - 1) / 2;
36011 bottom: verticalOffset,
36012 left: horizontalOffset,
36013 right: horizontalOffset,
36014 top: verticalOffset,
36017 this._currentFrame$
36018 .filter(function (frame) {
36019 return frame.state.currentNode != null;
36021 .distinctUntilChanged(function (k1, k2) {
36023 }, function (frame) {
36024 return frame.state.currentNode.key;
36026 .map(function (frame) {
36027 return frame.state.currentTransform.basicAspect;
36029 .map(function (aspect) {
36030 return function (adaptive) {
36031 adaptive.imageAspect = aspect;
36035 .subscribe(this._adaptiveOperation$);
36036 this._renderAdaptive$
36037 .scan(function (vNodeHashes, vNodeHash) {
36038 if (vNodeHash.vnode == null) {
36039 delete vNodeHashes[vNodeHash.name];
36042 vNodeHashes[vNodeHash.name] = vNodeHash.vnode;
36044 return vNodeHashes;
36046 .combineLatest(this._offset$)
36047 .map(function (vo) {
36048 var vNodes = _.values(vo[0]);
36049 var offset = vo[1];
36052 bottom: offset.bottom + "px",
36053 left: offset.left + "px",
36054 "pointer-events": "none",
36055 position: "absolute",
36056 right: offset.right + "px",
36057 top: offset.top + "px",
36061 name: "adaptiveDomRenderer",
36062 vnode: vd.h("div.adaptiveDomRenderer", properties, vNodes),
36065 .subscribe(this._render$);
36066 this._vNode$ = this._render$
36067 .scan(function (vNodeHashes, vNodeHash) {
36068 if (vNodeHash.vnode == null) {
36069 delete vNodeHashes[vNodeHash.name];
36072 vNodeHashes[vNodeHash.name] = vNodeHash.vnode;
36074 return vNodeHashes;
36076 .map(function (vNodeHashes) {
36077 var vNodes = _.values(vNodeHashes);
36078 return vd.h("div.domRenderer", vNodes);
36080 this._vPatch$ = this._vNode$
36081 .scan(function (nodePatch, vNode) {
36082 nodePatch.vpatch = vd.diff(nodePatch.vnode, vNode);
36083 nodePatch.vnode = vNode;
36085 }, { vnode: vd.h("div.domRenderer", []), vpatch: null })
36087 this._element$ = this._vPatch$
36088 .scan(function (oldElement, vPatch) {
36089 return vd.patch(oldElement, vPatch);
36093 this._element$.subscribe(function () { });
36094 this._renderService.size$
36095 .map(function (size) {
36096 return function (adaptive) {
36097 adaptive.elementWidth = size.width;
36098 adaptive.elementHeight = size.height;
36102 .subscribe(this._adaptiveOperation$);
36103 this._renderService.renderMode$
36104 .map(function (renderMode) {
36105 return function (adaptive) {
36106 adaptive.renderMode = renderMode;
36110 .subscribe(this._adaptiveOperation$);
36112 Object.defineProperty(DOMRenderer.prototype, "element$", {
36114 return this._element$;
36119 Object.defineProperty(DOMRenderer.prototype, "render$", {
36121 return this._render$;
36126 Object.defineProperty(DOMRenderer.prototype, "renderAdaptive$", {
36128 return this._renderAdaptive$;
36133 DOMRenderer.prototype.clear = function (name) {
36134 this._renderAdaptive$.next({ name: name, vnode: null });
36135 this._render$.next({ name: name, vnode: null });
36137 return DOMRenderer;
36139 exports.DOMRenderer = DOMRenderer;
36140 exports.default = DOMRenderer;
36142 },{"../Render":232,"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":73,"underscore":178,"virtual-dom":182}],332:[function(require,module,exports){
36144 Object.defineProperty(exports, "__esModule", { value: true });
36146 (function (GLRenderStage) {
36147 GLRenderStage[GLRenderStage["Background"] = 0] = "Background";
36148 GLRenderStage[GLRenderStage["Foreground"] = 1] = "Foreground";
36149 })(GLRenderStage = exports.GLRenderStage || (exports.GLRenderStage = {}));
36150 exports.default = GLRenderStage;
36152 },{}],333:[function(require,module,exports){
36154 /// <reference path="../../typings/index.d.ts" />
36155 Object.defineProperty(exports, "__esModule", { value: true });
36156 var THREE = require("three");
36157 var Observable_1 = require("rxjs/Observable");
36158 var Subject_1 = require("rxjs/Subject");
36159 require("rxjs/add/observable/combineLatest");
36160 require("rxjs/add/operator/distinctUntilChanged");
36161 require("rxjs/add/operator/filter");
36162 require("rxjs/add/operator/first");
36163 require("rxjs/add/operator/map");
36164 require("rxjs/add/operator/merge");
36165 require("rxjs/add/operator/mergeMap");
36166 require("rxjs/add/operator/scan");
36167 require("rxjs/add/operator/share");
36168 require("rxjs/add/operator/startWith");
36169 var Render_1 = require("../Render");
36170 var GLRenderer = (function () {
36171 function GLRenderer(canvasContainer, renderService) {
36173 this._renderFrame$ = new Subject_1.Subject();
36174 this._renderCameraOperation$ = new Subject_1.Subject();
36175 this._render$ = new Subject_1.Subject();
36176 this._clear$ = new Subject_1.Subject();
36177 this._renderOperation$ = new Subject_1.Subject();
36178 this._rendererOperation$ = new Subject_1.Subject();
36179 this._eraserOperation$ = new Subject_1.Subject();
36180 this._renderService = renderService;
36181 this._renderer$ = this._rendererOperation$
36182 .scan(function (renderer, operation) {
36183 return operation(renderer);
36184 }, { needsRender: false, renderer: null });
36185 this._renderCollection$ = this._renderOperation$
36186 .scan(function (hashes, operation) {
36187 return operation(hashes);
36190 this._renderCamera$ = this._renderCameraOperation$
36191 .scan(function (rc, operation) {
36192 return operation(rc);
36193 }, { frameId: -1, needsRender: false, perspective: null });
36194 this._eraser$ = this._eraserOperation$
36195 .startWith(function (eraser) {
36198 .scan(function (eraser, operation) {
36199 return operation(eraser);
36200 }, { needsRender: false });
36201 Observable_1.Observable
36202 .combineLatest([this._renderer$, this._renderCollection$, this._renderCamera$, this._eraser$], function (renderer, hashes, rc, eraser) {
36203 var renders = Object.keys(hashes)
36204 .map(function (key) {
36205 return hashes[key];
36207 return { camera: rc, eraser: eraser, renderer: renderer, renders: renders };
36209 .filter(function (co) {
36210 var needsRender = co.renderer.needsRender ||
36211 co.camera.needsRender ||
36212 co.eraser.needsRender;
36213 var frameId = co.camera.frameId;
36214 for (var _i = 0, _a = co.renders; _i < _a.length; _i++) {
36215 var render = _a[_i];
36216 if (render.frameId !== frameId) {
36219 needsRender = needsRender || render.needsRender;
36221 return needsRender;
36223 .distinctUntilChanged(function (n1, n2) {
36226 return co.eraser.needsRender ? -1 : co.camera.frameId;
36228 .subscribe(function (co) {
36229 co.renderer.needsRender = false;
36230 co.camera.needsRender = false;
36231 co.eraser.needsRender = false;
36232 var perspectiveCamera = co.camera.perspective;
36233 var backgroundRenders = [];
36234 var foregroundRenders = [];
36235 for (var _i = 0, _a = co.renders; _i < _a.length; _i++) {
36236 var render = _a[_i];
36237 if (render.stage === Render_1.GLRenderStage.Background) {
36238 backgroundRenders.push(render.render);
36240 else if (render.stage === Render_1.GLRenderStage.Foreground) {
36241 foregroundRenders.push(render.render);
36244 var renderer = co.renderer.renderer;
36246 for (var _b = 0, backgroundRenders_1 = backgroundRenders; _b < backgroundRenders_1.length; _b++) {
36247 var render = backgroundRenders_1[_b];
36248 render(perspectiveCamera, renderer);
36250 renderer.clearDepth();
36251 for (var _c = 0, foregroundRenders_1 = foregroundRenders; _c < foregroundRenders_1.length; _c++) {
36252 var render = foregroundRenders_1[_c];
36253 render(perspectiveCamera, renderer);
36257 .map(function (rc) {
36258 return function (irc) {
36259 irc.frameId = rc.frameId;
36260 irc.perspective = rc.perspective;
36261 if (rc.changed === true) {
36262 irc.needsRender = true;
36267 .subscribe(this._renderCameraOperation$);
36268 this._renderFrameSubscribe();
36269 var renderHash$ = this._render$
36270 .map(function (hash) {
36271 return function (hashes) {
36272 hashes[hash.name] = hash.render;
36276 var clearHash$ = this._clear$
36277 .map(function (name) {
36278 return function (hashes) {
36279 delete hashes[name];
36283 Observable_1.Observable
36284 .merge(renderHash$, clearHash$)
36285 .subscribe(this._renderOperation$);
36286 this._webGLRenderer$ = this._render$
36288 .map(function (hash) {
36289 var canvas = document.createElement("canvas");
36290 canvas.className = "mapillary-js-canvas";
36291 canvas.style.position = "absolute";
36292 canvas.setAttribute("tabindex", "0");
36293 canvasContainer.appendChild(canvas);
36294 var element = renderService.element;
36295 var webGLRenderer = new THREE.WebGLRenderer({ canvas: canvas });
36296 webGLRenderer.setPixelRatio(window.devicePixelRatio);
36297 webGLRenderer.setSize(element.offsetWidth, element.offsetHeight);
36298 webGLRenderer.setClearColor(new THREE.Color(0x202020), 1.0);
36299 webGLRenderer.autoClear = false;
36300 return webGLRenderer;
36304 this._webGLRenderer$.subscribe(function () { });
36305 var createRenderer$ = this._webGLRenderer$
36307 .map(function (webGLRenderer) {
36308 return function (renderer) {
36309 renderer.needsRender = true;
36310 renderer.renderer = webGLRenderer;
36314 var resizeRenderer$ = this._renderService.size$
36315 .map(function (size) {
36316 return function (renderer) {
36317 if (renderer.renderer == null) {
36320 renderer.renderer.setSize(size.width, size.height);
36321 renderer.needsRender = true;
36325 var clearRenderer$ = this._clear$
36326 .map(function (name) {
36327 return function (renderer) {
36328 if (renderer.renderer == null) {
36331 renderer.needsRender = true;
36335 Observable_1.Observable
36336 .merge(createRenderer$, resizeRenderer$, clearRenderer$)
36337 .subscribe(this._rendererOperation$);
36338 var renderCollectionEmpty$ = this._renderCollection$
36339 .filter(function (hashes) {
36340 return Object.keys(hashes).length === 0;
36343 renderCollectionEmpty$
36344 .subscribe(function (hashes) {
36345 if (_this._renderFrameSubscription == null) {
36348 _this._renderFrameSubscription.unsubscribe();
36349 _this._renderFrameSubscription = null;
36350 _this._renderFrameSubscribe();
36352 renderCollectionEmpty$
36353 .map(function (hashes) {
36354 return function (eraser) {
36355 eraser.needsRender = true;
36359 .subscribe(this._eraserOperation$);
36361 Object.defineProperty(GLRenderer.prototype, "render$", {
36363 return this._render$;
36368 Object.defineProperty(GLRenderer.prototype, "webGLRenderer$", {
36370 return this._webGLRenderer$;
36375 GLRenderer.prototype.clear = function (name) {
36376 this._clear$.next(name);
36378 GLRenderer.prototype._renderFrameSubscribe = function () {
36382 .map(function (renderHash) {
36383 return function (irc) {
36384 irc.needsRender = true;
36388 .subscribe(function (operation) {
36389 _this._renderCameraOperation$.next(operation);
36391 this._renderFrameSubscription = this._render$
36393 .mergeMap(function (hash) {
36394 return _this._renderService.renderCameraFrame$;
36396 .subscribe(this._renderFrame$);
36400 exports.GLRenderer = GLRenderer;
36401 exports.default = GLRenderer;
36403 },{"../Render":232,"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":73,"rxjs/add/operator/share":74,"rxjs/add/operator/startWith":78,"three":176}],334:[function(require,module,exports){
36405 /// <reference path="../../typings/index.d.ts" />
36406 Object.defineProperty(exports, "__esModule", { value: true });
36407 var THREE = require("three");
36408 var Geo_1 = require("../Geo");
36409 var Render_1 = require("../Render");
36410 var RenderCamera = (function () {
36411 function RenderCamera(elementWidth, elementHeight, renderMode) {
36414 this._frameId = -1;
36415 this._changed = false;
36416 this._changedForFrame = -1;
36417 this.currentAspect = 1;
36418 this.currentPano = false;
36419 this.previousAspect = 1;
36420 this.previousPano = false;
36421 this.renderMode = renderMode;
36422 this._spatial = new Geo_1.Spatial();
36423 this._camera = new Geo_1.Camera();
36424 var perspectiveCameraAspect = this._getPerspectiveCameraAspect(elementWidth, elementHeight);
36425 this._perspective = new THREE.PerspectiveCamera(50, perspectiveCameraAspect, 0.4, 10000);
36426 this._perspective.matrixAutoUpdate = false;
36427 this._rotation = { phi: 0, theta: 0 };
36429 Object.defineProperty(RenderCamera.prototype, "camera", {
36431 return this._camera;
36436 Object.defineProperty(RenderCamera.prototype, "changed", {
36438 return this.frameId === this._changedForFrame;
36443 Object.defineProperty(RenderCamera.prototype, "frameId", {
36445 return this._frameId;
36447 set: function (value) {
36448 this._frameId = value;
36449 if (this._changed) {
36450 this._changed = false;
36451 this._changedForFrame = value;
36457 Object.defineProperty(RenderCamera.prototype, "perspective", {
36459 return this._perspective;
36464 Object.defineProperty(RenderCamera.prototype, "rotation", {
36466 return this._rotation;
36471 RenderCamera.prototype.updateAspect = function (elementWidth, elementHeight) {
36472 var perspectiveCameraAspect = this._getPerspectiveCameraAspect(elementWidth, elementHeight);
36473 this._perspective.aspect = perspectiveCameraAspect;
36474 this._changed = true;
36476 RenderCamera.prototype.updateProjection = function () {
36477 var currentAspect = this._getAspect(this.currentAspect, this.currentPano, this.perspective.aspect);
36478 var previousAspect = this._getAspect(this.previousAspect, this.previousPano, this.perspective.aspect);
36479 var aspect = (1 - this.alpha) * previousAspect + this.alpha * currentAspect;
36480 var verticalFov = this._getVerticalFov(aspect, this._camera.focal, this.zoom);
36481 this._perspective.fov = verticalFov;
36482 this._perspective.updateProjectionMatrix();
36483 this._changed = true;
36485 RenderCamera.prototype.updatePerspective = function (camera) {
36486 this._perspective.up.copy(camera.up);
36487 this._perspective.position.copy(camera.position);
36488 this._perspective.lookAt(camera.lookat);
36489 this._perspective.updateMatrix();
36490 this._perspective.updateMatrixWorld(false);
36491 this._changed = true;
36493 RenderCamera.prototype.updateRotation = function (camera) {
36494 this._rotation = this._getRotation(camera);
36496 RenderCamera.prototype._getVerticalFov = function (aspect, focal, zoom) {
36497 return 2 * Math.atan(0.5 / (Math.pow(2, zoom) * aspect * focal)) * 180 / Math.PI;
36499 RenderCamera.prototype._getAspect = function (nodeAspect, pano, perspectiveCameraAspect) {
36503 var coeff = Math.max(1, 1 / nodeAspect);
36504 var usePerspective = this.renderMode === Render_1.RenderMode.Letterbox ?
36505 nodeAspect > perspectiveCameraAspect :
36506 nodeAspect < perspectiveCameraAspect;
36507 var aspect = usePerspective ?
36508 coeff * perspectiveCameraAspect :
36509 coeff * nodeAspect;
36512 RenderCamera.prototype._getPerspectiveCameraAspect = function (elementWidth, elementHeight) {
36513 return elementWidth === 0 ? 0 : elementWidth / elementHeight;
36515 RenderCamera.prototype._getRotation = function (camera) {
36516 var direction = camera.lookat.clone().sub(camera.position);
36517 var up = camera.up.clone();
36518 var upProjection = direction.clone().dot(up);
36519 var planeProjection = direction.clone().sub(up.clone().multiplyScalar(upProjection));
36520 var phi = Math.atan2(planeProjection.y, planeProjection.x);
36521 var theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
36522 return { phi: phi, theta: theta };
36524 return RenderCamera;
36526 exports.RenderCamera = RenderCamera;
36527 exports.default = RenderCamera;
36529 },{"../Geo":229,"../Render":232,"three":176}],335:[function(require,module,exports){
36531 Object.defineProperty(exports, "__esModule", { value: true });
36533 * Enumeration for render mode
36536 * @description Modes for specifying how rendering is done
36537 * in the viewer. All modes preserves the original aspect
36538 * ratio of the images.
36541 (function (RenderMode) {
36543 * Displays all content within the viewer.
36545 * @description Black bars shown on both
36546 * sides of the content. Bars are shown
36547 * either below and above or to the left
36548 * and right of the content depending on
36549 * the aspect ratio relation between the
36550 * image and the viewer.
36552 RenderMode[RenderMode["Letterbox"] = 0] = "Letterbox";
36554 * Fills the viewer by cropping content.
36556 * @description Cropping is done either
36557 * in horizontal or vertical direction
36558 * depending on the aspect ratio relation
36559 * between the image and the viewer.
36561 RenderMode[RenderMode["Fill"] = 1] = "Fill";
36562 })(RenderMode = exports.RenderMode || (exports.RenderMode = {}));
36563 exports.default = RenderMode;
36565 },{}],336:[function(require,module,exports){
36567 /// <reference path="../../typings/index.d.ts" />
36568 Object.defineProperty(exports, "__esModule", { value: true });
36569 var Subject_1 = require("rxjs/Subject");
36570 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
36571 require("rxjs/add/observable/combineLatest");
36572 require("rxjs/add/operator/do");
36573 require("rxjs/add/operator/filter");
36574 require("rxjs/add/operator/map");
36575 require("rxjs/add/operator/publishReplay");
36576 require("rxjs/add/operator/scan");
36577 require("rxjs/add/operator/skip");
36578 require("rxjs/add/operator/startWith");
36579 require("rxjs/add/operator/withLatestFrom");
36580 var Geo_1 = require("../Geo");
36581 var Render_1 = require("../Render");
36582 var RenderService = (function () {
36583 function RenderService(element, currentFrame$, renderMode) {
36585 this._element = element;
36586 this._currentFrame$ = currentFrame$;
36587 this._spatial = new Geo_1.Spatial();
36588 renderMode = renderMode != null ? renderMode : Render_1.RenderMode.Fill;
36589 this._resize$ = new Subject_1.Subject();
36590 this._renderCameraOperation$ = new Subject_1.Subject();
36592 new BehaviorSubject_1.BehaviorSubject({
36593 height: this._element.offsetHeight,
36594 width: this._element.offsetWidth,
36598 return { height: _this._element.offsetHeight, width: _this._element.offsetWidth };
36600 .subscribe(this._size$);
36601 this._renderMode$ = new BehaviorSubject_1.BehaviorSubject(renderMode);
36602 this._renderCameraHolder$ = this._renderCameraOperation$
36603 .startWith(function (rc) {
36606 .scan(function (rc, operation) {
36607 return operation(rc);
36608 }, new Render_1.RenderCamera(this._element.offsetWidth, this._element.offsetHeight, renderMode))
36611 this._renderCameraFrame$ = this._currentFrame$
36612 .withLatestFrom(this._renderCameraHolder$, function (frame, renderCamera) {
36613 return [frame, renderCamera];
36615 .do(function (args) {
36616 var frame = args[0];
36618 var camera = frame.state.camera;
36619 if (rc.alpha !== frame.state.alpha ||
36620 rc.zoom !== frame.state.zoom ||
36621 rc.camera.diff(camera) > 1e-9) {
36622 var currentTransform = frame.state.currentTransform;
36623 var previousTransform = frame.state.previousTransform != null ?
36624 frame.state.previousTransform :
36625 frame.state.currentTransform;
36626 var previousNode = frame.state.previousNode != null ?
36627 frame.state.previousNode :
36628 frame.state.currentNode;
36629 rc.currentAspect = currentTransform.basicAspect;
36630 rc.currentPano = frame.state.currentNode.pano;
36631 rc.previousAspect = previousTransform.basicAspect;
36632 rc.previousPano = previousNode.pano;
36633 rc.alpha = frame.state.alpha;
36634 rc.zoom = frame.state.zoom;
36635 rc.camera.copy(camera);
36636 rc.updatePerspective(camera);
36637 rc.updateRotation(camera);
36638 rc.updateProjection();
36640 rc.frameId = frame.id;
36642 .map(function (args) {
36647 this._renderCamera$ = this._renderCameraFrame$
36648 .filter(function (rc) {
36653 this._bearing$ = this._renderCamera$
36654 .map(function (renderCamera) {
36655 var bearing = _this._spatial.radToDeg(_this._spatial.azimuthalToBearing(renderCamera.rotation.phi));
36656 return _this._spatial.wrap(bearing, 0, 360);
36662 .map(function (size) {
36663 return function (rc) {
36664 rc.updateAspect(size.width, size.height);
36665 rc.updateProjection();
36669 .subscribe(this._renderCameraOperation$);
36672 .map(function (rm) {
36673 return function (rc) {
36674 rc.renderMode = rm;
36675 rc.updateProjection();
36679 .subscribe(this._renderCameraOperation$);
36680 this._bearing$.subscribe(function () { });
36681 this._renderCameraHolder$.subscribe(function () { });
36682 this._size$.subscribe(function () { });
36683 this._renderMode$.subscribe(function () { });
36684 this._renderCamera$.subscribe(function () { });
36685 this._renderCameraFrame$.subscribe(function () { });
36687 Object.defineProperty(RenderService.prototype, "bearing$", {
36689 return this._bearing$;
36694 Object.defineProperty(RenderService.prototype, "element", {
36696 return this._element;
36701 Object.defineProperty(RenderService.prototype, "resize$", {
36703 return this._resize$;
36708 Object.defineProperty(RenderService.prototype, "size$", {
36710 return this._size$;
36715 Object.defineProperty(RenderService.prototype, "renderMode$", {
36717 return this._renderMode$;
36722 Object.defineProperty(RenderService.prototype, "renderCameraFrame$", {
36724 return this._renderCameraFrame$;
36729 Object.defineProperty(RenderService.prototype, "renderCamera$", {
36731 return this._renderCamera$;
36736 return RenderService;
36738 exports.RenderService = RenderService;
36739 exports.default = RenderService;
36741 },{"../Geo":229,"../Render":232,"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":73,"rxjs/add/operator/skip":75,"rxjs/add/operator/startWith":78,"rxjs/add/operator/withLatestFrom":83}],337:[function(require,module,exports){
36743 Object.defineProperty(exports, "__esModule", { value: true });
36745 (function (State) {
36746 State[State["Traversing"] = 0] = "Traversing";
36747 State[State["Waiting"] = 1] = "Waiting";
36748 })(State = exports.State || (exports.State = {}));
36749 exports.default = State;
36751 },{}],338:[function(require,module,exports){
36753 Object.defineProperty(exports, "__esModule", { value: true });
36754 var State_1 = require("../State");
36755 var Geo_1 = require("../Geo");
36756 var StateContext = (function () {
36757 function StateContext() {
36758 this._state = new State_1.TraversingState({
36760 camera: new Geo_1.Camera(),
36762 reference: { alt: 0, lat: 0, lon: 0 },
36767 StateContext.prototype.traverse = function () {
36768 this._state = this._state.traverse();
36770 StateContext.prototype.wait = function () {
36771 this._state = this._state.wait();
36773 Object.defineProperty(StateContext.prototype, "state", {
36775 if (this._state instanceof State_1.TraversingState) {
36776 return State_1.State.Traversing;
36778 else if (this._state instanceof State_1.WaitingState) {
36779 return State_1.State.Waiting;
36781 throw new Error("Invalid state");
36786 Object.defineProperty(StateContext.prototype, "reference", {
36788 return this._state.reference;
36793 Object.defineProperty(StateContext.prototype, "alpha", {
36795 return this._state.alpha;
36800 Object.defineProperty(StateContext.prototype, "camera", {
36802 return this._state.camera;
36807 Object.defineProperty(StateContext.prototype, "zoom", {
36809 return this._state.zoom;
36814 Object.defineProperty(StateContext.prototype, "currentNode", {
36816 return this._state.currentNode;
36821 Object.defineProperty(StateContext.prototype, "previousNode", {
36823 return this._state.previousNode;
36828 Object.defineProperty(StateContext.prototype, "currentCamera", {
36830 return this._state.currentCamera;
36835 Object.defineProperty(StateContext.prototype, "currentTransform", {
36837 return this._state.currentTransform;
36842 Object.defineProperty(StateContext.prototype, "previousTransform", {
36844 return this._state.previousTransform;
36849 Object.defineProperty(StateContext.prototype, "trajectory", {
36851 return this._state.trajectory;
36856 Object.defineProperty(StateContext.prototype, "currentIndex", {
36858 return this._state.currentIndex;
36863 Object.defineProperty(StateContext.prototype, "lastNode", {
36865 return this._state.trajectory[this._state.trajectory.length - 1];
36870 Object.defineProperty(StateContext.prototype, "nodesAhead", {
36872 return this._state.trajectory.length - 1 - this._state.currentIndex;
36877 Object.defineProperty(StateContext.prototype, "motionless", {
36879 return this._state.motionless;
36884 StateContext.prototype.getCenter = function () {
36885 return this._state.getCenter();
36887 StateContext.prototype.setCenter = function (center) {
36888 this._state.setCenter(center);
36890 StateContext.prototype.setZoom = function (zoom) {
36891 this._state.setZoom(zoom);
36893 StateContext.prototype.update = function (fps) {
36894 this._state.update(fps);
36896 StateContext.prototype.append = function (nodes) {
36897 this._state.append(nodes);
36899 StateContext.prototype.prepend = function (nodes) {
36900 this._state.prepend(nodes);
36902 StateContext.prototype.remove = function (n) {
36903 this._state.remove(n);
36905 StateContext.prototype.clear = function () {
36906 this._state.clear();
36908 StateContext.prototype.clearPrior = function () {
36909 this._state.clearPrior();
36911 StateContext.prototype.cut = function () {
36914 StateContext.prototype.set = function (nodes) {
36915 this._state.set(nodes);
36917 StateContext.prototype.rotate = function (delta) {
36918 this._state.rotate(delta);
36920 StateContext.prototype.rotateBasic = function (basicRotation) {
36921 this._state.rotateBasic(basicRotation);
36923 StateContext.prototype.rotateBasicUnbounded = function (basicRotation) {
36924 this._state.rotateBasicUnbounded(basicRotation);
36926 StateContext.prototype.rotateToBasic = function (basic) {
36927 this._state.rotateToBasic(basic);
36929 StateContext.prototype.move = function (delta) {
36930 this._state.move(delta);
36932 StateContext.prototype.moveTo = function (delta) {
36933 this._state.moveTo(delta);
36935 StateContext.prototype.zoomIn = function (delta, reference) {
36936 this._state.zoomIn(delta, reference);
36938 return StateContext;
36940 exports.StateContext = StateContext;
36942 },{"../Geo":229,"../State":233}],339:[function(require,module,exports){
36944 Object.defineProperty(exports, "__esModule", { value: true });
36945 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
36946 var Subject_1 = require("rxjs/Subject");
36947 var AnimationFrame_1 = require("rxjs/util/AnimationFrame");
36948 require("rxjs/add/operator/bufferCount");
36949 require("rxjs/add/operator/distinctUntilChanged");
36950 require("rxjs/add/operator/do");
36951 require("rxjs/add/operator/filter");
36952 require("rxjs/add/operator/first");
36953 require("rxjs/add/operator/map");
36954 require("rxjs/add/operator/pairwise");
36955 require("rxjs/add/operator/publishReplay");
36956 require("rxjs/add/operator/scan");
36957 require("rxjs/add/operator/startWith");
36958 require("rxjs/add/operator/switchMap");
36959 require("rxjs/add/operator/withLatestFrom");
36960 var State_1 = require("../State");
36961 var StateService = (function () {
36962 function StateService() {
36964 this._appendNode$ = new Subject_1.Subject();
36965 this._start$ = new Subject_1.Subject();
36966 this._frame$ = new Subject_1.Subject();
36967 this._fpsSampleRate = 30;
36968 this._contextOperation$ = new BehaviorSubject_1.BehaviorSubject(function (context) {
36971 this._context$ = this._contextOperation$
36972 .scan(function (context, operation) {
36973 return operation(context);
36974 }, new State_1.StateContext())
36977 this._state$ = this._context$
36978 .map(function (context) {
36979 return context.state;
36981 .distinctUntilChanged()
36984 this._fps$ = this._start$
36985 .switchMap(function () {
36986 return _this._frame$
36987 .bufferCount(1, _this._fpsSampleRate)
36988 .map(function (frameIds) {
36989 return new Date().getTime();
36992 .map(function (times) {
36993 return Math.max(20, 1000 * _this._fpsSampleRate / (times[1] - times[0]));
36998 this._currentState$ = this._frame$
36999 .withLatestFrom(this._fps$, this._context$, function (frameId, fps, context) {
37000 return [frameId, fps, context];
37002 .filter(function (fc) {
37003 return fc[2].currentNode != null;
37005 .do(function (fc) {
37006 fc[2].update(fc[1]);
37008 .map(function (fc) {
37009 return { fps: fc[1], id: fc[0], state: fc[2] };
37012 this._lastState$ = this._currentState$
37015 var nodeChanged$ = this._currentState$
37016 .distinctUntilChanged(undefined, function (f) {
37017 return f.state.currentNode.key;
37021 var nodeChangedSubject$ = new Subject_1.Subject();
37023 .subscribe(nodeChangedSubject$);
37024 this._currentKey$ = new BehaviorSubject_1.BehaviorSubject(null);
37025 nodeChangedSubject$
37026 .map(function (f) {
37027 return f.state.currentNode.key;
37029 .subscribe(this._currentKey$);
37030 this._currentNode$ = nodeChangedSubject$
37031 .map(function (f) {
37032 return f.state.currentNode;
37036 this._currentCamera$ = nodeChangedSubject$
37037 .map(function (f) {
37038 return f.state.currentCamera;
37042 this._currentTransform$ = nodeChangedSubject$
37043 .map(function (f) {
37044 return f.state.currentTransform;
37048 this._reference$ = nodeChangedSubject$
37049 .map(function (f) {
37050 return f.state.reference;
37052 .distinctUntilChanged(function (r1, r2) {
37053 return r1.lat === r2.lat && r1.lon === r2.lon;
37054 }, function (reference) {
37055 return { lat: reference.lat, lon: reference.lon };
37059 this._currentNodeExternal$ = nodeChanged$
37060 .map(function (f) {
37061 return f.state.currentNode;
37066 .map(function (node) {
37067 return function (context) {
37068 context.append([node]);
37072 .subscribe(this._contextOperation$);
37073 this._inMotionOperation$ = new Subject_1.Subject();
37075 .map(function (frame) {
37078 .subscribe(this._inMotionOperation$);
37079 this._inMotionOperation$
37080 .distinctUntilChanged()
37081 .filter(function (moving) {
37084 .switchMap(function (moving) {
37085 return _this._currentState$
37086 .filter(function (frame) {
37087 return frame.state.nodesAhead === 0;
37089 .map(function (frame) {
37090 return [frame.state.camera.clone(), frame.state.zoom];
37093 .map(function (pair) {
37094 var c1 = pair[0][0];
37095 var c2 = pair[1][0];
37096 var z1 = pair[0][1];
37097 var z2 = pair[1][1];
37098 return c1.diff(c2) > 1e-5 || Math.abs(z1 - z2) > 1e-5;
37100 .first(function (changed) {
37104 .subscribe(this._inMotionOperation$);
37105 this._inMotion$ = this._inMotionOperation$
37106 .distinctUntilChanged()
37109 this._inTranslationOperation$ = new Subject_1.Subject();
37111 .map(function (frame) {
37114 .subscribe(this._inTranslationOperation$);
37115 this._inTranslationOperation$
37116 .distinctUntilChanged()
37117 .filter(function (inTranslation) {
37118 return inTranslation;
37120 .switchMap(function (inTranslation) {
37121 return _this._currentState$
37122 .filter(function (frame) {
37123 return frame.state.nodesAhead === 0;
37125 .map(function (frame) {
37126 return frame.state.camera.position.clone();
37129 .map(function (pair) {
37130 return pair[0].distanceToSquared(pair[1]) !== 0;
37132 .first(function (changed) {
37136 .subscribe(this._inTranslationOperation$);
37137 this._inTranslation$ = this._inTranslationOperation$
37138 .distinctUntilChanged()
37141 this._state$.subscribe(function () { });
37142 this._currentNode$.subscribe(function () { });
37143 this._currentCamera$.subscribe(function () { });
37144 this._currentTransform$.subscribe(function () { });
37145 this._reference$.subscribe(function () { });
37146 this._currentNodeExternal$.subscribe(function () { });
37147 this._lastState$.subscribe(function () { });
37148 this._inMotion$.subscribe(function () { });
37149 this._inTranslation$.subscribe(function () { });
37150 this._frameId = null;
37151 this._frameGenerator = new AnimationFrame_1.RequestAnimationFrameDefinition(window);
37153 Object.defineProperty(StateService.prototype, "currentState$", {
37155 return this._currentState$;
37160 Object.defineProperty(StateService.prototype, "currentNode$", {
37162 return this._currentNode$;
37167 Object.defineProperty(StateService.prototype, "currentKey$", {
37169 return this._currentKey$;
37174 Object.defineProperty(StateService.prototype, "currentNodeExternal$", {
37176 return this._currentNodeExternal$;
37181 Object.defineProperty(StateService.prototype, "currentCamera$", {
37183 return this._currentCamera$;
37188 Object.defineProperty(StateService.prototype, "currentTransform$", {
37190 return this._currentTransform$;
37195 Object.defineProperty(StateService.prototype, "state$", {
37197 return this._state$;
37202 Object.defineProperty(StateService.prototype, "reference$", {
37204 return this._reference$;
37209 Object.defineProperty(StateService.prototype, "inMotion$", {
37211 return this._inMotion$;
37216 Object.defineProperty(StateService.prototype, "inTranslation$", {
37218 return this._inTranslation$;
37223 Object.defineProperty(StateService.prototype, "appendNode$", {
37225 return this._appendNode$;
37230 StateService.prototype.traverse = function () {
37231 this._inMotionOperation$.next(true);
37232 this._invokeContextOperation(function (context) { context.traverse(); });
37234 StateService.prototype.wait = function () {
37235 this._invokeContextOperation(function (context) { context.wait(); });
37237 StateService.prototype.appendNodes = function (nodes) {
37238 this._invokeContextOperation(function (context) { context.append(nodes); });
37240 StateService.prototype.prependNodes = function (nodes) {
37241 this._invokeContextOperation(function (context) { context.prepend(nodes); });
37243 StateService.prototype.removeNodes = function (n) {
37244 this._invokeContextOperation(function (context) { context.remove(n); });
37246 StateService.prototype.clearNodes = function () {
37247 this._invokeContextOperation(function (context) { context.clear(); });
37249 StateService.prototype.clearPriorNodes = function () {
37250 this._invokeContextOperation(function (context) { context.clearPrior(); });
37252 StateService.prototype.cutNodes = function () {
37253 this._invokeContextOperation(function (context) { context.cut(); });
37255 StateService.prototype.setNodes = function (nodes) {
37256 this._invokeContextOperation(function (context) { context.set(nodes); });
37258 StateService.prototype.rotate = function (delta) {
37259 this._inMotionOperation$.next(true);
37260 this._invokeContextOperation(function (context) { context.rotate(delta); });
37262 StateService.prototype.rotateBasic = function (basicRotation) {
37263 this._inMotionOperation$.next(true);
37264 this._invokeContextOperation(function (context) { context.rotateBasic(basicRotation); });
37266 StateService.prototype.rotateBasicUnbounded = function (basicRotation) {
37267 this._inMotionOperation$.next(true);
37268 this._invokeContextOperation(function (context) { context.rotateBasicUnbounded(basicRotation); });
37270 StateService.prototype.rotateToBasic = function (basic) {
37271 this._inMotionOperation$.next(true);
37272 this._invokeContextOperation(function (context) { context.rotateToBasic(basic); });
37274 StateService.prototype.move = function (delta) {
37275 this._inMotionOperation$.next(true);
37276 this._invokeContextOperation(function (context) { context.move(delta); });
37278 StateService.prototype.moveTo = function (position) {
37279 this._inMotionOperation$.next(true);
37280 this._invokeContextOperation(function (context) { context.moveTo(position); });
37283 * Change zoom level while keeping the reference point position approximately static.
37285 * @parameter {number} delta - Change in zoom level.
37286 * @parameter {Array<number>} reference - Reference point in basic coordinates.
37288 StateService.prototype.zoomIn = function (delta, reference) {
37289 this._inMotionOperation$.next(true);
37290 this._invokeContextOperation(function (context) { context.zoomIn(delta, reference); });
37292 StateService.prototype.getCenter = function () {
37293 return this._lastState$
37295 .map(function (frame) {
37296 return frame.state.getCenter();
37299 StateService.prototype.getZoom = function () {
37300 return this._lastState$
37302 .map(function (frame) {
37303 return frame.state.zoom;
37306 StateService.prototype.setCenter = function (center) {
37307 this._inMotionOperation$.next(true);
37308 this._invokeContextOperation(function (context) { context.setCenter(center); });
37310 StateService.prototype.setZoom = function (zoom) {
37311 this._inMotionOperation$.next(true);
37312 this._invokeContextOperation(function (context) { context.setZoom(zoom); });
37314 StateService.prototype.start = function () {
37315 if (this._frameId == null) {
37316 this._start$.next(null);
37317 this._frameId = this._frameGenerator.requestAnimationFrame(this._frame.bind(this));
37318 this._frame$.next(this._frameId);
37321 StateService.prototype.stop = function () {
37322 if (this._frameId != null) {
37323 this._frameGenerator.cancelAnimationFrame(this._frameId);
37324 this._frameId = null;
37327 StateService.prototype._invokeContextOperation = function (action) {
37328 this._contextOperation$
37329 .next(function (context) {
37334 StateService.prototype._frame = function (time) {
37335 this._frameId = this._frameGenerator.requestAnimationFrame(this._frame.bind(this));
37336 this._frame$.next(this._frameId);
37338 return StateService;
37340 exports.StateService = StateService;
37342 },{"../State":233,"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":73,"rxjs/add/operator/startWith":78,"rxjs/add/operator/switchMap":79,"rxjs/add/operator/withLatestFrom":83,"rxjs/util/AnimationFrame":157}],340:[function(require,module,exports){
37344 /// <reference path="../../../typings/index.d.ts" />
37345 Object.defineProperty(exports, "__esModule", { value: true });
37346 var Error_1 = require("../../Error");
37347 var Geo_1 = require("../../Geo");
37348 var StateBase = (function () {
37349 function StateBase(state) {
37350 this._spatial = new Geo_1.Spatial();
37351 this._geoCoords = new Geo_1.GeoCoords();
37352 this._referenceThreshold = 0.01;
37353 this._reference = state.reference;
37354 this._alpha = state.alpha;
37355 this._camera = state.camera.clone();
37356 this._zoom = state.zoom;
37357 this._currentIndex = state.currentIndex;
37358 this._trajectory = state.trajectory.slice();
37359 this._trajectoryTransforms = [];
37360 this._trajectoryCameras = [];
37361 for (var _i = 0, _a = this._trajectory; _i < _a.length; _i++) {
37363 var translation = this._nodeToTranslation(node);
37364 var transform = new Geo_1.Transform(node, node.image, translation);
37365 this._trajectoryTransforms.push(transform);
37366 this._trajectoryCameras.push(new Geo_1.Camera(transform));
37368 this._currentNode = this._trajectory.length > 0 ?
37369 this._trajectory[this._currentIndex] :
37371 this._previousNode = this._trajectory.length > 1 && this.currentIndex > 0 ?
37372 this._trajectory[this._currentIndex - 1] :
37374 this._currentCamera = this._trajectoryCameras.length > 0 ?
37375 this._trajectoryCameras[this._currentIndex].clone() :
37376 new Geo_1.Camera();
37377 this._previousCamera = this._trajectoryCameras.length > 1 && this.currentIndex > 0 ?
37378 this._trajectoryCameras[this._currentIndex - 1].clone() :
37379 this._currentCamera.clone();
37381 Object.defineProperty(StateBase.prototype, "reference", {
37383 return this._reference;
37388 Object.defineProperty(StateBase.prototype, "alpha", {
37390 return this._getAlpha();
37395 Object.defineProperty(StateBase.prototype, "camera", {
37397 return this._camera;
37402 Object.defineProperty(StateBase.prototype, "zoom", {
37409 Object.defineProperty(StateBase.prototype, "trajectory", {
37411 return this._trajectory;
37416 Object.defineProperty(StateBase.prototype, "currentIndex", {
37418 return this._currentIndex;
37423 Object.defineProperty(StateBase.prototype, "currentNode", {
37425 return this._currentNode;
37430 Object.defineProperty(StateBase.prototype, "previousNode", {
37432 return this._previousNode;
37437 Object.defineProperty(StateBase.prototype, "currentCamera", {
37439 return this._currentCamera;
37444 Object.defineProperty(StateBase.prototype, "currentTransform", {
37446 return this._trajectoryTransforms.length > 0 ?
37447 this._trajectoryTransforms[this.currentIndex] : null;
37452 Object.defineProperty(StateBase.prototype, "previousTransform", {
37454 return this._trajectoryTransforms.length > 1 && this.currentIndex > 0 ?
37455 this._trajectoryTransforms[this.currentIndex - 1] : null;
37460 Object.defineProperty(StateBase.prototype, "motionless", {
37462 return this._motionless;
37467 StateBase.prototype.append = function (nodes) {
37468 if (nodes.length < 1) {
37469 throw Error("Trajectory can not be empty");
37471 if (this._currentIndex < 0) {
37475 this._trajectory = this._trajectory.concat(nodes);
37476 this._appendToTrajectories(nodes);
37479 StateBase.prototype.prepend = function (nodes) {
37480 if (nodes.length < 1) {
37481 throw Error("Trajectory can not be empty");
37483 this._trajectory = nodes.slice().concat(this._trajectory);
37484 this._currentIndex += nodes.length;
37485 this._setCurrentNode();
37486 var referenceReset = this._setReference(this._currentNode);
37487 if (referenceReset) {
37488 this._setTrajectories();
37491 this._prependToTrajectories(nodes);
37493 this._setCurrentCamera();
37495 StateBase.prototype.remove = function (n) {
37497 throw Error("n must be a positive integer");
37499 if (this._currentIndex - 1 < n) {
37500 throw Error("Current and previous nodes can not be removed");
37502 for (var i = 0; i < n; i++) {
37503 this._trajectory.shift();
37504 this._trajectoryTransforms.shift();
37505 this._trajectoryCameras.shift();
37506 this._currentIndex--;
37508 this._setCurrentNode();
37510 StateBase.prototype.clearPrior = function () {
37511 if (this._currentIndex > 0) {
37512 this.remove(this._currentIndex - 1);
37515 StateBase.prototype.clear = function () {
37517 if (this._currentIndex > 0) {
37518 this.remove(this._currentIndex - 1);
37521 StateBase.prototype.cut = function () {
37522 while (this._trajectory.length - 1 > this._currentIndex) {
37523 this._trajectory.pop();
37524 this._trajectoryTransforms.pop();
37525 this._trajectoryCameras.pop();
37528 StateBase.prototype.set = function (nodes) {
37529 this._setTrajectory(nodes);
37530 this._setCurrentNode();
37531 this._setReference(this._currentNode);
37532 this._setTrajectories();
37533 this._setCurrentCamera();
37535 StateBase.prototype.getCenter = function () {
37536 return this._currentNode != null ?
37537 this.currentTransform.projectBasic(this._camera.lookat.toArray()) :
37540 StateBase.prototype._setCurrent = function () {
37541 this._setCurrentNode();
37542 var referenceReset = this._setReference(this._currentNode);
37543 if (referenceReset) {
37544 this._setTrajectories();
37546 this._setCurrentCamera();
37548 StateBase.prototype._setCurrentCamera = function () {
37549 this._currentCamera = this._trajectoryCameras[this._currentIndex].clone();
37550 this._previousCamera = this._currentIndex > 0 ?
37551 this._trajectoryCameras[this._currentIndex - 1].clone() :
37552 this._currentCamera.clone();
37554 StateBase.prototype._motionlessTransition = function () {
37555 var nodesSet = this._currentNode != null && this._previousNode != null;
37556 return nodesSet && !(this._currentNode.merged &&
37557 this._previousNode.merged &&
37558 this._withinOriginalDistance() &&
37559 this._sameConnectedComponent());
37561 StateBase.prototype._setReference = function (node) {
37562 // do not reset reference if node is within threshold distance
37563 if (Math.abs(node.latLon.lat - this.reference.lat) < this._referenceThreshold &&
37564 Math.abs(node.latLon.lon - this.reference.lon) < this._referenceThreshold) {
37567 // do not reset reference if previous node exist and transition is with motion
37568 if (this._previousNode != null && !this._motionlessTransition()) {
37571 this._reference.lat = node.latLon.lat;
37572 this._reference.lon = node.latLon.lon;
37573 this._reference.alt = node.alt;
37576 StateBase.prototype._setCurrentNode = function () {
37577 this._currentNode = this._trajectory.length > 0 ?
37578 this._trajectory[this._currentIndex] :
37580 this._previousNode = this._currentIndex > 0 ?
37581 this._trajectory[this._currentIndex - 1] :
37584 StateBase.prototype._setTrajectory = function (nodes) {
37585 if (nodes.length < 1) {
37586 throw new Error_1.ArgumentMapillaryError("Trajectory can not be empty");
37588 if (this._currentNode != null) {
37589 this._trajectory = [this._currentNode].concat(nodes);
37590 this._currentIndex = 1;
37593 this._trajectory = nodes.slice();
37594 this._currentIndex = 0;
37597 StateBase.prototype._setTrajectories = function () {
37598 this._trajectoryTransforms.length = 0;
37599 this._trajectoryCameras.length = 0;
37600 this._appendToTrajectories(this._trajectory);
37602 StateBase.prototype._appendToTrajectories = function (nodes) {
37603 for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
37604 var node = nodes_1[_i];
37605 if (!node.assetsCached) {
37606 throw new Error_1.ArgumentMapillaryError("Assets must be cached when node is added to trajectory");
37608 var translation = this._nodeToTranslation(node);
37609 var transform = new Geo_1.Transform(node, node.image, translation);
37610 this._trajectoryTransforms.push(transform);
37611 this._trajectoryCameras.push(new Geo_1.Camera(transform));
37614 StateBase.prototype._prependToTrajectories = function (nodes) {
37615 for (var _i = 0, _a = nodes.reverse(); _i < _a.length; _i++) {
37617 if (!node.assetsCached) {
37618 throw new Error_1.ArgumentMapillaryError("Assets must be cached when added to trajectory");
37620 var translation = this._nodeToTranslation(node);
37621 var transform = new Geo_1.Transform(node, node.image, translation);
37622 this._trajectoryTransforms.unshift(transform);
37623 this._trajectoryCameras.unshift(new Geo_1.Camera(transform));
37626 StateBase.prototype._nodeToTranslation = function (node) {
37627 var C = this._geoCoords.geodeticToEnu(node.latLon.lat, node.latLon.lon, node.alt, this._reference.lat, this._reference.lon, this._reference.alt);
37628 var RC = this._spatial.rotate(C, node.rotation);
37629 return [-RC.x, -RC.y, -RC.z];
37631 StateBase.prototype._sameConnectedComponent = function () {
37632 var current = this._currentNode;
37633 var previous = this._previousNode;
37635 !current.mergeCC ||
37637 !previous.mergeCC) {
37640 return current.mergeCC === previous.mergeCC;
37642 StateBase.prototype._withinOriginalDistance = function () {
37643 var current = this._currentNode;
37644 var previous = this._previousNode;
37645 if (!current || !previous) {
37648 // 50 km/h moves 28m in 2s
37649 var distance = this._spatial.distanceFromLatLon(current.originalLatLon.lat, current.originalLatLon.lon, previous.originalLatLon.lat, previous.originalLatLon.lon);
37650 return distance < 25;
37654 exports.StateBase = StateBase;
37656 },{"../../Error":228,"../../Geo":229}],341:[function(require,module,exports){
37658 /// <reference path="../../../typings/index.d.ts" />
37659 var __extends = (this && this.__extends) || (function () {
37660 var extendStatics = Object.setPrototypeOf ||
37661 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
37662 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
37663 return function (d, b) {
37664 extendStatics(d, b);
37665 function __() { this.constructor = d; }
37666 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
37669 Object.defineProperty(exports, "__esModule", { value: true });
37670 var THREE = require("three");
37671 var UnitBezier = require("@mapbox/unitbezier");
37672 var State_1 = require("../../State");
37673 var RotationDelta = (function () {
37674 function RotationDelta(phi, theta) {
37676 this._theta = theta;
37678 Object.defineProperty(RotationDelta.prototype, "phi", {
37682 set: function (value) {
37688 Object.defineProperty(RotationDelta.prototype, "theta", {
37690 return this._theta;
37692 set: function (value) {
37693 this._theta = value;
37698 Object.defineProperty(RotationDelta.prototype, "isZero", {
37700 return this._phi === 0 && this._theta === 0;
37705 RotationDelta.prototype.copy = function (delta) {
37706 this._phi = delta.phi;
37707 this._theta = delta.theta;
37709 RotationDelta.prototype.lerp = function (other, alpha) {
37710 this._phi = (1 - alpha) * this._phi + alpha * other.phi;
37711 this._theta = (1 - alpha) * this._theta + alpha * other.theta;
37713 RotationDelta.prototype.multiply = function (value) {
37714 this._phi *= value;
37715 this._theta *= value;
37717 RotationDelta.prototype.threshold = function (value) {
37718 this._phi = Math.abs(this._phi) > value ? this._phi : 0;
37719 this._theta = Math.abs(this._theta) > value ? this._theta : 0;
37721 RotationDelta.prototype.lengthSquared = function () {
37722 return this._phi * this._phi + this._theta * this._theta;
37724 RotationDelta.prototype.reset = function () {
37728 return RotationDelta;
37730 var TraversingState = (function (_super) {
37731 __extends(TraversingState, _super);
37732 function TraversingState(state) {
37733 var _this = _super.call(this, state) || this;
37734 _this._adjustCameras();
37735 _this._motionless = _this._motionlessTransition();
37736 _this._baseAlpha = _this._alpha;
37737 _this._animationSpeed = 0.025;
37738 _this._unitBezier = new UnitBezier(0.74, 0.67, 0.38, 0.96);
37739 _this._useBezier = false;
37740 _this._rotationDelta = new RotationDelta(0, 0);
37741 _this._requestedRotationDelta = null;
37742 _this._basicRotation = [0, 0];
37743 _this._requestedBasicRotation = null;
37744 _this._requestedBasicRotationUnbounded = null;
37745 _this._rotationAcceleration = 0.86;
37746 _this._rotationIncreaseAlpha = 0.97;
37747 _this._rotationDecreaseAlpha = 0.9;
37748 _this._rotationThreshold = 1e-3;
37749 _this._unboundedRotationAlpha = 0.8;
37750 _this._desiredZoom = state.zoom;
37751 _this._minZoom = 0;
37752 _this._maxZoom = 3;
37753 _this._lookatDepth = 10;
37754 _this._desiredLookat = null;
37755 _this._desiredCenter = null;
37758 TraversingState.prototype.traverse = function () {
37759 throw new Error("Not implemented");
37761 TraversingState.prototype.wait = function () {
37762 return new State_1.WaitingState(this);
37764 TraversingState.prototype.append = function (nodes) {
37765 var emptyTrajectory = this._trajectory.length === 0;
37766 if (emptyTrajectory) {
37767 this._resetTransition();
37769 _super.prototype.append.call(this, nodes);
37770 if (emptyTrajectory) {
37771 this._setDesiredCenter();
37772 this._setDesiredZoom();
37775 TraversingState.prototype.prepend = function (nodes) {
37776 var emptyTrajectory = this._trajectory.length === 0;
37777 if (emptyTrajectory) {
37778 this._resetTransition();
37780 _super.prototype.prepend.call(this, nodes);
37781 if (emptyTrajectory) {
37782 this._setDesiredCenter();
37783 this._setDesiredZoom();
37786 TraversingState.prototype.set = function (nodes) {
37787 _super.prototype.set.call(this, nodes);
37788 this._desiredLookat = null;
37789 this._resetTransition();
37790 this._clearRotation();
37791 this._setDesiredCenter();
37792 this._setDesiredZoom();
37793 if (this._trajectory.length < 3) {
37794 this._useBezier = true;
37797 TraversingState.prototype.move = function (delta) {
37798 throw new Error("Not implemented");
37800 TraversingState.prototype.moveTo = function (delta) {
37801 throw new Error("Not implemented");
37803 TraversingState.prototype.rotate = function (rotationDelta) {
37804 if (this._currentNode == null) {
37807 this._desiredZoom = this._zoom;
37808 this._desiredLookat = null;
37809 this._requestedBasicRotation = null;
37810 if (this._requestedRotationDelta != null) {
37811 this._requestedRotationDelta.phi = this._requestedRotationDelta.phi + rotationDelta.phi;
37812 this._requestedRotationDelta.theta = this._requestedRotationDelta.theta + rotationDelta.theta;
37815 this._requestedRotationDelta = new RotationDelta(rotationDelta.phi, rotationDelta.theta);
37818 TraversingState.prototype.rotateBasic = function (basicRotation) {
37819 if (this._currentNode == null) {
37822 this._desiredZoom = this._zoom;
37823 this._desiredLookat = null;
37824 this._requestedRotationDelta = null;
37825 if (this._requestedBasicRotation != null) {
37826 this._requestedBasicRotation[0] += basicRotation[0];
37827 this._requestedBasicRotation[1] += basicRotation[1];
37828 var threshold = 0.05 / Math.pow(2, this._zoom);
37829 this._requestedBasicRotation[0] =
37830 this._spatial.clamp(this._requestedBasicRotation[0], -threshold, threshold);
37831 this._requestedBasicRotation[1] =
37832 this._spatial.clamp(this._requestedBasicRotation[1], -threshold, threshold);
37835 this._requestedBasicRotation = basicRotation.slice();
37838 TraversingState.prototype.rotateBasicUnbounded = function (basicRotation) {
37839 if (this._currentNode == null) {
37842 if (this._requestedBasicRotationUnbounded != null) {
37843 this._requestedBasicRotationUnbounded[0] += basicRotation[0];
37844 this._requestedBasicRotationUnbounded[1] += basicRotation[1];
37847 this._requestedBasicRotationUnbounded = basicRotation.slice();
37850 TraversingState.prototype.rotateToBasic = function (basic) {
37851 if (this._currentNode == null) {
37854 this._desiredZoom = this._zoom;
37855 this._desiredLookat = null;
37856 basic[0] = this._spatial.clamp(basic[0], 0, 1);
37857 basic[1] = this._spatial.clamp(basic[1], 0, 1);
37858 var lookat = this.currentTransform.unprojectBasic(basic, this._lookatDepth);
37859 this._currentCamera.lookat.fromArray(lookat);
37861 TraversingState.prototype.zoomIn = function (delta, reference) {
37862 if (this._currentNode == null) {
37865 this._desiredZoom = Math.max(this._minZoom, Math.min(this._maxZoom, this._desiredZoom + delta));
37866 var currentCenter = this.currentTransform.projectBasic(this._currentCamera.lookat.toArray());
37867 var currentCenterX = currentCenter[0];
37868 var currentCenterY = currentCenter[1];
37869 var zoom0 = Math.pow(2, this._zoom);
37870 var zoom1 = Math.pow(2, this._desiredZoom);
37871 var refX = reference[0];
37872 var refY = reference[1];
37873 if (this.currentTransform.gpano != null &&
37874 this.currentTransform.gpano.CroppedAreaImageWidthPixels === this.currentTransform.gpano.FullPanoWidthPixels) {
37875 if (refX - currentCenterX > 0.5) {
37878 else if (currentCenterX - refX > 0.5) {
37882 var newCenterX = refX - zoom0 / zoom1 * (refX - currentCenterX);
37883 var newCenterY = refY - zoom0 / zoom1 * (refY - currentCenterY);
37884 var gpano = this.currentTransform.gpano;
37885 if (this._currentNode.fullPano) {
37886 newCenterX = this._spatial.wrap(newCenterX + this._basicRotation[0], 0, 1);
37887 newCenterY = this._spatial.clamp(newCenterY + this._basicRotation[1], 0.05, 0.95);
37889 else if (gpano != null &&
37890 this.currentTransform.gpano.CroppedAreaImageWidthPixels === this.currentTransform.gpano.FullPanoWidthPixels) {
37891 newCenterX = this._spatial.wrap(newCenterX + this._basicRotation[0], 0, 1);
37892 newCenterY = this._spatial.clamp(newCenterY + this._basicRotation[1], 0, 1);
37895 newCenterX = this._spatial.clamp(newCenterX, 0, 1);
37896 newCenterY = this._spatial.clamp(newCenterY, 0, 1);
37898 this._desiredLookat = new THREE.Vector3()
37899 .fromArray(this.currentTransform.unprojectBasic([newCenterX, newCenterY], this._lookatDepth));
37901 TraversingState.prototype.setCenter = function (center) {
37902 this._desiredLookat = null;
37903 this._requestedRotationDelta = null;
37904 this._requestedBasicRotation = null;
37905 this._desiredZoom = this._zoom;
37907 this._spatial.clamp(center[0], 0, 1),
37908 this._spatial.clamp(center[1], 0, 1),
37910 if (this._currentNode == null) {
37911 this._desiredCenter = clamped;
37914 this._desiredCenter = null;
37915 var currentLookat = new THREE.Vector3()
37916 .fromArray(this.currentTransform.unprojectBasic(clamped, this._lookatDepth));
37917 var previousTransform = this.previousTransform != null ?
37918 this.previousTransform :
37919 this.currentTransform;
37920 var previousLookat = new THREE.Vector3()
37921 .fromArray(previousTransform.unprojectBasic(clamped, this._lookatDepth));
37922 this._currentCamera.lookat.copy(currentLookat);
37923 this._previousCamera.lookat.copy(previousLookat);
37925 TraversingState.prototype.setZoom = function (zoom) {
37926 this._desiredLookat = null;
37927 this._requestedRotationDelta = null;
37928 this._requestedBasicRotation = null;
37929 this._zoom = this._spatial.clamp(zoom, this._minZoom, this._maxZoom);
37930 this._desiredZoom = this._zoom;
37932 TraversingState.prototype.update = function (fps) {
37933 if (this._alpha === 1 && this._currentIndex + this._alpha < this._trajectory.length) {
37934 this._currentIndex += 1;
37935 this._useBezier = this._trajectory.length < 3 &&
37936 this._currentIndex + 1 === this._trajectory.length;
37937 this._setCurrent();
37938 this._resetTransition();
37939 this._clearRotation();
37940 this._desiredZoom = this._currentNode.fullPano ? this._zoom : 0;
37941 this._desiredLookat = null;
37943 var animationSpeed = this._animationSpeed * (60 / fps);
37944 this._baseAlpha = Math.min(1, this._baseAlpha + animationSpeed);
37945 if (this._useBezier) {
37946 this._alpha = this._unitBezier.solve(this._baseAlpha);
37949 this._alpha = this._baseAlpha;
37951 this._updateRotation();
37952 if (!this._rotationDelta.isZero) {
37953 this._applyRotation(this._previousCamera);
37954 this._applyRotation(this._currentCamera);
37956 this._updateRotationBasic();
37957 if (this._basicRotation[0] !== 0 || this._basicRotation[1] !== 0) {
37958 this._applyRotationBasic();
37960 this._updateZoom(animationSpeed);
37961 this._updateLookat(animationSpeed);
37962 this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha);
37964 TraversingState.prototype._getAlpha = function () {
37965 return this._motionless ? Math.ceil(this._alpha) : this._alpha;
37967 TraversingState.prototype._setCurrentCamera = function () {
37968 _super.prototype._setCurrentCamera.call(this);
37969 this._adjustCameras();
37971 TraversingState.prototype._adjustCameras = function () {
37972 if (this._previousNode == null) {
37975 var lookat = this._camera.lookat.clone().sub(this._camera.position);
37976 this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position));
37977 if (this._currentNode.fullPano) {
37978 this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position));
37981 TraversingState.prototype._resetTransition = function () {
37983 this._baseAlpha = 0;
37984 this._motionless = this._motionlessTransition();
37986 TraversingState.prototype._applyRotation = function (camera) {
37987 if (camera == null) {
37990 var q = new THREE.Quaternion().setFromUnitVectors(camera.up, new THREE.Vector3(0, 0, 1));
37991 var qInverse = q.clone().inverse();
37992 var offset = new THREE.Vector3();
37993 offset.copy(camera.lookat).sub(camera.position);
37994 offset.applyQuaternion(q);
37995 var length = offset.length();
37996 var phi = Math.atan2(offset.y, offset.x);
37997 phi += this._rotationDelta.phi;
37998 var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z);
37999 theta += this._rotationDelta.theta;
38000 theta = Math.max(0.1, Math.min(Math.PI - 0.1, theta));
38001 offset.x = Math.sin(theta) * Math.cos(phi);
38002 offset.y = Math.sin(theta) * Math.sin(phi);
38003 offset.z = Math.cos(theta);
38004 offset.applyQuaternion(qInverse);
38005 camera.lookat.copy(camera.position).add(offset.multiplyScalar(length));
38007 TraversingState.prototype._applyRotationBasic = function () {
38008 var currentNode = this._currentNode;
38009 var previousNode = this._previousNode != null ?
38010 this.previousNode :
38012 var currentCamera = this._currentCamera;
38013 var previousCamera = this._previousCamera;
38014 var currentTransform = this.currentTransform;
38015 var previousTransform = this.previousTransform != null ?
38016 this.previousTransform :
38017 this.currentTransform;
38018 var currentBasic = currentTransform.projectBasic(currentCamera.lookat.toArray());
38019 var previousBasic = previousTransform.projectBasic(previousCamera.lookat.toArray());
38020 var currentGPano = currentTransform.gpano;
38021 var previousGPano = previousTransform.gpano;
38022 if (currentNode.fullPano) {
38023 currentBasic[0] = this._spatial.wrap(currentBasic[0] + this._basicRotation[0], 0, 1);
38024 currentBasic[1] = this._spatial.clamp(currentBasic[1] + this._basicRotation[1], 0.05, 0.95);
38026 else if (currentGPano != null &&
38027 currentTransform.gpano.CroppedAreaImageWidthPixels === currentTransform.gpano.FullPanoWidthPixels) {
38028 currentBasic[0] = this._spatial.wrap(currentBasic[0] + this._basicRotation[0], 0, 1);
38029 currentBasic[1] = this._spatial.clamp(currentBasic[1] + this._basicRotation[1], 0, 1);
38032 currentBasic[0] = this._spatial.clamp(currentBasic[0] + this._basicRotation[0], 0, 1);
38033 currentBasic[1] = this._spatial.clamp(currentBasic[1] + this._basicRotation[1], 0, 1);
38035 if (previousNode.fullPano) {
38036 previousBasic[0] = this._spatial.wrap(previousBasic[0] + this._basicRotation[0], 0, 1);
38037 previousBasic[1] = this._spatial.clamp(previousBasic[1] + this._basicRotation[1], 0.05, 0.95);
38039 else if (previousGPano != null &&
38040 previousTransform.gpano.CroppedAreaImageWidthPixels === previousTransform.gpano.FullPanoWidthPixels) {
38041 previousBasic[0] = this._spatial.wrap(previousBasic[0] + this._basicRotation[0], 0, 1);
38042 previousBasic[1] = this._spatial.clamp(previousBasic[1] + this._basicRotation[1], 0, 1);
38045 previousBasic[0] = this._spatial.clamp(previousBasic[0] + this._basicRotation[0], 0, 1);
38046 previousBasic[1] = this._spatial.clamp(currentBasic[1] + this._basicRotation[1], 0, 1);
38048 var currentLookat = currentTransform.unprojectBasic(currentBasic, this._lookatDepth);
38049 currentCamera.lookat.fromArray(currentLookat);
38050 var previousLookat = previousTransform.unprojectBasic(previousBasic, this._lookatDepth);
38051 previousCamera.lookat.fromArray(previousLookat);
38053 TraversingState.prototype._updateZoom = function (animationSpeed) {
38054 var diff = this._desiredZoom - this._zoom;
38055 var sign = diff > 0 ? 1 : diff < 0 ? -1 : 0;
38059 else if (Math.abs(diff) < 2e-3) {
38060 this._zoom = this._desiredZoom;
38061 if (this._desiredLookat != null) {
38062 this._desiredLookat = null;
38066 this._zoom += sign * Math.max(Math.abs(5 * animationSpeed * diff), 2e-3);
38069 TraversingState.prototype._updateLookat = function (animationSpeed) {
38070 if (this._desiredLookat === null) {
38073 var diff = this._desiredLookat.distanceToSquared(this._currentCamera.lookat);
38074 if (Math.abs(diff) < 1e-6) {
38075 this._currentCamera.lookat.copy(this._desiredLookat);
38076 this._desiredLookat = null;
38079 this._currentCamera.lookat.lerp(this._desiredLookat, 5 * animationSpeed);
38082 TraversingState.prototype._updateRotation = function () {
38083 if (this._requestedRotationDelta != null) {
38084 var length_1 = this._rotationDelta.lengthSquared();
38085 var requestedLength = this._requestedRotationDelta.lengthSquared();
38086 if (requestedLength > length_1) {
38087 this._rotationDelta.lerp(this._requestedRotationDelta, this._rotationIncreaseAlpha);
38090 this._rotationDelta.lerp(this._requestedRotationDelta, this._rotationDecreaseAlpha);
38092 this._requestedRotationDelta = null;
38095 if (this._rotationDelta.isZero) {
38098 this._rotationDelta.multiply(this._rotationAcceleration);
38099 this._rotationDelta.threshold(this._rotationThreshold);
38101 TraversingState.prototype._updateRotationBasic = function () {
38102 if (this._requestedBasicRotation != null) {
38103 var x = this._basicRotation[0];
38104 var y = this._basicRotation[1];
38105 var reqX = this._requestedBasicRotation[0];
38106 var reqY = this._requestedBasicRotation[1];
38107 if (Math.abs(reqX) > Math.abs(x)) {
38108 this._basicRotation[0] = (1 - this._rotationIncreaseAlpha) * x + this._rotationIncreaseAlpha * reqX;
38111 this._basicRotation[0] = (1 - this._rotationDecreaseAlpha) * x + this._rotationDecreaseAlpha * reqX;
38113 if (Math.abs(reqY) > Math.abs(y)) {
38114 this._basicRotation[1] = (1 - this._rotationIncreaseAlpha) * y + this._rotationIncreaseAlpha * reqY;
38117 this._basicRotation[1] = (1 - this._rotationDecreaseAlpha) * y + this._rotationDecreaseAlpha * reqY;
38119 this._requestedBasicRotation = null;
38122 if (this._requestedBasicRotationUnbounded != null) {
38123 var reqX = this._requestedBasicRotationUnbounded[0];
38124 var reqY = this._requestedBasicRotationUnbounded[1];
38125 if (Math.abs(reqX) > 0) {
38126 this._basicRotation[0] = (1 - this._unboundedRotationAlpha) * this._basicRotation[0] + this._unboundedRotationAlpha * reqX;
38128 if (Math.abs(reqY) > 0) {
38129 this._basicRotation[1] = (1 - this._unboundedRotationAlpha) * this._basicRotation[1] + this._unboundedRotationAlpha * reqY;
38131 if (this._desiredLookat != null) {
38132 var desiredBasicLookat = this.currentTransform.projectBasic(this._desiredLookat.toArray());
38133 desiredBasicLookat[0] += reqX;
38134 desiredBasicLookat[1] += reqY;
38135 this._desiredLookat = new THREE.Vector3()
38136 .fromArray(this.currentTransform.unprojectBasic(desiredBasicLookat, this._lookatDepth));
38138 this._requestedBasicRotationUnbounded = null;
38140 if (this._basicRotation[0] === 0 && this._basicRotation[1] === 0) {
38143 this._basicRotation[0] = this._rotationAcceleration * this._basicRotation[0];
38144 this._basicRotation[1] = this._rotationAcceleration * this._basicRotation[1];
38145 if (Math.abs(this._basicRotation[0]) < this._rotationThreshold / Math.pow(2, this._zoom) &&
38146 Math.abs(this._basicRotation[1]) < this._rotationThreshold / Math.pow(2, this._zoom)) {
38147 this._basicRotation = [0, 0];
38150 TraversingState.prototype._clearRotation = function () {
38151 if (this._currentNode.fullPano) {
38154 if (this._requestedRotationDelta != null) {
38155 this._requestedRotationDelta = null;
38157 if (!this._rotationDelta.isZero) {
38158 this._rotationDelta.reset();
38160 if (this._requestedBasicRotation != null) {
38161 this._requestedBasicRotation = null;
38163 if (this._basicRotation[0] > 0 || this._basicRotation[1] > 0) {
38164 this._basicRotation = [0, 0];
38167 TraversingState.prototype._setDesiredCenter = function () {
38168 if (this._desiredCenter == null) {
38171 var lookatDirection = new THREE.Vector3()
38172 .fromArray(this.currentTransform.unprojectBasic(this._desiredCenter, this._lookatDepth))
38173 .sub(this._currentCamera.position);
38174 this._currentCamera.lookat.copy(this._currentCamera.position.clone().add(lookatDirection));
38175 this._previousCamera.lookat.copy(this._previousCamera.position.clone().add(lookatDirection));
38176 this._desiredCenter = null;
38178 TraversingState.prototype._setDesiredZoom = function () {
38179 this._desiredZoom =
38180 this._currentNode.fullPano || this._previousNode == null ?
38183 return TraversingState;
38184 }(State_1.StateBase));
38185 exports.TraversingState = TraversingState;
38187 },{"../../State":233,"@mapbox/unitbezier":2,"three":176}],342:[function(require,module,exports){
38189 var __extends = (this && this.__extends) || (function () {
38190 var extendStatics = Object.setPrototypeOf ||
38191 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
38192 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
38193 return function (d, b) {
38194 extendStatics(d, b);
38195 function __() { this.constructor = d; }
38196 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
38199 Object.defineProperty(exports, "__esModule", { value: true });
38200 var State_1 = require("../../State");
38201 var WaitingState = (function (_super) {
38202 __extends(WaitingState, _super);
38203 function WaitingState(state) {
38204 var _this = _super.call(this, state) || this;
38206 _this._adjustCameras();
38207 _this._motionless = _this._motionlessTransition();
38210 WaitingState.prototype.traverse = function () {
38211 return new State_1.TraversingState(this);
38213 WaitingState.prototype.wait = function () {
38214 throw new Error("Not implemented");
38216 WaitingState.prototype.prepend = function (nodes) {
38217 _super.prototype.prepend.call(this, nodes);
38218 this._motionless = this._motionlessTransition();
38220 WaitingState.prototype.set = function (nodes) {
38221 _super.prototype.set.call(this, nodes);
38222 this._motionless = this._motionlessTransition();
38224 WaitingState.prototype.rotate = function (delta) { return; };
38225 WaitingState.prototype.rotateBasic = function (basicRotation) { return; };
38226 WaitingState.prototype.rotateBasicUnbounded = function (basicRotation) { return; };
38227 WaitingState.prototype.rotateToBasic = function (basic) { return; };
38228 WaitingState.prototype.zoomIn = function (delta, reference) { return; };
38229 WaitingState.prototype.move = function (delta) {
38230 this._alpha = Math.max(0, Math.min(1, this._alpha + delta));
38232 WaitingState.prototype.moveTo = function (position) {
38233 this._alpha = Math.max(0, Math.min(1, position));
38235 WaitingState.prototype.update = function (fps) {
38236 this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha);
38238 WaitingState.prototype.setCenter = function (center) { return; };
38239 WaitingState.prototype.setZoom = function (zoom) { return; };
38240 WaitingState.prototype._getAlpha = function () {
38241 return this._motionless ? Math.round(this._alpha) : this._alpha;
38243 WaitingState.prototype._setCurrentCamera = function () {
38244 _super.prototype._setCurrentCamera.call(this);
38245 this._adjustCameras();
38247 WaitingState.prototype._adjustCameras = function () {
38248 if (this._previousNode == null) {
38251 if (this._currentNode.fullPano) {
38252 var lookat = this._camera.lookat.clone().sub(this._camera.position);
38253 this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position));
38255 if (this._previousNode.fullPano) {
38256 var lookat = this._currentCamera.lookat.clone().sub(this._currentCamera.position);
38257 this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position));
38260 return WaitingState;
38261 }(State_1.StateBase));
38262 exports.WaitingState = WaitingState;
38264 },{"../../State":233}],343:[function(require,module,exports){
38266 Object.defineProperty(exports, "__esModule", { value: true });
38267 var Observable_1 = require("rxjs/Observable");
38269 * @class ImageTileLoader
38271 * @classdesc Represents a loader of image tiles.
38273 var ImageTileLoader = (function () {
38275 * Create a new node image tile loader instance.
38277 * @param {string} scheme - The URI scheme.
38278 * @param {string} host - The URI host.
38279 * @param {string} [origin] - The origin query param.
38281 function ImageTileLoader(scheme, host, origin) {
38282 this._scheme = scheme;
38284 this._origin = origin != null ? "?origin=" + origin : "";
38287 * Retrieve an image tile.
38289 * @description Retrieve an image tile by specifying the area
38290 * as well as the scaled size.
38292 * @param {string} identifier - The identifier of the image.
38293 * @param {number} x - The top left x pixel coordinate for the tile
38294 * in the original image.
38295 * @param {number} y - The top left y pixel coordinate for the tile
38296 * in the original image.
38297 * @param {number} w - The pixel width of the tile in the original image.
38298 * @param {number} h - The pixel height of the tile in the original image.
38299 * @param {number} scaledW - The scaled width of the returned tile.
38300 * @param {number} scaledH - The scaled height of the returned tile.
38302 ImageTileLoader.prototype.getTile = function (identifier, x, y, w, h, scaledW, scaledH) {
38303 var characteristics = "/" + identifier + "/" + x + "," + y + "," + w + "," + h + "/" + scaledW + "," + scaledH + "/0/default.jpg";
38304 var url = this._scheme +
38309 var xmlHTTP = null;
38310 return [Observable_1.Observable.create(function (subscriber) {
38311 xmlHTTP = new XMLHttpRequest();
38312 xmlHTTP.open("GET", url, true);
38313 xmlHTTP.responseType = "arraybuffer";
38314 xmlHTTP.timeout = 15000;
38315 xmlHTTP.onload = function (event) {
38316 if (xmlHTTP.status !== 200) {
38317 subscriber.error(new Error("Failed to fetch tile (" + identifier + ": " + x + "," + y + "," + w + "," + h + "). " +
38318 ("Status: " + xmlHTTP.status + ", " + xmlHTTP.statusText)));
38321 var image = new Image();
38322 image.crossOrigin = "Anonymous";
38323 image.onload = function (e) {
38324 subscriber.next(image);
38325 subscriber.complete();
38327 image.onerror = function (error) {
38328 subscriber.error(new Error("Failed to load tile image (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
38330 var blob = new Blob([xmlHTTP.response]);
38331 image.src = window.URL.createObjectURL(blob);
38333 xmlHTTP.onerror = function (error) {
38334 subscriber.error(new Error("Failed to fetch tile (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
38336 xmlHTTP.ontimeout = function (error) {
38337 subscriber.error(new Error("Tile request timed out (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
38339 xmlHTTP.onabort = function (event) {
38340 subscriber.error(new Error("Tile request was aborted (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
38342 xmlHTTP.send(null);
38345 if (xmlHTTP != null) {
38351 return ImageTileLoader;
38353 exports.ImageTileLoader = ImageTileLoader;
38354 exports.default = ImageTileLoader;
38356 },{"rxjs/Observable":29}],344:[function(require,module,exports){
38358 Object.defineProperty(exports, "__esModule", { value: true });
38360 * @class ImageTileStore
38362 * @classdesc Represents a store for image tiles.
38364 var ImageTileStore = (function () {
38366 * Create a new node image tile store instance.
38368 function ImageTileStore() {
38372 * Add an image tile to the store.
38374 * @param {HTMLImageElement} image - The image tile.
38375 * @param {string} key - The identifier for the tile.
38376 * @param {number} level - The level of the tile.
38378 ImageTileStore.prototype.addImage = function (image, key, level) {
38379 if (!(level in this._images)) {
38380 this._images[level] = {};
38382 this._images[level][key] = image;
38385 * Dispose the store.
38387 * @description Disposes all cached assets.
38389 ImageTileStore.prototype.dispose = function () {
38390 for (var _i = 0, _a = Object.keys(this._images); _i < _a.length; _i++) {
38391 var level = _a[_i];
38392 var levelImages = this._images[level];
38393 for (var _b = 0, _c = Object.keys(levelImages); _b < _c.length; _b++) {
38395 window.URL.revokeObjectURL(levelImages[key].src);
38396 delete levelImages[key];
38398 delete this._images[level];
38402 * Get an image tile from the store.
38404 * @param {string} key - The identifier for the tile.
38405 * @param {number} level - The level of the tile.
38407 ImageTileStore.prototype.getImage = function (key, level) {
38408 return this._images[level][key];
38411 * Check if an image tile exist in the store.
38413 * @param {string} key - The identifier for the tile.
38414 * @param {number} level - The level of the tile.
38416 ImageTileStore.prototype.hasImage = function (key, level) {
38417 return level in this._images && key in this._images[level];
38419 return ImageTileStore;
38421 exports.ImageTileStore = ImageTileStore;
38422 exports.default = ImageTileStore;
38424 },{}],345:[function(require,module,exports){
38426 /// <reference path="../../typings/index.d.ts" />
38427 Object.defineProperty(exports, "__esModule", { value: true });
38428 var Geo_1 = require("../Geo");
38430 * @class RegionOfInterestCalculator
38432 * @classdesc Represents a calculator for regions of interest.
38434 var RegionOfInterestCalculator = (function () {
38435 function RegionOfInterestCalculator() {
38436 this._viewportCoords = new Geo_1.ViewportCoords();
38439 * Compute a region of interest based on the current render camera
38440 * and the viewport size.
38442 * @param {RenderCamera} renderCamera - Render camera used for unprojections.
38443 * @param {ISize} size - Viewport size in pixels.
38444 * @param {Transform} transform - Transform used for projections.
38446 * @returns {IRegionOfInterest} A region of interest.
38448 RegionOfInterestCalculator.prototype.computeRegionOfInterest = function (renderCamera, size, transform) {
38449 var viewportBoundaryPoints = this._viewportBoundaryPoints(4);
38450 var bbox = this._viewportPointsBoundingBox(viewportBoundaryPoints, renderCamera, transform);
38451 this._clipBoundingBox(bbox);
38452 var viewportPixelWidth = 2 / size.width;
38453 var viewportPixelHeight = 2 / size.height;
38454 var centralViewportPixel = [
38455 [-0.5 * viewportPixelWidth, 0.5 * viewportPixelHeight],
38456 [0.5 * viewportPixelWidth, 0.5 * viewportPixelHeight],
38457 [0.5 * viewportPixelWidth, -0.5 * viewportPixelHeight],
38458 [-0.5 * viewportPixelWidth, -0.5 * viewportPixelHeight],
38460 var cpbox = this._viewportPointsBoundingBox(centralViewportPixel, renderCamera, transform);
38463 pixelHeight: cpbox.maxY - cpbox.minY,
38464 pixelWidth: cpbox.maxX - cpbox.minX + (cpbox.minX < cpbox.maxX ? 0 : 1),
38467 RegionOfInterestCalculator.prototype._viewportBoundaryPoints = function (pointsPerSide) {
38469 var os = [[-1, 1], [1, 1], [1, -1], [-1, -1]];
38470 var ds = [[2, 0], [0, -2], [-2, 0], [0, 2]];
38471 for (var side = 0; side < 4; ++side) {
38474 for (var i = 0; i < pointsPerSide; ++i) {
38475 points.push([o[0] + d[0] * i / pointsPerSide,
38476 o[1] + d[1] * i / pointsPerSide]);
38481 RegionOfInterestCalculator.prototype._viewportPointsBoundingBox = function (viewportPoints, renderCamera, transform) {
38483 var basicPoints = viewportPoints
38484 .map(function (point) {
38485 return _this._viewportCoords
38486 .viewportToBasic(point[0], point[1], transform, renderCamera.perspective);
38488 if (transform.gpano != null) {
38489 return this._boundingBoxPano(basicPoints);
38492 return this._boundingBox(basicPoints);
38495 RegionOfInterestCalculator.prototype._boundingBox = function (points) {
38497 maxX: Number.NEGATIVE_INFINITY,
38498 maxY: Number.NEGATIVE_INFINITY,
38499 minX: Number.POSITIVE_INFINITY,
38500 minY: Number.POSITIVE_INFINITY,
38502 for (var i = 0; i < points.length; ++i) {
38503 bbox.minX = Math.min(bbox.minX, points[i][0]);
38504 bbox.maxX = Math.max(bbox.maxX, points[i][0]);
38505 bbox.minY = Math.min(bbox.minY, points[i][1]);
38506 bbox.maxY = Math.max(bbox.maxY, points[i][1]);
38510 RegionOfInterestCalculator.prototype._boundingBoxPano = function (points) {
38514 for (var i = 0; i < points.length; ++i) {
38515 xs.push(points[i][0]);
38516 ys.push(points[i][1]);
38518 xs.sort(function (a, b) { return _this._sign(a - b); });
38519 ys.sort(function (a, b) { return _this._sign(a - b); });
38520 var intervalX = this._intervalPano(xs);
38522 maxX: intervalX[1],
38523 maxY: ys[ys.length - 1],
38524 minX: intervalX[0],
38529 * Find the max interval between consecutive numbers.
38530 * Assumes numbers are between 0 and 1, sorted and that
38531 * x is equivalent to x + 1.
38533 RegionOfInterestCalculator.prototype._intervalPano = function (xs) {
38536 for (var i = 0; i < xs.length - 1; ++i) {
38537 var dx = xs[i + 1] - xs[i];
38543 var loopdx = xs[0] + 1 - xs[xs.length - 1];
38544 if (loopdx > maxdx) {
38545 return [xs[0], xs[xs.length - 1]];
38548 return [xs[maxi + 1], xs[maxi]];
38551 RegionOfInterestCalculator.prototype._clipBoundingBox = function (bbox) {
38552 bbox.minX = Math.max(0, Math.min(1, bbox.minX));
38553 bbox.maxX = Math.max(0, Math.min(1, bbox.maxX));
38554 bbox.minY = Math.max(0, Math.min(1, bbox.minY));
38555 bbox.maxY = Math.max(0, Math.min(1, bbox.maxY));
38557 RegionOfInterestCalculator.prototype._sign = function (n) {
38558 return n > 0 ? 1 : n < 0 ? -1 : 0;
38560 return RegionOfInterestCalculator;
38562 exports.RegionOfInterestCalculator = RegionOfInterestCalculator;
38563 exports.default = RegionOfInterestCalculator;
38565 },{"../Geo":229}],346:[function(require,module,exports){
38567 /// <reference path="../../typings/index.d.ts" />
38568 Object.defineProperty(exports, "__esModule", { value: true });
38569 var THREE = require("three");
38570 var Subject_1 = require("rxjs/Subject");
38572 * @class TextureProvider
38574 * @classdesc Represents a provider of textures.
38576 var TextureProvider = (function () {
38578 * Create a new node texture provider instance.
38580 * @param {string} key - The identifier of the image for which to request tiles.
38581 * @param {number} width - The full width of the original image.
38582 * @param {number} height - The full height of the original image.
38583 * @param {number} tileSize - The size used when requesting tiles.
38584 * @param {HTMLImageElement} background - Image to use as background.
38585 * @param {ImageTileLoader} imageTileLoader - Loader for retrieving tiles.
38586 * @param {ImageTileStore} imageTileStore - Store for saving tiles.
38587 * @param {THREE.WebGLRenderer} renderer - Renderer used for rendering tiles to texture.
38589 function TextureProvider(key, width, height, tileSize, background, imageTileLoader, imageTileStore, renderer) {
38590 this._disposed = false;
38592 if (width <= 0 || height <= 0) {
38593 console.warn("Original image size (" + width + ", " + height + ") is invalid (" + key + "). Tiles will not be loaded.");
38595 this._width = width;
38596 this._height = height;
38597 this._maxLevel = Math.ceil(Math.log(Math.max(height, width)) / Math.log(2));
38598 this._currentLevel = -1;
38599 this._tileSize = tileSize;
38600 this._updated$ = new Subject_1.Subject();
38601 this._createdSubject$ = new Subject_1.Subject();
38602 this._created$ = this._createdSubject$
38605 this._createdSubscription = this._created$.subscribe(function () { });
38606 this._hasSubject$ = new Subject_1.Subject();
38607 this._has$ = this._hasSubject$
38611 this._hasSubscription = this._has$.subscribe(function () { });
38612 this._abortFunctions = [];
38613 this._tileSubscriptions = {};
38614 this._renderedCurrentLevelTiles = {};
38615 this._renderedTiles = {};
38616 this._background = background;
38617 this._camera = null;
38618 this._imageTileLoader = imageTileLoader;
38619 this._imageTileStore = imageTileStore;
38620 this._renderer = renderer;
38621 this._renderTarget = null;
38624 Object.defineProperty(TextureProvider.prototype, "disposed", {
38628 * @returns {boolean} Value indicating whether provider has
38632 return this._disposed;
38637 Object.defineProperty(TextureProvider.prototype, "hasTexture$", {
38641 * @returns {Observable<boolean>} Observable emitting
38642 * values indicating when the existance of a texture
38651 Object.defineProperty(TextureProvider.prototype, "key", {
38655 * @returns {boolean} The identifier of the image for
38656 * which to render textures.
38664 Object.defineProperty(TextureProvider.prototype, "textureUpdated$", {
38666 * Get textureUpdated$.
38668 * @returns {Observable<boolean>} Observable emitting
38669 * values when an existing texture has been updated.
38672 return this._updated$;
38677 Object.defineProperty(TextureProvider.prototype, "textureCreated$", {
38679 * Get textureCreated$.
38681 * @returns {Observable<boolean>} Observable emitting
38682 * values when a new texture has been created.
38685 return this._created$;
38691 * Abort all outstanding image tile requests.
38693 TextureProvider.prototype.abort = function () {
38694 for (var key in this._tileSubscriptions) {
38695 if (!this._tileSubscriptions.hasOwnProperty(key)) {
38698 this._tileSubscriptions[key].unsubscribe();
38700 this._tileSubscriptions = {};
38701 for (var _i = 0, _a = this._abortFunctions; _i < _a.length; _i++) {
38702 var abort = _a[_i];
38705 this._abortFunctions = [];
38708 * Dispose the provider.
38710 * @description Disposes all cached assets and
38711 * aborts all outstanding image tile requests.
38713 TextureProvider.prototype.dispose = function () {
38714 if (this._disposed) {
38715 console.warn("Texture already disposed (" + this._key + ")");
38719 if (this._renderTarget != null) {
38720 this._renderTarget.dispose();
38721 this._renderTarget = null;
38723 this._imageTileStore.dispose();
38724 this._imageTileStore = null;
38725 this._background = null;
38726 this._camera = null;
38727 this._imageTileLoader = null;
38728 this._renderer = null;
38730 this._createdSubscription.unsubscribe();
38731 this._hasSubscription.unsubscribe();
38732 this._disposed = true;
38735 * Set the region of interest.
38737 * @description When the region of interest is set the
38738 * the tile level is determined and tiles for the region
38739 * are fetched from the store or the loader and renderedLevel
38742 * @param {IRegionOfInterest} roi - Spatial edges to cache.
38744 TextureProvider.prototype.setRegionOfInterest = function (roi) {
38745 if (this._width <= 0 || this._height <= 0) {
38749 var width = 1 / this._roi.pixelWidth;
38750 var height = 1 / this._roi.pixelHeight;
38751 var size = Math.max(height, width);
38752 var currentLevel = Math.max(0, Math.min(this._maxLevel, Math.round(Math.log(size) / Math.log(2) + 0.25)));
38753 if (currentLevel !== this._currentLevel) {
38755 this._currentLevel = currentLevel;
38756 if (!(this._currentLevel in this._renderedTiles)) {
38757 this._renderedTiles[this._currentLevel] = [];
38759 this._renderedCurrentLevelTiles = {};
38760 for (var _i = 0, _a = this._renderedTiles[this._currentLevel]; _i < _a.length; _i++) {
38762 this._renderedCurrentLevelTiles[this._tileKey(tile)] = true;
38765 var topLeft = this._getTileCoords([this._roi.bbox.minX, this._roi.bbox.minY]);
38766 var bottomRight = this._getTileCoords([this._roi.bbox.maxX, this._roi.bbox.maxY]);
38767 var tiles = this._getTiles(topLeft, bottomRight);
38768 if (this._camera == null) {
38769 this._camera = new THREE.OrthographicCamera(-this._width / 2, this._width / 2, this._height / 2, -this._height / 2, -1, 1);
38770 this._camera.position.z = 1;
38771 var gl = this._renderer.getContext();
38772 var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
38773 var backgroundSize = Math.max(this._width, this._height);
38774 var scale = maxTextureSize > backgroundSize ? 1 : maxTextureSize / backgroundSize;
38775 var targetWidth = Math.floor(scale * this._width);
38776 var targetHeight = Math.floor(scale * this._height);
38777 this._renderTarget = new THREE.WebGLRenderTarget(targetWidth, targetHeight, {
38778 depthBuffer: false,
38779 format: THREE.RGBFormat,
38780 magFilter: THREE.LinearFilter,
38781 minFilter: THREE.LinearFilter,
38782 stencilBuffer: false,
38784 this._renderToTarget(0, 0, this._width, this._height, this._background);
38785 this._createdSubject$.next(this._renderTarget.texture);
38786 this._hasSubject$.next(true);
38788 this._fetchTiles(tiles);
38791 * Update the image used as background for the texture.
38793 * @param {HTMLImageElement} background - The background image.
38795 TextureProvider.prototype.updateBackground = function (background) {
38796 this._background = background;
38799 * Retrieve an image tile.
38801 * @description Retrieve an image tile and render it to the
38802 * texture. Add the tile to the store and emit to the updated
38805 * @param {Array<number>} tile - The tile coordinates.
38806 * @param {number} level - The tile level.
38807 * @param {number} x - The top left x pixel coordinate of the tile.
38808 * @param {number} y - The top left y pixel coordinate of the tile.
38809 * @param {number} w - The pixel width of the tile.
38810 * @param {number} h - The pixel height of the tile.
38811 * @param {number} scaledW - The scaled width of the returned tile.
38812 * @param {number} scaledH - The scaled height of the returned tile.
38814 TextureProvider.prototype._fetchTile = function (tile, level, x, y, w, h, scaledX, scaledY) {
38816 var getTile = this._imageTileLoader.getTile(this._key, x, y, w, h, scaledX, scaledY);
38817 var tile$ = getTile[0];
38818 var abort = getTile[1];
38819 this._abortFunctions.push(abort);
38820 var tileKey = this._tileKey(tile);
38821 var subscription = tile$
38822 .subscribe(function (image) {
38823 _this._renderToTarget(x, y, w, h, image);
38824 _this._removeFromDictionary(tileKey, _this._tileSubscriptions);
38825 _this._removeFromArray(abort, _this._abortFunctions);
38826 _this._setTileRendered(tile, _this._currentLevel);
38827 _this._imageTileStore.addImage(image, tileKey, level);
38828 _this._updated$.next(true);
38829 }, function (error) {
38830 _this._removeFromDictionary(tileKey, _this._tileSubscriptions);
38831 _this._removeFromArray(abort, _this._abortFunctions);
38832 console.error(error);
38834 if (!subscription.closed) {
38835 this._tileSubscriptions[tileKey] = subscription;
38839 * Retrieve image tiles.
38841 * @description Retrieve a image tiles and render them to the
38842 * texture. Retrieve from store if it exists, otherwise Retrieve
38845 * @param {Array<Array<number>>} tiles - Array of tile coordinates to
38848 TextureProvider.prototype._fetchTiles = function (tiles) {
38849 var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
38850 for (var _i = 0, tiles_1 = tiles; _i < tiles_1.length; _i++) {
38851 var tile = tiles_1[_i];
38852 var tileKey = this._tileKey(tile);
38853 if (tileKey in this._renderedCurrentLevelTiles ||
38854 tileKey in this._tileSubscriptions) {
38857 var tileX = tileSize * tile[0];
38858 var tileY = tileSize * tile[1];
38859 var tileWidth = tileX + tileSize > this._width ? this._width - tileX : tileSize;
38860 var tileHeight = tileY + tileSize > this._height ? this._height - tileY : tileSize;
38861 if (this._imageTileStore.hasImage(tileKey, this._currentLevel)) {
38862 this._renderToTarget(tileX, tileY, tileWidth, tileHeight, this._imageTileStore.getImage(tileKey, this._currentLevel));
38863 this._setTileRendered(tile, this._currentLevel);
38864 this._updated$.next(true);
38867 var scaledX = Math.floor(tileWidth / tileSize * this._tileSize);
38868 var scaledY = Math.floor(tileHeight / tileSize * this._tileSize);
38869 this._fetchTile(tile, this._currentLevel, tileX, tileY, tileWidth, tileHeight, scaledX, scaledY);
38873 * Get tile coordinates for a point using the current level.
38875 * @param {Array<number>} point - Point in basic coordinates.
38877 * @returns {Array<number>} x and y tile coodinates.
38879 TextureProvider.prototype._getTileCoords = function (point) {
38880 var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
38881 var maxX = Math.ceil(this._width / tileSize) - 1;
38882 var maxY = Math.ceil(this._height / tileSize) - 1;
38884 Math.min(Math.floor(this._width * point[0] / tileSize), maxX),
38885 Math.min(Math.floor(this._height * point[1] / tileSize), maxY),
38889 * Get tile coordinates for all tiles contained in a bounding
38892 * @param {Array<number>} topLeft - Top left tile coordinate of bounding box.
38893 * @param {Array<number>} bottomRight - Bottom right tile coordinate of bounding box.
38895 * @returns {Array<Array<number>>} Array of x, y tile coodinates.
38897 TextureProvider.prototype._getTiles = function (topLeft, bottomRight) {
38899 if (topLeft[0] > bottomRight[0]) {
38900 var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
38901 var maxX = Math.ceil(this._width / tileSize) - 1;
38902 for (var x = topLeft[0]; x <= maxX; x++) {
38905 for (var x = 0; x <= bottomRight[0]; x++) {
38910 for (var x = topLeft[0]; x <= bottomRight[0]; x++) {
38915 for (var _i = 0, xs_1 = xs; _i < xs_1.length; _i++) {
38917 for (var y = topLeft[1]; y <= bottomRight[1]; y++) {
38918 tiles.push([x, y]);
38924 * Remove an item from an array if it exists in array.
38926 * @param {T} item - Item to remove.
38927 * @param {Array<T>} array - Array from which item should be removed.
38929 TextureProvider.prototype._removeFromArray = function (item, array) {
38930 var index = array.indexOf(item);
38931 if (index !== -1) {
38932 array.splice(index, 1);
38936 * Remove an item from a dictionary.
38938 * @param {string} key - Key of the item to remove.
38939 * @param {Object} dict - Dictionary from which item should be removed.
38941 TextureProvider.prototype._removeFromDictionary = function (key, dict) {
38947 * Render an image tile to the target texture.
38949 * @param {number} x - The top left x pixel coordinate of the tile.
38950 * @param {number} y - The top left y pixel coordinate of the tile.
38951 * @param {number} w - The pixel width of the tile.
38952 * @param {number} h - The pixel height of the tile.
38953 * @param {HTMLImageElement} background - The image tile to render.
38955 TextureProvider.prototype._renderToTarget = function (x, y, w, h, image) {
38956 var texture = new THREE.Texture(image);
38957 texture.minFilter = THREE.LinearFilter;
38958 texture.needsUpdate = true;
38959 var geometry = new THREE.PlaneGeometry(w, h);
38960 var material = new THREE.MeshBasicMaterial({ map: texture, side: THREE.FrontSide });
38961 var mesh = new THREE.Mesh(geometry, material);
38962 mesh.position.x = -this._width / 2 + x + w / 2;
38963 mesh.position.y = this._height / 2 - y - h / 2;
38964 var scene = new THREE.Scene();
38966 this._renderer.render(scene, this._camera, this._renderTarget);
38967 this._renderer.setRenderTarget(undefined);
38968 scene.remove(mesh);
38969 geometry.dispose();
38970 material.dispose();
38974 * Mark a tile as rendered.
38976 * @description Clears tiles marked as rendered in other
38977 * levels of the tile pyramid if they were rendered on
38978 * top of or below the tile.
38980 * @param {Arrary<number>} tile - The tile coordinates.
38981 * @param {number} level - Tile level of the tile coordinates.
38983 TextureProvider.prototype._setTileRendered = function (tile, level) {
38984 var otherLevels = Object.keys(this._renderedTiles)
38985 .map(function (key) {
38986 return parseInt(key, 10);
38988 .filter(function (renderedLevel) {
38989 return renderedLevel !== level;
38991 for (var _i = 0, otherLevels_1 = otherLevels; _i < otherLevels_1.length; _i++) {
38992 var otherLevel = otherLevels_1[_i];
38993 var scale = Math.pow(2, otherLevel - level);
38994 if (otherLevel < level) {
38995 var x = Math.floor(scale * tile[0]);
38996 var y = Math.floor(scale * tile[1]);
38997 for (var _a = 0, _b = this._renderedTiles[otherLevel].slice(); _a < _b.length; _a++) {
38998 var otherTile = _b[_a];
38999 if (otherTile[0] === x && otherTile[1] === y) {
39000 var index = this._renderedTiles[otherLevel].indexOf(otherTile);
39001 this._renderedTiles[otherLevel].splice(index, 1);
39006 var startX = scale * tile[0];
39007 var endX = startX + scale - 1;
39008 var startY = scale * tile[1];
39009 var endY = startY + scale - 1;
39010 for (var _c = 0, _d = this._renderedTiles[otherLevel].slice(); _c < _d.length; _c++) {
39011 var otherTile = _d[_c];
39012 if (otherTile[0] >= startX && otherTile[0] <= endX &&
39013 otherTile[1] >= startY && otherTile[1] <= endY) {
39014 var index = this._renderedTiles[otherLevel].indexOf(otherTile);
39015 this._renderedTiles[otherLevel].splice(index, 1);
39019 if (this._renderedTiles[otherLevel].length === 0) {
39020 delete this._renderedTiles[otherLevel];
39023 this._renderedTiles[level].push(tile);
39024 this._renderedCurrentLevelTiles[this._tileKey(tile)] = true;
39027 * Create a tile key from a tile coordinates.
39029 * @description Tile keys are used as a hash for
39030 * storing the tile in a dictionary.
39032 * @param {Arrary<number>} tile - The tile coordinates.
39034 TextureProvider.prototype._tileKey = function (tile) {
39035 return tile[0] + "-" + tile[1];
39037 return TextureProvider;
39039 exports.TextureProvider = TextureProvider;
39040 exports.default = TextureProvider;
39042 },{"rxjs/Subject":34,"three":176}],347:[function(require,module,exports){
39044 Object.defineProperty(exports, "__esModule", { value: true });
39045 var EventEmitter = (function () {
39046 function EventEmitter() {
39050 * Subscribe to an event by its name.
39051 * @param {string }eventType - The name of the event to subscribe to.
39052 * @param {any} fn - The handler called when the event occurs.
39054 EventEmitter.prototype.on = function (eventType, fn) {
39055 this._events[eventType] = this._events[eventType] || [];
39056 this._events[eventType].push(fn);
39060 * Unsubscribe from an event by its name.
39061 * @param {string} eventType - The name of the event to subscribe to.
39062 * @param {any} fn - The handler to remove.
39064 EventEmitter.prototype.off = function (eventType, fn) {
39069 if (!this._listens(eventType)) {
39070 var idx = this._events[eventType].indexOf(fn);
39072 this._events[eventType].splice(idx, 1);
39074 if (this._events[eventType].length) {
39075 delete this._events[eventType];
39079 delete this._events[eventType];
39083 EventEmitter.prototype.fire = function (eventType, data) {
39084 if (!this._listens(eventType)) {
39087 for (var _i = 0, _a = this._events[eventType]; _i < _a.length; _i++) {
39089 fn.call(this, data);
39093 EventEmitter.prototype._listens = function (eventType) {
39094 return !!(this._events && this._events[eventType]);
39096 return EventEmitter;
39098 exports.EventEmitter = EventEmitter;
39099 exports.default = EventEmitter;
39101 },{}],348:[function(require,module,exports){
39103 Object.defineProperty(exports, "__esModule", { value: true });
39104 var Viewer_1 = require("../Viewer");
39105 var Settings = (function () {
39106 function Settings() {
39108 Settings.setOptions = function (options) {
39109 Settings._baseImageSize = options.baseImageSize != null ?
39110 options.baseImageSize :
39111 Viewer_1.ImageSize.Size640;
39112 Settings._basePanoramaSize = options.basePanoramaSize != null ?
39113 options.basePanoramaSize :
39114 Viewer_1.ImageSize.Size2048;
39115 Settings._maxImageSize = options.maxImageSize != null ?
39116 options.maxImageSize :
39117 Viewer_1.ImageSize.Size2048;
39119 Object.defineProperty(Settings, "baseImageSize", {
39121 return Settings._baseImageSize;
39126 Object.defineProperty(Settings, "basePanoramaSize", {
39128 return Settings._basePanoramaSize;
39133 Object.defineProperty(Settings, "maxImageSize", {
39135 return Settings._maxImageSize;
39142 exports.Settings = Settings;
39143 exports.default = Settings;
39145 },{"../Viewer":237}],349:[function(require,module,exports){
39147 Object.defineProperty(exports, "__esModule", { value: true });
39148 function isBrowser() {
39149 return typeof window !== "undefined" && typeof document !== "undefined";
39151 exports.isBrowser = isBrowser;
39152 function isArraySupported() {
39153 return !!(Array.prototype &&
39154 Array.prototype.filter &&
39155 Array.prototype.indexOf &&
39156 Array.prototype.map);
39158 exports.isArraySupported = isArraySupported;
39159 function isFunctionSupported() {
39160 return !!(Function.prototype && Function.prototype.bind);
39162 exports.isFunctionSupported = isFunctionSupported;
39163 function isJSONSupported() {
39164 return "JSON" in window && "parse" in JSON && "stringify" in JSON;
39166 exports.isJSONSupported = isJSONSupported;
39167 function isObjectSupported() {
39168 return !!(Object.keys &&
39171 exports.isObjectSupported = isObjectSupported;
39172 var isWebGLSupportedCache = undefined;
39173 function isWebGLSupportedCached() {
39174 if (isWebGLSupportedCache === undefined) {
39175 isWebGLSupportedCache = isWebGLSupported();
39177 return isWebGLSupportedCache;
39179 exports.isWebGLSupportedCached = isWebGLSupportedCached;
39180 function isWebGLSupported() {
39181 var webGLContextAttributes = {
39185 failIfMajorPerformanceCaveat: false,
39186 premultipliedAlpha: true,
39187 preserveDrawingBuffer: false,
39190 var canvas = document.createElement("canvas");
39191 var context = canvas.getContext("webgl", webGLContextAttributes) ||
39192 canvas.getContext("experimental-webgl", webGLContextAttributes);
39196 var requiredExtensions = [
39197 "OES_texture_float",
39198 "OES_standard_derivatives",
39200 var supportedExtensions = context.getSupportedExtensions();
39201 for (var _i = 0, requiredExtensions_1 = requiredExtensions; _i < requiredExtensions_1.length; _i++) {
39202 var requiredExtension = requiredExtensions_1[_i];
39203 if (supportedExtensions.indexOf(requiredExtension) === -1) {
39209 exports.isWebGLSupported = isWebGLSupported;
39211 },{}],350:[function(require,module,exports){
39213 Object.defineProperty(exports, "__esModule", { value: true });
39214 var Urls = (function () {
39217 Object.defineProperty(Urls, "tileScheme", {
39224 Object.defineProperty(Urls, "tileDomain", {
39226 return "d2qb1440i7l50o.cloudfront.net";
39231 Object.defineProperty(Urls, "origin", {
39233 return "mapillary.webgl";
39238 Urls.thumbnail = function (key, size) {
39239 return "https://d1cuyjsrcm0gby.cloudfront.net/" + key + "/thumb-" + size + ".jpg?origin=" + this.origin;
39241 Urls.falcorModel = function (clientId) {
39242 return "https://a.mapillary.com/v3/model.json?client_id=" + clientId;
39244 Urls.protoMesh = function (key) {
39245 return "https://d1brzeo354iq2l.cloudfront.net/v2/mesh/" + key;
39249 exports.Urls = Urls;
39250 exports.default = Urls;
39252 },{}],351:[function(require,module,exports){
39254 Object.defineProperty(exports, "__esModule", { value: true });
39256 * Enumeration for alignments
39261 (function (Alignment) {
39265 Alignment[Alignment["Bottom"] = 0] = "Bottom";
39267 * Align to bottom left
39269 Alignment[Alignment["BottomLeft"] = 1] = "BottomLeft";
39271 * Align to bottom right
39273 Alignment[Alignment["BottomRight"] = 2] = "BottomRight";
39277 Alignment[Alignment["Center"] = 3] = "Center";
39281 Alignment[Alignment["Left"] = 4] = "Left";
39285 Alignment[Alignment["Right"] = 5] = "Right";
39289 Alignment[Alignment["Top"] = 6] = "Top";
39291 * Align to top left
39293 Alignment[Alignment["TopLeft"] = 7] = "TopLeft";
39295 * Align to top right
39297 Alignment[Alignment["TopRight"] = 8] = "TopRight";
39298 })(Alignment = exports.Alignment || (exports.Alignment = {}));
39299 exports.default = Alignment;
39301 },{}],352:[function(require,module,exports){
39303 Object.defineProperty(exports, "__esModule", { value: true });
39304 require("rxjs/add/operator/bufferCount");
39305 require("rxjs/add/operator/delay");
39306 require("rxjs/add/operator/distinctUntilChanged");
39307 require("rxjs/add/operator/map");
39308 require("rxjs/add/operator/switchMap");
39309 var CacheService = (function () {
39310 function CacheService(graphService, stateService) {
39311 this._graphService = graphService;
39312 this._stateService = stateService;
39313 this._started = false;
39315 Object.defineProperty(CacheService.prototype, "started", {
39317 return this._started;
39322 CacheService.prototype.start = function () {
39324 if (this._started) {
39327 this._uncacheSubscription = this._stateService.currentState$
39328 .distinctUntilChanged(undefined, function (frame) {
39329 return frame.state.currentNode.key;
39331 .map(function (frame) {
39332 return frame.state.trajectory
39333 .map(function (n) {
39338 .switchMap(function (keepKeysBuffer) {
39339 var keepKeys = keepKeysBuffer[0];
39340 return _this._graphService.uncache$(keepKeys);
39342 .subscribe(function () { });
39343 this._started = true;
39345 CacheService.prototype.stop = function () {
39346 if (!this._started) {
39349 this._uncacheSubscription.unsubscribe();
39350 this._uncacheSubscription = null;
39351 this._started = false;
39353 return CacheService;
39355 exports.CacheService = CacheService;
39356 exports.default = CacheService;
39358 },{"rxjs/add/operator/bufferCount":50,"rxjs/add/operator/delay":56,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/map":65,"rxjs/add/operator/switchMap":79}],353:[function(require,module,exports){
39360 Object.defineProperty(exports, "__esModule", { value: true });
39361 var Component_1 = require("../Component");
39362 var ComponentController = (function () {
39363 function ComponentController(container, navigator, observer, key, options, componentService) {
39365 this._container = container;
39366 this._observer = observer;
39367 this._navigator = navigator;
39368 this._options = options != null ? options : {};
39370 this._navigable = key == null;
39371 this._componentService = !!componentService ?
39373 new Component_1.ComponentService(this._container, this._navigator);
39374 this._coverComponent = this._componentService.getCover();
39375 this._initializeComponents();
39377 this._initilizeCoverComponent();
39378 this._subscribeCoverComponent();
39381 this._navigator.movedToKey$
39382 .first(function (k) {
39385 .subscribe(function (k) {
39387 _this._componentService.deactivateCover();
39388 _this._coverComponent.configure({ key: _this._key, state: Component_1.CoverState.Hidden });
39389 _this._subscribeCoverComponent();
39390 _this._navigator.stateService.start();
39391 _this._observer.startEmit();
39395 Object.defineProperty(ComponentController.prototype, "navigable", {
39397 return this._navigable;
39402 ComponentController.prototype.get = function (name) {
39403 return this._componentService.get(name);
39405 ComponentController.prototype.activate = function (name) {
39406 this._componentService.activate(name);
39408 ComponentController.prototype.activateCover = function () {
39409 this._coverComponent.configure({ state: Component_1.CoverState.Visible });
39411 ComponentController.prototype.deactivate = function (name) {
39412 this._componentService.deactivate(name);
39414 ComponentController.prototype.deactivateCover = function () {
39415 this._coverComponent.configure({ state: Component_1.CoverState.Loading });
39417 ComponentController.prototype.resize = function () {
39418 this._componentService.resize();
39420 ComponentController.prototype._initializeComponents = function () {
39421 var options = this._options;
39422 this._uFalse(options.background, "background");
39423 this._uFalse(options.debug, "debug");
39424 this._uFalse(options.image, "image");
39425 this._uFalse(options.marker, "marker");
39426 this._uFalse(options.navigation, "navigation");
39427 this._uFalse(options.popup, "popup");
39428 this._uFalse(options.route, "route");
39429 this._uFalse(options.slider, "slider");
39430 this._uFalse(options.tag, "tag");
39431 this._uTrue(options.attribution, "attribution");
39432 this._uTrue(options.bearing, "bearing");
39433 this._uTrue(options.cache, "cache");
39434 this._uTrue(options.direction, "direction");
39435 this._uTrue(options.imagePlane, "imagePlane");
39436 this._uTrue(options.keyboard, "keyboard");
39437 this._uTrue(options.loading, "loading");
39438 this._uTrue(options.mouse, "mouse");
39439 this._uTrue(options.sequence, "sequence");
39440 this._uTrue(options.stats, "stats");
39442 ComponentController.prototype._initilizeCoverComponent = function () {
39443 var options = this._options;
39444 this._coverComponent.configure({ key: this._key });
39445 if (options.cover === undefined || options.cover) {
39446 this.activateCover();
39449 this.deactivateCover();
39452 ComponentController.prototype._setNavigable = function (navigable) {
39453 if (this._navigable === navigable) {
39456 this._navigable = navigable;
39457 this._observer.navigable$.next(navigable);
39459 ComponentController.prototype._subscribeCoverComponent = function () {
39461 this._coverComponent.configuration$.subscribe(function (conf) {
39462 if (conf.state === Component_1.CoverState.Loading) {
39463 _this._navigator.stateService.currentKey$
39465 .switchMap(function (key) {
39466 var keyChanged = key == null || key !== conf.key;
39468 _this._setNavigable(false);
39470 return keyChanged ?
39471 _this._navigator.moveToKey$(conf.key) :
39472 _this._navigator.stateService.currentNode$
39475 .subscribe(function (node) {
39476 _this._navigator.stateService.start();
39477 _this._observer.startEmit();
39478 _this._coverComponent.configure({ state: Component_1.CoverState.Hidden });
39479 _this._componentService.deactivateCover();
39480 _this._setNavigable(true);
39481 }, function (error) {
39482 console.error("Failed to deactivate cover.", error);
39483 _this._coverComponent.configure({ state: Component_1.CoverState.Visible });
39486 else if (conf.state === Component_1.CoverState.Visible) {
39487 _this._observer.stopEmit();
39488 _this._navigator.stateService.stop();
39489 _this._componentService.activateCover();
39490 _this._setNavigable(conf.key == null);
39494 ComponentController.prototype._uFalse = function (option, name) {
39495 if (option === undefined) {
39496 this._componentService.deactivate(name);
39499 if (typeof option === "boolean") {
39501 this._componentService.activate(name);
39504 this._componentService.deactivate(name);
39508 this._componentService.configure(name, option);
39509 this._componentService.activate(name);
39511 ComponentController.prototype._uTrue = function (option, name) {
39512 if (option === undefined) {
39513 this._componentService.activate(name);
39516 if (typeof option === "boolean") {
39518 this._componentService.activate(name);
39521 this._componentService.deactivate(name);
39525 this._componentService.configure(name, option);
39526 this._componentService.activate(name);
39528 return ComponentController;
39530 exports.ComponentController = ComponentController;
39532 },{"../Component":226}],354:[function(require,module,exports){
39534 Object.defineProperty(exports, "__esModule", { value: true });
39535 var Render_1 = require("../Render");
39536 var Viewer_1 = require("../Viewer");
39537 var Container = (function () {
39538 function Container(id, stateService, options) {
39540 this._container = document.getElementById(id);
39541 if (!this._container) {
39542 throw new Error("Container '" + id + "' not found.");
39544 this._container.classList.add("mapillary-js");
39545 this._canvasContainer = document.createElement("div");
39546 this._canvasContainer.className = "mapillary-js-interactive";
39547 this._domContainer = document.createElement("div");
39548 this._domContainer.className = "mapillary-js-dom";
39549 this._container.appendChild(this._canvasContainer);
39550 this._container.appendChild(this._domContainer);
39551 this.renderService = new Render_1.RenderService(this._container, stateService.currentState$, options.renderMode);
39552 this.glRenderer = new Render_1.GLRenderer(this._canvasContainer, this.renderService);
39553 this.domRenderer = new Render_1.DOMRenderer(this._domContainer, this.renderService, stateService.currentState$);
39554 this.keyboardService = new Viewer_1.KeyboardService(this._canvasContainer);
39555 this.mouseService = new Viewer_1.MouseService(this._container, this._canvasContainer, this._domContainer);
39556 this.touchService = new Viewer_1.TouchService(this._canvasContainer, this._domContainer);
39557 this.spriteService = new Viewer_1.SpriteService(options.sprite);
39559 Object.defineProperty(Container.prototype, "element", {
39561 return this._container;
39566 Object.defineProperty(Container.prototype, "canvasContainer", {
39568 return this._canvasContainer;
39575 exports.Container = Container;
39576 exports.default = Container;
39578 },{"../Render":232,"../Viewer":237}],355:[function(require,module,exports){
39580 Object.defineProperty(exports, "__esModule", { value: true });
39582 * Enumeration for image sizes
39585 * @description Image sizes in pixels for the long side of the image.
39588 (function (ImageSize) {
39590 * 320 pixels image size
39592 ImageSize[ImageSize["Size320"] = 320] = "Size320";
39594 * 640 pixels image size
39596 ImageSize[ImageSize["Size640"] = 640] = "Size640";
39598 * 1024 pixels image size
39600 ImageSize[ImageSize["Size1024"] = 1024] = "Size1024";
39602 * 2048 pixels image size
39604 ImageSize[ImageSize["Size2048"] = 2048] = "Size2048";
39605 })(ImageSize = exports.ImageSize || (exports.ImageSize = {}));
39607 },{}],356:[function(require,module,exports){
39609 Object.defineProperty(exports, "__esModule", { value: true });
39610 var Observable_1 = require("rxjs/Observable");
39611 var KeyboardService = (function () {
39612 function KeyboardService(canvasContainer) {
39613 this._keyDown$ = Observable_1.Observable.fromEvent(canvasContainer, "keydown");
39615 Object.defineProperty(KeyboardService.prototype, "keyDown$", {
39617 return this._keyDown$;
39622 return KeyboardService;
39624 exports.KeyboardService = KeyboardService;
39625 exports.default = KeyboardService;
39627 },{"rxjs/Observable":29}],357:[function(require,module,exports){
39629 /// <reference path="../../typings/index.d.ts" />
39630 Object.defineProperty(exports, "__esModule", { value: true });
39631 var _ = require("underscore");
39632 var Subject_1 = require("rxjs/Subject");
39633 require("rxjs/add/operator/debounceTime");
39634 require("rxjs/add/operator/distinctUntilChanged");
39635 require("rxjs/add/operator/map");
39636 require("rxjs/add/operator/publishReplay");
39637 require("rxjs/add/operator/scan");
39638 require("rxjs/add/operator/startWith");
39639 var LoadingService = (function () {
39640 function LoadingService() {
39641 this._loadersSubject$ = new Subject_1.Subject();
39642 this._loaders$ = this._loadersSubject$
39643 .scan(function (loaders, loader) {
39644 if (loader.task !== undefined) {
39645 loaders[loader.task] = loader.loading;
39653 Object.defineProperty(LoadingService.prototype, "loading$", {
39655 return this._loaders$
39656 .map(function (loaders) {
39657 return _.reduce(loaders, function (loader, acc) {
39658 return (loader || acc);
39662 .distinctUntilChanged();
39667 LoadingService.prototype.taskLoading$ = function (task) {
39668 return this._loaders$
39669 .map(function (loaders) {
39670 return !!loaders[task];
39673 .distinctUntilChanged();
39675 LoadingService.prototype.startLoading = function (task) {
39676 this._loadersSubject$.next({ loading: true, task: task });
39678 LoadingService.prototype.stopLoading = function (task) {
39679 this._loadersSubject$.next({ loading: false, task: task });
39681 return LoadingService;
39683 exports.LoadingService = LoadingService;
39684 exports.default = LoadingService;
39686 },{"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":73,"rxjs/add/operator/startWith":78,"underscore":178}],358:[function(require,module,exports){
39688 Object.defineProperty(exports, "__esModule", { value: true });
39689 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
39690 var Observable_1 = require("rxjs/Observable");
39691 var Subject_1 = require("rxjs/Subject");
39692 require("rxjs/add/observable/fromEvent");
39693 require("rxjs/add/operator/distinctUntilChanged");
39694 require("rxjs/add/operator/filter");
39695 require("rxjs/add/operator/map");
39696 require("rxjs/add/operator/merge");
39697 require("rxjs/add/operator/mergeMap");
39698 require("rxjs/add/operator/publishReplay");
39699 require("rxjs/add/operator/scan");
39700 require("rxjs/add/operator/switchMap");
39701 require("rxjs/add/operator/withLatestFrom");
39702 var Geo_1 = require("../Geo");
39703 var MouseService = (function () {
39704 function MouseService(container, canvasContainer, domContainer, viewportCoords) {
39706 this._canvasContainer = canvasContainer;
39707 this._domContainer = domContainer;
39708 this._viewportCoords = viewportCoords != null ? viewportCoords : new Geo_1.ViewportCoords();
39709 this._activeSubject$ = new BehaviorSubject_1.BehaviorSubject(false);
39710 this._active$ = this._activeSubject$
39711 .distinctUntilChanged()
39714 this._claimMouse$ = new Subject_1.Subject();
39715 this._documentMouseMove$ = Observable_1.Observable.fromEvent(document, "mousemove");
39716 this._documentMouseUp$ = Observable_1.Observable.fromEvent(document, "mouseup");
39717 this._mouseDown$ = Observable_1.Observable.fromEvent(canvasContainer, "mousedown");
39718 this._mouseLeave$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseleave");
39719 this._mouseMove$ = Observable_1.Observable.fromEvent(canvasContainer, "mousemove");
39720 this._mouseUp$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseup");
39721 this._mouseOut$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseout");
39722 this._mouseOver$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseover");
39723 this._domMouseDown$ = Observable_1.Observable.fromEvent(domContainer, "mousedown");
39724 this._domMouseMove$ = Observable_1.Observable.fromEvent(domContainer, "mousemove");
39725 this._click$ = Observable_1.Observable.fromEvent(canvasContainer, "click");
39726 this._contextMenu$ = Observable_1.Observable.fromEvent(canvasContainer, "contextmenu");
39727 this._dblClick$ = Observable_1.Observable
39728 .merge(Observable_1.Observable.fromEvent(container, "click"), Observable_1.Observable.fromEvent(canvasContainer, "dblclick"))
39730 .filter(function (events) {
39731 var event1 = events[0];
39732 var event2 = events[1];
39733 var event3 = events[2];
39734 return event1.type === "click" &&
39735 event2.type === "click" &&
39736 event3.type === "dblclick" &&
39737 event1.target.parentNode === canvasContainer &&
39738 event2.target.parentNode === canvasContainer;
39740 .map(function (events) {
39744 Observable_1.Observable
39745 .merge(this._domMouseDown$, this._domMouseMove$, this._dblClick$, this._contextMenu$)
39746 .subscribe(function (event) {
39747 event.preventDefault();
39749 this._mouseWheel$ = Observable_1.Observable
39750 .merge(Observable_1.Observable.fromEvent(canvasContainer, "wheel"), Observable_1.Observable.fromEvent(domContainer, "wheel"));
39751 this._consistentContextMenu$ = Observable_1.Observable
39752 .merge(this._mouseDown$, this._mouseMove$, this._mouseOut$, this._mouseUp$, this._contextMenu$)
39754 .filter(function (events) {
39755 // fire context menu on mouse up both on mac and windows
39756 return events[0].type === "mousedown" &&
39757 events[1].type === "contextmenu" &&
39758 events[2].type === "mouseup";
39760 .map(function (events) {
39764 var dragStop$ = Observable_1.Observable
39765 .merge(Observable_1.Observable.fromEvent(window, "blur"), this._documentMouseUp$
39766 .filter(function (e) {
39767 return e.button === 0;
39770 var leftButtonDown$ = this._mouseDown$
39771 .filter(function (e) {
39772 return e.button === 0;
39775 this._mouseDragStart$ = leftButtonDown$
39776 .mergeMap(function (e) {
39777 return _this._documentMouseMove$
39778 .takeUntil(dragStop$)
39781 this._mouseDrag$ = leftButtonDown$
39782 .mergeMap(function (e) {
39783 return _this._documentMouseMove$
39785 .takeUntil(dragStop$);
39787 this._mouseDragEnd$ = this._mouseDragStart$
39788 .mergeMap(function (e) {
39789 return dragStop$.first();
39791 var containerLeftButtonDown$ = this._domMouseDown$
39792 .filter(function (e) {
39793 return e.button === 0;
39796 this._domMouseDragStart$ = containerLeftButtonDown$
39797 .mergeMap(function (e) {
39798 return _this._documentMouseMove$
39799 .takeUntil(dragStop$)
39802 this._domMouseDrag$ = containerLeftButtonDown$
39803 .mergeMap(function (e) {
39804 return _this._documentMouseMove$
39806 .takeUntil(dragStop$);
39808 this._domMouseDragEnd$ = this._domMouseDragStart$
39809 .mergeMap(function (e) {
39810 return dragStop$.first();
39812 this._staticClick$ = this._mouseDown$
39813 .switchMap(function (e) {
39814 return _this._click$
39815 .takeUntil(_this._mouseMove$)
39818 this._mouseOwner$ = this._claimMouse$
39819 .scan(function (claims, mouseClaim) {
39820 if (mouseClaim.zindex == null) {
39821 delete claims[mouseClaim.name];
39824 claims[mouseClaim.name] = mouseClaim.zindex;
39828 .map(function (claims) {
39831 for (var name_1 in claims) {
39832 if (claims.hasOwnProperty(name_1)) {
39833 if (claims[name_1] > curZ) {
39834 curZ = claims[name_1];
39843 this._mouseOwner$.subscribe(function () { });
39845 Object.defineProperty(MouseService.prototype, "active$", {
39847 return this._active$;
39852 Object.defineProperty(MouseService.prototype, "activate$", {
39854 return this._activeSubject$;
39859 Object.defineProperty(MouseService.prototype, "documentMouseMove$", {
39861 return this._documentMouseMove$;
39866 Object.defineProperty(MouseService.prototype, "documentMouseUp$", {
39868 return this._documentMouseUp$;
39873 Object.defineProperty(MouseService.prototype, "domMouseDragStart$", {
39875 return this._domMouseDragStart$;
39880 Object.defineProperty(MouseService.prototype, "domMouseDrag$", {
39882 return this._domMouseDrag$;
39887 Object.defineProperty(MouseService.prototype, "domMouseDragEnd$", {
39889 return this._domMouseDragEnd$;
39894 Object.defineProperty(MouseService.prototype, "domMouseDown$", {
39896 return this._domMouseDown$;
39901 Object.defineProperty(MouseService.prototype, "domMouseMove$", {
39903 return this._domMouseMove$;
39908 Object.defineProperty(MouseService.prototype, "mouseOwner$", {
39910 return this._mouseOwner$;
39915 Object.defineProperty(MouseService.prototype, "mouseDown$", {
39917 return this._mouseDown$;
39922 Object.defineProperty(MouseService.prototype, "mouseMove$", {
39924 return this._mouseMove$;
39929 Object.defineProperty(MouseService.prototype, "mouseLeave$", {
39931 return this._mouseLeave$;
39936 Object.defineProperty(MouseService.prototype, "mouseOut$", {
39938 return this._mouseOut$;
39943 Object.defineProperty(MouseService.prototype, "mouseOver$", {
39945 return this._mouseOver$;
39950 Object.defineProperty(MouseService.prototype, "mouseUp$", {
39952 return this._mouseUp$;
39957 Object.defineProperty(MouseService.prototype, "click$", {
39959 return this._click$;
39964 Object.defineProperty(MouseService.prototype, "dblClick$", {
39966 return this._dblClick$;
39971 Object.defineProperty(MouseService.prototype, "contextMenu$", {
39973 return this._consistentContextMenu$;
39978 Object.defineProperty(MouseService.prototype, "mouseWheel$", {
39980 return this._mouseWheel$;
39985 Object.defineProperty(MouseService.prototype, "mouseDragStart$", {
39987 return this._mouseDragStart$;
39992 Object.defineProperty(MouseService.prototype, "mouseDrag$", {
39994 return this._mouseDrag$;
39999 Object.defineProperty(MouseService.prototype, "mouseDragEnd$", {
40001 return this._mouseDragEnd$;
40006 Object.defineProperty(MouseService.prototype, "staticClick$", {
40008 return this._staticClick$;
40013 MouseService.prototype.claimMouse = function (name, zindex) {
40014 this._claimMouse$.next({ name: name, zindex: zindex });
40016 MouseService.prototype.unclaimMouse = function (name) {
40017 this._claimMouse$.next({ name: name, zindex: null });
40019 MouseService.prototype.filtered$ = function (name, observable$) {
40021 .withLatestFrom(this.mouseOwner$, function (event, owner) {
40022 return [event, owner];
40024 .filter(function (eo) {
40025 return eo[1] === name;
40027 .map(function (eo) {
40031 return MouseService;
40033 exports.MouseService = MouseService;
40034 exports.default = MouseService;
40036 },{"../Geo":229,"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":73,"rxjs/add/operator/switchMap":79,"rxjs/add/operator/withLatestFrom":83}],359:[function(require,module,exports){
40038 /// <reference path="../../typings/index.d.ts" />
40039 Object.defineProperty(exports, "__esModule", { value: true });
40040 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
40041 var Observable_1 = require("rxjs/Observable");
40042 var ReplaySubject_1 = require("rxjs/ReplaySubject");
40043 require("rxjs/add/observable/throw");
40044 require("rxjs/add/operator/do");
40045 require("rxjs/add/operator/finally");
40046 require("rxjs/add/operator/first");
40047 require("rxjs/add/operator/map");
40048 require("rxjs/add/operator/mergeMap");
40049 var API_1 = require("../API");
40050 var Graph_1 = require("../Graph");
40051 var Edge_1 = require("../Edge");
40052 var State_1 = require("../State");
40053 var Viewer_1 = require("../Viewer");
40054 var Navigator = (function () {
40055 function Navigator(clientId, token, apiV3, graphService, imageLoadingService, loadingService, stateService, cacheService) {
40056 this._apiV3 = apiV3 != null ? apiV3 : new API_1.APIv3(clientId, token);
40057 this._imageLoadingService = imageLoadingService != null ? imageLoadingService : new Graph_1.ImageLoadingService();
40058 this._graphService = graphService != null ?
40060 new Graph_1.GraphService(new Graph_1.Graph(this.apiV3), this._imageLoadingService);
40061 this._loadingService = loadingService != null ? loadingService : new Viewer_1.LoadingService();
40062 this._loadingName = "navigator";
40063 this._stateService = stateService != null ? stateService : new State_1.StateService();
40064 this._cacheService = cacheService != null ?
40066 new Viewer_1.CacheService(this._graphService, this._stateService);
40067 this._cacheService.start();
40068 this._keyRequested$ = new BehaviorSubject_1.BehaviorSubject(null);
40069 this._movedToKey$ = new BehaviorSubject_1.BehaviorSubject(null);
40070 this._request$ = null;
40071 this._requestSubscription = null;
40072 this._nodeRequestSubscription = null;
40074 Object.defineProperty(Navigator.prototype, "apiV3", {
40076 return this._apiV3;
40081 Object.defineProperty(Navigator.prototype, "graphService", {
40083 return this._graphService;
40088 Object.defineProperty(Navigator.prototype, "imageLoadingService", {
40090 return this._imageLoadingService;
40095 Object.defineProperty(Navigator.prototype, "loadingService", {
40097 return this._loadingService;
40102 Object.defineProperty(Navigator.prototype, "movedToKey$", {
40104 return this._movedToKey$;
40109 Object.defineProperty(Navigator.prototype, "stateService", {
40111 return this._stateService;
40116 Navigator.prototype.moveToKey$ = function (key) {
40117 this._abortRequest("to key " + key);
40118 this._loadingService.startLoading(this._loadingName);
40119 var node$ = this._moveToKey$(key);
40120 return this._makeRequest$(node$);
40122 Navigator.prototype.moveDir$ = function (direction) {
40124 this._abortRequest("in dir " + Edge_1.EdgeDirection[direction]);
40125 this._loadingService.startLoading(this._loadingName);
40126 var node$ = this.stateService.currentNode$
40128 .mergeMap(function (node) {
40129 return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
40130 node.sequenceEdges$ :
40131 node.spatialEdges$)
40133 .map(function (status) {
40134 for (var _i = 0, _a = status.edges; _i < _a.length; _i++) {
40136 if (edge.data.direction === direction) {
40143 .mergeMap(function (directionKey) {
40144 if (directionKey == null) {
40145 _this._loadingService.stopLoading(_this._loadingName);
40146 return Observable_1.Observable
40147 .throw(new Error("Direction (" + direction + ") does not exist for current node."));
40149 return _this._moveToKey$(directionKey);
40151 return this._makeRequest$(node$);
40153 Navigator.prototype.moveCloseTo$ = function (lat, lon) {
40155 this._abortRequest("to lat " + lat + ", lon " + lon);
40156 this._loadingService.startLoading(this._loadingName);
40157 var node$ = this.apiV3.imageCloseTo$(lat, lon)
40158 .mergeMap(function (fullNode) {
40159 if (fullNode == null) {
40160 _this._loadingService.stopLoading(_this._loadingName);
40161 return Observable_1.Observable
40162 .throw(new Error("No image found close to lat " + lat + ", lon " + lon + "."));
40164 return _this._moveToKey$(fullNode.key);
40166 return this._makeRequest$(node$);
40168 Navigator.prototype.setFilter$ = function (filter) {
40170 this._stateService.clearNodes();
40171 return this._movedToKey$
40173 .mergeMap(function (key) {
40175 return _this._trajectoryKeys$()
40176 .mergeMap(function (keys) {
40177 return _this._graphService.setFilter$(filter)
40178 .mergeMap(function (graph) {
40179 return _this._cacheKeys$(keys);
40184 return _this._keyRequested$
40186 .mergeMap(function (requestedKey) {
40187 if (requestedKey != null) {
40188 return _this._graphService.setFilter$(filter)
40189 .mergeMap(function (graph) {
40190 return _this._graphService.cacheNode$(requestedKey);
40193 return _this._graphService.setFilter$(filter)
40194 .map(function (graph) {
40199 .map(function (node) {
40203 Navigator.prototype.setToken$ = function (token) {
40205 this._abortRequest("to set token");
40206 this._stateService.clearNodes();
40207 return this._movedToKey$
40209 .do(function (key) {
40210 _this._apiV3.setToken(token);
40212 .mergeMap(function (key) {
40213 return key == null ?
40214 _this._graphService.reset$([])
40215 .map(function (graph) {
40218 _this._trajectoryKeys$()
40219 .mergeMap(function (keys) {
40220 return _this._graphService.reset$(keys)
40221 .mergeMap(function (graph) {
40222 return _this._cacheKeys$(keys);
40226 .map(function (node) {
40231 Navigator.prototype._cacheKeys$ = function (keys) {
40233 var cacheNodes$ = keys
40234 .map(function (key) {
40235 return _this._graphService.cacheNode$(key);
40237 return Observable_1.Observable
40241 Navigator.prototype._abortRequest = function (reason) {
40242 if (this._requestSubscription != null) {
40243 this._requestSubscription.unsubscribe();
40244 this._requestSubscription = null;
40246 if (this._nodeRequestSubscription != null) {
40247 this._nodeRequestSubscription.unsubscribe();
40248 this._nodeRequestSubscription = null;
40250 if (this._request$ != null) {
40251 this._request$.error(new Error("Request aborted by a subsequent request " + reason + "."));
40252 this._request$ = null;
40255 Navigator.prototype._makeRequest$ = function (node$) {
40257 this._request$ = new ReplaySubject_1.ReplaySubject(1);
40258 this._requestSubscription = this._request$
40259 .subscribe(undefined, function (e) { });
40260 this._nodeRequestSubscription = node$
40261 .subscribe(function (node) {
40262 _this._request$.next(node);
40263 _this._request$.complete();
40264 }, function (error) {
40265 _this._request$.error(error);
40267 return this._request$;
40269 Navigator.prototype._moveToKey$ = function (key) {
40271 this._keyRequested$.next(key);
40272 return this._graphService.cacheNode$(key)
40273 .do(function (node) {
40274 _this._stateService.setNodes([node]);
40275 _this._movedToKey$.next(node.key);
40277 .finally(function () {
40278 _this._loadingService.stopLoading(_this._loadingName);
40281 Navigator.prototype._trajectoryKeys$ = function () {
40282 return this._stateService.currentState$
40284 .map(function (frame) {
40285 return frame.state.trajectory
40286 .map(function (node) {
40293 exports.Navigator = Navigator;
40294 exports.default = Navigator;
40296 },{"../API":225,"../Edge":227,"../Graph":230,"../State":233,"../Viewer":237,"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}],360:[function(require,module,exports){
40298 Object.defineProperty(exports, "__esModule", { value: true });
40299 var Observable_1 = require("rxjs/Observable");
40300 var Subject_1 = require("rxjs/Subject");
40301 require("rxjs/add/observable/combineLatest");
40302 require("rxjs/add/operator/distinctUntilChanged");
40303 require("rxjs/add/operator/map");
40304 require("rxjs/add/operator/throttleTime");
40305 var Viewer_1 = require("../Viewer");
40306 var Observer = (function () {
40307 function Observer(eventEmitter, navigator, container) {
40309 this._container = container;
40310 this._eventEmitter = eventEmitter;
40311 this._navigator = navigator;
40312 this._projection = new Viewer_1.Projection();
40313 this._started = false;
40314 this._navigable$ = new Subject_1.Subject();
40315 // navigable and loading should always emit, also when cover is activated.
40317 .subscribe(function (navigable) {
40318 _this._eventEmitter.fire(Viewer_1.Viewer.navigablechanged, navigable);
40320 this._navigator.loadingService.loading$
40321 .subscribe(function (loading) {
40322 _this._eventEmitter.fire(Viewer_1.Viewer.loadingchanged, loading);
40325 Object.defineProperty(Observer.prototype, "started", {
40327 return this._started;
40332 Object.defineProperty(Observer.prototype, "navigable$", {
40334 return this._navigable$;
40339 Observer.prototype.projectBasic$ = function (basicPoint) {
40341 return Observable_1.Observable
40342 .combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
40344 .map(function (_a) {
40345 var render = _a[0], transform = _a[1];
40346 var canvasPoint = _this._projection.basicToCanvas(basicPoint, _this._container.element, render, transform);
40347 return [Math.round(canvasPoint[0]), Math.round(canvasPoint[1])];
40350 Observer.prototype.startEmit = function () {
40352 if (this._started) {
40355 this._started = true;
40356 this._currentNodeSubscription = this._navigator.stateService.currentNodeExternal$
40357 .subscribe(function (node) {
40358 _this._eventEmitter.fire(Viewer_1.Viewer.nodechanged, node);
40360 this._sequenceEdgesSubscription = this._navigator.stateService.currentNodeExternal$
40361 .switchMap(function (node) {
40362 return node.sequenceEdges$;
40364 .subscribe(function (status) {
40365 _this._eventEmitter.fire(Viewer_1.Viewer.sequenceedgeschanged, status);
40367 this._spatialEdgesSubscription = this._navigator.stateService.currentNodeExternal$
40368 .switchMap(function (node) {
40369 return node.spatialEdges$;
40371 .subscribe(function (status) {
40372 _this._eventEmitter.fire(Viewer_1.Viewer.spatialedgeschanged, status);
40374 this._moveSubscription = Observable_1.Observable
40375 .combineLatest(this._navigator.stateService.inMotion$, this._container.mouseService.active$, this._container.touchService.active$)
40376 .map(function (values) {
40377 return values[0] || values[1] || values[2];
40379 .distinctUntilChanged()
40380 .subscribe(function (started) {
40382 _this._eventEmitter.fire(Viewer_1.Viewer.movestart, null);
40385 _this._eventEmitter.fire(Viewer_1.Viewer.moveend, null);
40388 this._bearingSubscription = this._container.renderService.bearing$
40390 .distinctUntilChanged(function (b1, b2) {
40391 return Math.abs(b2 - b1) < 1;
40393 .subscribe(function (bearing) {
40394 _this._eventEmitter.fire(Viewer_1.Viewer.bearingchanged, bearing);
40396 var mouseMove$ = this._container.mouseService.active$
40397 .switchMap(function (active) {
40399 Observable_1.Observable.empty() :
40400 _this._container.mouseService.mouseMove$;
40402 this._viewerMouseEventSubscription = Observable_1.Observable
40403 .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$))
40404 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.reference$, this._navigator.stateService.currentTransform$)
40405 .map(function (_a) {
40406 var _b = _a[0], type = _b[0], event = _b[1], render = _a[1], reference = _a[2], transform = _a[3];
40407 var unprojection = _this._projection.eventToUnprojection(event, _this._container.element, render, reference, transform);
40409 basicPoint: unprojection.basicPoint,
40410 latLon: unprojection.latLon,
40411 originalEvent: event,
40412 pixelPoint: unprojection.pixelPoint,
40413 target: _this._eventEmitter,
40417 .subscribe(function (event) {
40418 _this._eventEmitter.fire(event.type, event);
40421 Observer.prototype.stopEmit = function () {
40422 if (!this.started) {
40425 this._started = false;
40426 this._bearingSubscription.unsubscribe();
40427 this._currentNodeSubscription.unsubscribe();
40428 this._moveSubscription.unsubscribe();
40429 this._sequenceEdgesSubscription.unsubscribe();
40430 this._spatialEdgesSubscription.unsubscribe();
40431 this._viewerMouseEventSubscription.unsubscribe();
40432 this._bearingSubscription = null;
40433 this._currentNodeSubscription = null;
40434 this._moveSubscription = null;
40435 this._sequenceEdgesSubscription = null;
40436 this._spatialEdgesSubscription = null;
40437 this._viewerMouseEventSubscription = null;
40439 Observer.prototype.unproject$ = function (canvasPoint) {
40441 return Observable_1.Observable
40442 .combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.reference$, this._navigator.stateService.currentTransform$)
40444 .map(function (_a) {
40445 var render = _a[0], reference = _a[1], transform = _a[2];
40446 var unprojection = _this._projection.canvasToUnprojection(canvasPoint, _this._container.element, render, reference, transform);
40447 return unprojection.latLon;
40450 Observer.prototype.unprojectBasic$ = function (canvasPoint) {
40452 return Observable_1.Observable
40453 .combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
40455 .map(function (_a) {
40456 var render = _a[0], transform = _a[1];
40457 return _this._projection.canvasToBasic(canvasPoint, _this._container.element, render, transform);
40460 Observer.prototype._mapMouseEvent$ = function (type, mouseEvent$) {
40461 return mouseEvent$.map(function (event) {
40462 return [type, event];
40467 exports.Observer = Observer;
40468 exports.default = Observer;
40470 },{"../Viewer":237,"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":82}],361:[function(require,module,exports){
40472 /// <reference path="../../typings/index.d.ts" />
40473 Object.defineProperty(exports, "__esModule", { value: true });
40474 var THREE = require("three");
40475 var Geo_1 = require("../Geo");
40476 var Projection = (function () {
40477 function Projection(geoCoords, viewportCoords) {
40478 this._geoCoords = !!geoCoords ? geoCoords : new Geo_1.GeoCoords();
40479 this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
40481 Projection.prototype.basicToCanvas = function (basicPoint, container, render, transform) {
40482 return this._viewportCoords
40483 .basicToCanvas(basicPoint[0], basicPoint[1], container, transform, render.perspective);
40485 Projection.prototype.canvasToBasic = function (canvasPoint, container, render, transform) {
40486 var basicPoint = this._viewportCoords
40487 .canvasToBasic(canvasPoint[0], canvasPoint[1], container, transform, render.perspective);
40488 if (basicPoint[0] < 0 || basicPoint[0] > 1 || basicPoint[1] < 0 || basicPoint[1] > 1) {
40493 Projection.prototype.eventToUnprojection = function (event, container, render, reference, transform) {
40494 var pixelPoint = this._viewportCoords.canvasPosition(event, container);
40495 return this.canvasToUnprojection(pixelPoint, container, render, reference, transform);
40497 Projection.prototype.canvasToUnprojection = function (canvasPoint, container, render, reference, transform) {
40498 var canvasX = canvasPoint[0];
40499 var canvasY = canvasPoint[1];
40500 var _a = this._viewportCoords.canvasToViewport(canvasX, canvasY, container), viewportX = _a[0], viewportY = _a[1];
40501 var point3d = new THREE.Vector3(viewportX, viewportY, 1)
40502 .unproject(render.perspective);
40503 var basicPoint = transform.projectBasic(point3d.toArray());
40504 if (basicPoint[0] < 0 || basicPoint[0] > 1 || basicPoint[1] < 0 || basicPoint[1] > 1) {
40507 var direction3d = point3d.clone().sub(render.camera.position).normalize();
40508 var dist = -2 / direction3d.z;
40510 if (dist > 0 && dist < 100 && !!basicPoint) {
40511 var point = direction3d.clone().multiplyScalar(dist).add(render.camera.position);
40512 var latLonArray = this._geoCoords
40513 .enuToGeodetic(point.x, point.y, point.z, reference.lat, reference.lon, reference.alt)
40515 latLon = { lat: latLonArray[0], lon: latLonArray[1] };
40517 var unprojection = {
40518 basicPoint: basicPoint,
40520 pixelPoint: [canvasX, canvasY],
40522 return unprojection;
40526 exports.Projection = Projection;
40527 exports.default = Projection;
40529 },{"../Geo":229,"three":176}],362:[function(require,module,exports){
40531 /// <reference path="../../typings/index.d.ts" />
40532 Object.defineProperty(exports, "__esModule", { value: true });
40533 var THREE = require("three");
40534 var vd = require("virtual-dom");
40535 var Subject_1 = require("rxjs/Subject");
40536 require("rxjs/add/operator/publishReplay");
40537 require("rxjs/add/operator/scan");
40538 require("rxjs/add/operator/startWith");
40539 var Viewer_1 = require("../Viewer");
40540 var SpriteAtlas = (function () {
40541 function SpriteAtlas() {
40543 Object.defineProperty(SpriteAtlas.prototype, "json", {
40544 set: function (value) {
40545 this._json = value;
40550 Object.defineProperty(SpriteAtlas.prototype, "image", {
40551 set: function (value) {
40552 this._image = value;
40553 this._texture = new THREE.Texture(this._image);
40554 this._texture.minFilter = THREE.NearestFilter;
40559 Object.defineProperty(SpriteAtlas.prototype, "loaded", {
40561 return !!(this._image && this._json);
40566 SpriteAtlas.prototype.getGLSprite = function (name) {
40567 if (!this.loaded) {
40568 throw new Error("Sprites cannot be retrieved before the atlas is loaded.");
40570 var definition = this._json[name];
40572 console.warn("Sprite with key" + name + "does not exist in sprite definition.");
40573 return new THREE.Object3D();
40575 var texture = this._texture.clone();
40576 texture.needsUpdate = true;
40577 var width = this._image.width;
40578 var height = this._image.height;
40579 texture.offset.x = definition.x / width;
40580 texture.offset.y = (height - definition.y - definition.height) / height;
40581 texture.repeat.x = definition.width / width;
40582 texture.repeat.y = definition.height / height;
40583 var material = new THREE.SpriteMaterial({ map: texture });
40584 return new THREE.Sprite(material);
40586 SpriteAtlas.prototype.getDOMSprite = function (name, float) {
40587 if (!this.loaded) {
40588 throw new Error("Sprites cannot be retrieved before the atlas is loaded.");
40590 if (float == null) {
40591 float = Viewer_1.Alignment.Center;
40593 var definition = this._json[name];
40595 console.warn("Sprite with key" + name + "does not exist in sprite definition.");
40596 return vd.h("div", {}, []);
40598 var clipTop = definition.y;
40599 var clipRigth = definition.x + definition.width;
40600 var clipBottom = definition.y + definition.height;
40601 var clipLeft = definition.x;
40602 var left = -definition.x;
40603 var top = -definition.y;
40604 var height = this._image.height;
40605 var width = this._image.width;
40607 case Viewer_1.Alignment.Bottom:
40608 case Viewer_1.Alignment.Center:
40609 case Viewer_1.Alignment.Top:
40610 left -= definition.width / 2;
40612 case Viewer_1.Alignment.BottomLeft:
40613 case Viewer_1.Alignment.Left:
40614 case Viewer_1.Alignment.TopLeft:
40615 left -= definition.width;
40617 case Viewer_1.Alignment.BottomRight:
40618 case Viewer_1.Alignment.Right:
40619 case Viewer_1.Alignment.BottomRight:
40624 case Viewer_1.Alignment.Center:
40625 case Viewer_1.Alignment.Left:
40626 case Viewer_1.Alignment.Right:
40627 top -= definition.height / 2;
40629 case Viewer_1.Alignment.Top:
40630 case Viewer_1.Alignment.TopLeft:
40631 case Viewer_1.Alignment.TopRight:
40632 top -= definition.height;
40634 case Viewer_1.Alignment.Bottom:
40635 case Viewer_1.Alignment.BottomLeft:
40636 case Viewer_1.Alignment.BottomRight:
40640 var pixelRatioInverse = 1 / definition.pixelRatio;
40641 clipTop *= pixelRatioInverse;
40642 clipRigth *= pixelRatioInverse;
40643 clipBottom *= pixelRatioInverse;
40644 clipLeft *= pixelRatioInverse;
40645 left *= pixelRatioInverse;
40646 top *= pixelRatioInverse;
40647 height *= pixelRatioInverse;
40648 width *= pixelRatioInverse;
40650 src: this._image.src,
40652 clip: "rect(" + clipTop + "px, " + clipRigth + "px, " + clipBottom + "px, " + clipLeft + "px)",
40653 height: height + "px",
40655 position: "absolute",
40657 width: width + "px",
40660 return vd.h("img", properties, []);
40662 return SpriteAtlas;
40664 var SpriteService = (function () {
40665 function SpriteService(sprite) {
40667 this._retina = window.devicePixelRatio > 1;
40668 this._spriteAtlasOperation$ = new Subject_1.Subject();
40669 this._spriteAtlas$ = this._spriteAtlasOperation$
40670 .startWith(function (atlas) {
40673 .scan(function (atlas, operation) {
40674 return operation(atlas);
40675 }, new SpriteAtlas())
40678 this._spriteAtlas$.subscribe(function () { });
40679 if (sprite == null) {
40682 var format = this._retina ? "@2x" : "";
40683 var imageXmlHTTP = new XMLHttpRequest();
40684 imageXmlHTTP.open("GET", sprite + format + ".png", true);
40685 imageXmlHTTP.responseType = "arraybuffer";
40686 imageXmlHTTP.onload = function () {
40687 var image = new Image();
40688 image.onload = function () {
40689 _this._spriteAtlasOperation$.next(function (atlas) {
40690 atlas.image = image;
40694 var blob = new Blob([imageXmlHTTP.response]);
40695 image.src = window.URL.createObjectURL(blob);
40697 imageXmlHTTP.onerror = function (error) {
40698 console.error(new Error("Failed to fetch sprite sheet (" + sprite + format + ".png)"));
40700 imageXmlHTTP.send();
40701 var jsonXmlHTTP = new XMLHttpRequest();
40702 jsonXmlHTTP.open("GET", sprite + format + ".json", true);
40703 jsonXmlHTTP.responseType = "text";
40704 jsonXmlHTTP.onload = function () {
40705 var json = JSON.parse(jsonXmlHTTP.response);
40706 _this._spriteAtlasOperation$.next(function (atlas) {
40711 jsonXmlHTTP.onerror = function (error) {
40712 console.error(new Error("Failed to fetch sheet (" + sprite + format + ".json)"));
40714 jsonXmlHTTP.send();
40716 Object.defineProperty(SpriteService.prototype, "spriteAtlas$", {
40718 return this._spriteAtlas$;
40723 return SpriteService;
40725 exports.SpriteService = SpriteService;
40726 exports.default = SpriteService;
40728 },{"../Viewer":237,"rxjs/Subject":34,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":73,"rxjs/add/operator/startWith":78,"three":176,"virtual-dom":182}],363:[function(require,module,exports){
40730 Object.defineProperty(exports, "__esModule", { value: true });
40731 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
40732 var Observable_1 = require("rxjs/Observable");
40733 var Subject_1 = require("rxjs/Subject");
40734 require("rxjs/add/observable/timer");
40735 require("rxjs/add/operator/bufferWhen");
40736 require("rxjs/add/operator/filter");
40737 require("rxjs/add/operator/map");
40738 require("rxjs/add/operator/merge");
40739 require("rxjs/add/operator/scan");
40740 require("rxjs/add/operator/switchMap");
40741 var TouchService = (function () {
40742 function TouchService(canvasContainer, domContainer) {
40744 this._canvasContainer = canvasContainer;
40745 this._domContainer = domContainer;
40746 this._activeSubject$ = new BehaviorSubject_1.BehaviorSubject(false);
40747 this._active$ = this._activeSubject$
40748 .distinctUntilChanged()
40751 Observable_1.Observable.fromEvent(domContainer, "touchmove")
40752 .subscribe(function (event) {
40753 event.preventDefault();
40755 this._touchStart$ = Observable_1.Observable.fromEvent(canvasContainer, "touchstart");
40756 this._touchMove$ = Observable_1.Observable.fromEvent(canvasContainer, "touchmove");
40757 this._touchEnd$ = Observable_1.Observable.fromEvent(canvasContainer, "touchend");
40758 this._touchCancel$ = Observable_1.Observable.fromEvent(canvasContainer, "touchcancel");
40759 var tapStart$ = this._touchStart$
40760 .filter(function (te) {
40761 return te.touches.length === 1 && te.targetTouches.length === 1;
40764 this._doubleTap$ = tapStart$
40765 .bufferWhen(function () {
40768 .switchMap(function (event) {
40769 return Observable_1.Observable
40775 .filter(function (events) {
40776 return events.length === 2;
40778 .map(function (events) {
40779 return events[events.length - 1];
40783 .subscribe(function (event) {
40784 event.preventDefault();
40786 this._singleTouchMove$ = this._touchMove$
40787 .filter(function (te) {
40788 return te.touches.length === 1 && te.targetTouches.length === 1;
40791 var singleTouchStart$ = Observable_1.Observable
40792 .merge(this._touchStart$, this._touchEnd$, this._touchCancel$)
40793 .filter(function (te) {
40794 return te.touches.length === 1 && te.targetTouches.length === 1;
40796 var multipleTouchStart$ = Observable_1.Observable
40797 .merge(this._touchStart$, this._touchEnd$, this._touchCancel$)
40798 .filter(function (te) {
40799 return te.touches.length >= 1;
40801 var touchStop$ = Observable_1.Observable
40802 .merge(this._touchEnd$, this._touchCancel$)
40803 .filter(function (te) {
40804 return te.touches.length === 0;
40806 this._singleTouchDragStart$ = singleTouchStart$
40807 .mergeMap(function (e) {
40808 return _this._singleTouchMove$
40809 .takeUntil(Observable_1.Observable.merge(touchStop$, multipleTouchStart$))
40812 this._singleTouchDragEnd$ = singleTouchStart$
40813 .mergeMap(function (e) {
40814 return Observable_1.Observable
40815 .merge(touchStop$, multipleTouchStart$)
40818 this._singleTouchDrag$ = singleTouchStart$
40819 .switchMap(function (te) {
40820 return _this._singleTouchMove$
40822 .takeUntil(Observable_1.Observable
40823 .merge(multipleTouchStart$, touchStop$));
40825 var touchesChanged$ = Observable_1.Observable
40826 .merge(this._touchStart$, this._touchEnd$, this._touchCancel$);
40827 this._pinchStart$ = touchesChanged$
40828 .filter(function (te) {
40829 return te.touches.length === 2 && te.targetTouches.length === 2;
40831 this._pinchEnd$ = touchesChanged$
40832 .filter(function (te) {
40833 return te.touches.length !== 2 || te.targetTouches.length !== 2;
40835 this._pinchOperation$ = new Subject_1.Subject();
40836 this._pinch$ = this._pinchOperation$
40837 .scan(function (pinch, operation) {
40838 return operation(pinch);
40848 originalEvent: null,
40857 .filter(function (te) {
40858 return te.touches.length === 2 && te.targetTouches.length === 2;
40860 .map(function (te) {
40861 return function (previous) {
40862 var touch1 = te.touches[0];
40863 var touch2 = te.touches[1];
40864 var minX = Math.min(touch1.clientX, touch2.clientX);
40865 var maxX = Math.max(touch1.clientX, touch2.clientX);
40866 var minY = Math.min(touch1.clientY, touch2.clientY);
40867 var maxY = Math.max(touch1.clientY, touch2.clientY);
40868 var centerClientX = minX + (maxX - minX) / 2;
40869 var centerClientY = minY + (maxY - minY) / 2;
40870 var centerPageX = centerClientX + touch1.pageX - touch1.clientX;
40871 var centerPageY = centerClientY + touch1.pageY - touch1.clientY;
40872 var centerScreenX = centerClientX + touch1.screenX - touch1.clientX;
40873 var centerScreenY = centerClientY + touch1.screenY - touch1.clientY;
40874 var distanceX = Math.abs(touch1.clientX - touch2.clientX);
40875 var distanceY = Math.abs(touch1.clientY - touch2.clientY);
40876 var distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
40877 var distanceChange = distance - previous.distance;
40878 var changeX = distanceX - previous.distanceX;
40879 var changeY = distanceY - previous.distanceY;
40883 clientX: centerClientX,
40884 clientY: centerClientY,
40885 distance: distance,
40886 distanceChange: distanceChange,
40887 distanceX: distanceX,
40888 distanceY: distanceY,
40890 pageX: centerPageX,
40891 pageY: centerPageY,
40892 screenX: centerScreenX,
40893 screenY: centerScreenY,
40900 .subscribe(this._pinchOperation$);
40901 this._pinchChange$ = this._pinchStart$
40902 .switchMap(function (te) {
40903 return _this._pinch$
40905 .takeUntil(_this._pinchEnd$);
40908 Object.defineProperty(TouchService.prototype, "active$", {
40910 return this._active$;
40915 Object.defineProperty(TouchService.prototype, "activate$", {
40917 return this._activeSubject$;
40922 Object.defineProperty(TouchService.prototype, "doubleTap$", {
40924 return this._doubleTap$;
40929 Object.defineProperty(TouchService.prototype, "touchStart$", {
40931 return this._touchStart$;
40936 Object.defineProperty(TouchService.prototype, "touchMove$", {
40938 return this._touchMove$;
40943 Object.defineProperty(TouchService.prototype, "touchEnd$", {
40945 return this._touchEnd$;
40950 Object.defineProperty(TouchService.prototype, "touchCancel$", {
40952 return this._touchCancel$;
40957 Object.defineProperty(TouchService.prototype, "singleTouchDragStart$", {
40959 return this._singleTouchDragStart$;
40964 Object.defineProperty(TouchService.prototype, "singleTouchDrag$", {
40966 return this._singleTouchDrag$;
40971 Object.defineProperty(TouchService.prototype, "singleTouchDragEnd$", {
40973 return this._singleTouchDragEnd$;
40978 Object.defineProperty(TouchService.prototype, "pinch$", {
40980 return this._pinchChange$;
40985 Object.defineProperty(TouchService.prototype, "pinchStart$", {
40987 return this._pinchStart$;
40992 Object.defineProperty(TouchService.prototype, "pinchEnd$", {
40994 return this._pinchEnd$;
40999 return TouchService;
41001 exports.TouchService = TouchService;
41003 },{"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":73,"rxjs/add/operator/switchMap":79}],364:[function(require,module,exports){
41005 /// <reference path="../../typings/index.d.ts" />
41006 var __extends = (this && this.__extends) || (function () {
41007 var extendStatics = Object.setPrototypeOf ||
41008 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
41009 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
41010 return function (d, b) {
41011 extendStatics(d, b);
41012 function __() { this.constructor = d; }
41013 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
41016 Object.defineProperty(exports, "__esModule", { value: true });
41017 var when = require("when");
41018 var Observable_1 = require("rxjs/Observable");
41019 var Viewer_1 = require("../Viewer");
41020 var Utils_1 = require("../Utils");
41024 * @classdesc The Viewer object represents the navigable photo viewer.
41025 * Create a Viewer by specifying a container, client ID, photo key and
41026 * other options. The viewer exposes methods and events for programmatic
41029 * The viewer works with a few different coordinate systems.
41031 * Container pixel coordinates
41033 * Pixel coordinates are coordinates on the viewer container. The origin is
41034 * in the top left corner of the container. The axes are
41035 * directed according to the following for a viewer container with a width
41036 * of 640 pixels and height of 480 pixels.
41040 * +------------------------>
41045 * (0, 480) (640, 480)
41048 * Basic image coordinates
41050 * Basic image coordinates represents points in the original image adjusted for
41051 * orientation. They range from 0 to 1 on both axes. The origin is in the top left
41052 * corner of the image and the axes are directed
41053 * according to the following for all image types.
41057 * +------------------------>
41065 * For every camera viewing direction it is possible to convert between these
41066 * two coordinate systems for the current node. The image can be panned and
41067 * zoomed independently of the size of the viewer container resulting in
41068 * different conversion results for different viewing directions.
41070 var Viewer = (function (_super) {
41071 __extends(Viewer, _super);
41073 * Create a new viewer instance.
41075 * @param {string} id - Required `id` of a DOM element which will
41076 * be transformed into the viewer.
41077 * @param {string} clientId - Required `Mapillary API ClientID`. Can
41078 * be obtained from https://www.mapillary.com/app/settings/developers.
41079 * @param {string} [key] - Optional `photoId` to start from, can be any
41080 * Mapillary photo, if null no image is loaded.
41081 * @param {IViewerOptions} [options] - Optional configuration object
41082 * specifing Viewer's initial setup.
41083 * @param {string} [token] - Optional bearer token for API requests of
41084 * protected resources.
41088 * var viewer = new Mapillary.Viewer("<element-id>", "<client-id>", "<my key>");
41091 function Viewer(id, clientId, key, options, token) {
41092 var _this = _super.call(this) || this;
41093 options = options != null ? options : {};
41094 Utils_1.Settings.setOptions(options);
41095 _this._navigator = new Viewer_1.Navigator(clientId, token);
41096 _this._container = new Viewer_1.Container(id, _this._navigator.stateService, options);
41097 _this._observer = new Viewer_1.Observer(_this, _this._navigator, _this._container);
41098 _this._componentController = new Viewer_1.ComponentController(_this._container, _this._navigator, _this._observer, key, options.component);
41101 Object.defineProperty(Viewer.prototype, "isNavigable", {
41103 * Return a boolean indicating if the viewer is in a navigable state.
41105 * @description The navigable state indicates if the viewer supports
41106 * moving, i.e. calling the `moveToKey`, `moveDir` and `moveCloseTo`
41107 * methods. The viewer will not be in a navigable state if the cover
41108 * is activated and the viewer has been supplied a key. When the cover
41109 * is deactivated or activated without being supplied a key it will
41113 * @returns {boolean} Boolean indicating whether the viewer is navigable.
41116 return this._componentController.navigable;
41122 * Activate a component.
41124 * @param {string} name - Name of the component which will become active.
41128 * viewer.activateComponent("marker");
41131 Viewer.prototype.activateComponent = function (name) {
41132 this._componentController.activate(name);
41135 * Activate the cover (deactivates all other components).
41137 Viewer.prototype.activateCover = function () {
41138 this._componentController.activateCover();
41141 * Deactivate a component.
41143 * @param {string} name - Name of component which become inactive.
41147 * viewer.deactivateComponent("mouse");
41150 Viewer.prototype.deactivateComponent = function (name) {
41151 this._componentController.deactivate(name);
41154 * Deactivate the cover (activates all components marked as active).
41156 Viewer.prototype.deactivateCover = function () {
41157 this._componentController.deactivateCover();
41160 * Get the bearing of the current viewer camera.
41162 * @description The bearing depends on how the camera
41163 * is currently rotated and does not correspond
41164 * to the compass angle of the current node if the view
41167 * Bearing is measured in degrees clockwise with respect to
41170 * @returns {Promise<number>} Promise to the bearing
41171 * of the current viewer camera.
41175 * viewer.getBearing().then((b) => { console.log(b); });
41178 Viewer.prototype.getBearing = function () {
41180 return when.promise(function (resolve, reject) {
41181 _this._container.renderService.bearing$
41183 .subscribe(function (bearing) {
41185 }, function (error) {
41191 * Get the basic coordinates of the current photo that is
41192 * at the center of the viewport.
41194 * @description Basic coordinates are 2D coordinates on the [0, 1] interval
41195 * and have the origin point, (0, 0), at the top left corner and the
41196 * maximum value, (1, 1), at the bottom right corner of the original
41199 * @returns {Promise<number[]>} Promise to the basic coordinates
41200 * of the current photo at the center for the viewport.
41204 * viewer.getCenter().then((c) => { console.log(c); });
41207 Viewer.prototype.getCenter = function () {
41209 return when.promise(function (resolve, reject) {
41210 _this._navigator.stateService.getCenter()
41211 .subscribe(function (center) {
41213 }, function (error) {
41221 * @param {string} name - Name of component.
41222 * @returns {Component} The requested component.
41226 * var mouseComponent = viewer.getComponent("mouse");
41229 Viewer.prototype.getComponent = function (name) {
41230 return this._componentController.get(name);
41233 * Returns the viewer's containing HTML element.
41235 * @returns {HTMLElement} The viewer's container.
41237 Viewer.prototype.getContainer = function () {
41238 return this._container.element;
41241 * Get the photo's current zoom level.
41243 * @returns {Promise<number>} Promise to the viewers's current
41248 * viewer.getZoom().then((z) => { console.log(z); });
41251 Viewer.prototype.getZoom = function () {
41253 return when.promise(function (resolve, reject) {
41254 _this._navigator.stateService.getZoom()
41255 .subscribe(function (zoom) {
41257 }, function (error) {
41263 * Move close to given latitude and longitude.
41265 * @description Because the method propagates IO errors, these potential errors
41266 * need to be handled by the method caller (see example).
41268 * @param {Number} lat - Latitude, in degrees.
41269 * @param {Number} lon - Longitude, in degrees.
41270 * @returns {Promise<Node>} Promise to the node that was navigated to.
41271 * @throws {Error} If no nodes exist close to provided latitude
41273 * @throws {Error} Propagates any IO errors to the caller.
41274 * @throws {Error} When viewer is not navigable.
41278 * viewer.moveCloseTo(0, 0).then(
41279 * (n) => { console.log(n); },
41280 * (e) => { console.error(e); });
41283 Viewer.prototype.moveCloseTo = function (lat, lon) {
41284 var moveCloseTo$ = this.isNavigable ?
41285 this._navigator.moveCloseTo$(lat, lon) :
41286 Observable_1.Observable.throw(new Error("Calling moveCloseTo is not supported when viewer is not navigable."));
41287 return when.promise(function (resolve, reject) {
41288 moveCloseTo$.subscribe(function (node) {
41290 }, function (error) {
41296 * Navigate in a given direction.
41298 * @description This method has to be called through EdgeDirection enumeration as in the example.
41300 * @param {EdgeDirection} dir - Direction in which which to move.
41301 * @returns {Promise<Node>} Promise to the node that was navigated to.
41302 * @throws {Error} If the current node does not have the edge direction
41303 * or the edges has not yet been cached.
41304 * @throws {Error} Propagates any IO errors to the caller.
41305 * @throws {Error} When viewer is not navigable.
41309 * viewer.moveDir(Mapillary.EdgeDirection.Next).then(
41310 * (n) => { console.log(n); },
41311 * (e) => { console.error(e); });
41314 Viewer.prototype.moveDir = function (dir) {
41315 var moveDir$ = this.isNavigable ?
41316 this._navigator.moveDir$(dir) :
41317 Observable_1.Observable.throw(new Error("Calling moveDir is not supported when viewer is not navigable."));
41318 return when.promise(function (resolve, reject) {
41319 moveDir$.subscribe(function (node) {
41321 }, function (error) {
41327 * Navigate to a given photo key.
41329 * @param {string} key - A valid Mapillary photo key.
41330 * @returns {Promise<Node>} Promise to the node that was navigated to.
41331 * @throws {Error} Propagates any IO errors to the caller.
41332 * @throws {Error} When viewer is not navigable.
41336 * viewer.moveToKey("<my key>").then(
41337 * (n) => { console.log(n); },
41338 * (e) => { console.error(e); });
41341 Viewer.prototype.moveToKey = function (key) {
41342 var moveToKey$ = this.isNavigable ?
41343 this._navigator.moveToKey$(key) :
41344 Observable_1.Observable.throw(new Error("Calling moveToKey is not supported when viewer is not navigable."));
41345 return when.promise(function (resolve, reject) {
41346 moveToKey$.subscribe(function (node) {
41348 }, function (error) {
41354 * Project basic image coordinates for the current node to canvas pixel
41357 * @description The basic image coordinates may not always correspond to a
41358 * pixel point that lies in the visible area of the viewer container.
41360 * @param {Array<number>} basicPoint - Basic images coordinates to project.
41361 * @returns {Promise<ILatLon>} Promise to the pixel coordinates corresponding
41362 * to the basic image point.
41366 * viewer.projectFromBasic([0.3, 0.7])
41367 * .then((pixelPoint) => { console.log(pixelPoint); });
41370 Viewer.prototype.projectFromBasic = function (basicPoint) {
41372 return when.promise(function (resolve, reject) {
41373 _this._observer.projectBasic$(basicPoint)
41374 .subscribe(function (pixelPoint) {
41375 resolve(pixelPoint);
41376 }, function (error) {
41382 * Detect the viewer's new width and height and resize it.
41384 * @description The components will also detect the viewer's
41385 * new size and resize their rendered elements if needed.
41392 Viewer.prototype.resize = function () {
41393 this._container.renderService.resize$.next(null);
41394 this._componentController.resize();
41397 * Set a bearer token for authenticated API requests of
41398 * protected resources.
41400 * @description When the supplied token is null or undefined,
41401 * any previously set bearer token will be cleared and the
41402 * viewer will make unauthenticated requests.
41404 * Calling setAuthToken aborts all outstanding move requests.
41405 * The promises of those move requests will be rejected and
41406 * the rejections need to be caught.
41408 * @param {string} [token] token - Bearer token.
41409 * @returns {Promise<void>} Promise that resolves after token
41412 * @throws {Error} When viewer is not navigable.
41416 * viewer.setAuthToken("<my token>")
41417 * .then(() => { console.log("token set"); });
41420 Viewer.prototype.setAuthToken = function (token) {
41421 var setToken$ = this.isNavigable ?
41422 this._navigator.setToken$(token) :
41423 Observable_1.Observable.throw(new Error("Calling setAuthToken is not supported when viewer is not navigable."));
41424 return when.promise(function (resolve, reject) {
41426 .subscribe(function () {
41427 resolve(undefined);
41428 }, function (error) {
41434 * Set the basic coordinates of the current photo to be in the
41435 * center of the viewport.
41437 * @description Basic coordinates are 2D coordinates on the [0, 1] interval
41438 * and has the origin point, (0, 0), at the top left corner and the
41439 * maximum value, (1, 1), at the bottom right corner of the original
41442 * @param {number[]} The basic coordinates of the current
41443 * photo to be at the center for the viewport.
41447 * viewer.setCenter([0.5, 0.5]);
41450 Viewer.prototype.setCenter = function (center) {
41451 this._navigator.stateService.setCenter(center);
41454 * Set the filter selecting nodes to use when calculating
41455 * the spatial edges.
41457 * @description The following filter types are supported:
41461 * `["==", key, value]` equality: `node[key] = value`
41463 * `["!=", key, value]` inequality: `node[key] ≠ value`
41465 * `["<", key, value]` less than: `node[key] < value`
41467 * `["<=", key, value]` less than or equal: `node[key] ≤ value`
41469 * `[">", key, value]` greater than: `node[key] > value`
41471 * `[">=", key, value]` greater than or equal: `node[key] ≥ value`
41475 * `["in", key, v0, ..., vn]` set inclusion: `node[key] ∈ {v0, ..., vn}`
41477 * `["!in", key, v0, ..., vn]` set exclusion: `node[key] ∉ {v0, ..., vn}`
41481 * `["all", f0, ..., fn]` logical `AND`: `f0 ∧ ... ∧ fn`
41483 * A key must be a string that identifies a node property name. A value must be
41484 * a string, number, or boolean. Strictly-typed comparisons are used. The values
41485 * `f0, ..., fn` of the combining filter must be filter expressions.
41487 * Clear the filter by setting it to null or empty array.
41489 * @param {FilterExpression} filter - The filter expression.
41490 * @returns {Promise<void>} Promise that resolves after filter is applied.
41494 * viewer.setFilter(["==", "sequenceKey", "<my sequence key>"]);
41497 Viewer.prototype.setFilter = function (filter) {
41499 return when.promise(function (resolve, reject) {
41500 _this._navigator.setFilter$(filter)
41501 .subscribe(function () {
41502 resolve(undefined);
41503 }, function (error) {
41509 * Set the viewer's render mode.
41511 * @param {RenderMode} renderMode - Render mode.
41515 * viewer.setRenderMode(Mapillary.RenderMode.Letterbox);
41518 Viewer.prototype.setRenderMode = function (renderMode) {
41519 this._container.renderService.renderMode$.next(renderMode);
41522 * Set the photo's current zoom level.
41524 * @description Possible zoom level values are on the [0, 3] interval.
41525 * Zero means zooming out to fit the photo to the view whereas three
41526 * shows the highest level of detail.
41528 * @param {number} The photo's current zoom level.
41532 * viewer.setZoom(2);
41535 Viewer.prototype.setZoom = function (zoom) {
41536 this._navigator.stateService.setZoom(zoom);
41539 * Unproject canvas pixel coordinates to an ILatLon representing geographical
41542 * @description The pixel point may not always correspond to geographical
41543 * coordinates. In the case of no correspondence the returned value will
41546 * @param {Array<number>} pixelPoint - Pixel coordinates to unproject.
41547 * @returns {Promise<ILatLon>} Promise to the latLon corresponding to the pixel point.
41551 * viewer.unproject([100, 100])
41552 * .then((latLon) => { console.log(latLon); });
41555 Viewer.prototype.unproject = function (pixelPoint) {
41557 return when.promise(function (resolve, reject) {
41558 _this._observer.unproject$(pixelPoint)
41559 .subscribe(function (latLon) {
41561 }, function (error) {
41567 * Unproject canvas pixel coordinates to basic image coordinates for the
41570 * @description The pixel point may not always correspond to basic image
41571 * coordinates. In the case of no correspondence the returned value will
41574 * @param {Array<number>} pixelPoint - Pixel coordinates to unproject.
41575 * @returns {Promise<ILatLon>} Promise to the basic coordinates corresponding
41576 * to the pixel point.
41580 * viewer.unprojectToBasic([100, 100])
41581 * .then((basicPoint) => { console.log(basicPoint); });
41584 Viewer.prototype.unprojectToBasic = function (pixelPoint) {
41586 return when.promise(function (resolve, reject) {
41587 _this._observer.unprojectBasic$(pixelPoint)
41588 .subscribe(function (basicPoint) {
41589 resolve(basicPoint);
41590 }, function (error) {
41596 * Fired when the viewing direction of the camera changes.
41598 * @type {number} bearing - Value indicating the current bearing
41599 * measured in degrees clockwise with respect to north.
41601 Viewer.bearingchanged = "bearingchanged";
41603 * Fired when a pointing device (usually a mouse) is pressed and released at
41604 * the same point in the viewer.
41606 * @type {IViewerMouseEvent} event - Viewer mouse event data.
41608 Viewer.click = "click";
41610 * Fired when the right button of the mouse is clicked within the viewer.
41612 * @type {IViewerMouseEvent} event - Viewer mouse event data.
41614 Viewer.contextmenu = "contextmenu";
41616 * Fired when a pointing device (usually a mouse) is clicked twice at
41617 * the same point in the viewer.
41619 * @type {IViewerMouseEvent} event - Viewer mouse event data.
41621 Viewer.dblclick = "dblclick";
41623 * Fired when the viewer is loading more data.
41625 * @type {boolean} loading - Boolean indicating whether the viewer is loading.
41627 Viewer.loadingchanged = "loadingchanged";
41629 * Fired when a pointing device (usually a mouse) is pressed within the viewer.
41631 * @type {IViewerMouseEvent} event - Viewer mouse event data.
41633 Viewer.mousedown = "mousedown";
41635 * Fired when a pointing device (usually a mouse) is moved within the viewer.
41636 * @description Will not fire when the mouse is actively used, e.g. for drag pan.
41638 * @type {IViewerMouseEvent} event - Viewer mouse event data.
41640 Viewer.mousemove = "mousemove";
41642 * Fired when a pointing device (usually a mouse) leaves the viewer's canvas.
41644 * @type {IViewerMouseEvent} event - Viewer mouse event data.
41646 Viewer.mouseout = "mouseout";
41648 * Fired when a pointing device (usually a mouse) is moved onto the viewer's canvas.
41650 * @type {IViewerMouseEvent} event - Viewer mouse event data.
41652 Viewer.mouseover = "mouseover";
41654 * Fired when a pointing device (usually a mouse) is released within the viewer.
41656 * @type {IViewerMouseEvent} event - Viewer mouse event data.
41658 Viewer.mouseup = "mouseup";
41660 * Fired when the viewer motion stops and it is in a fixed
41661 * position with a fixed point of view.
41664 Viewer.moveend = "moveend";
41666 * Fired when the motion from one view to another start,
41667 * either by changing the position (e.g. when changing node) or
41668 * when changing point of view (e.g. by interaction such as pan and zoom).
41671 Viewer.movestart = "movestart";
41673 * Fired when the navigable state of the viewer changes.
41675 * @description The navigable state indicates if the viewer supports
41676 * moving, i.e. calling the `moveToKey`, `moveDir` and `moveCloseTo`
41677 * methods. The viewer will not be in a navigable state if the cover
41678 * is activated and the viewer has been supplied a key. When the cover
41679 * is deactivated or activated without being supplied a key it will
41683 * @type {boolean} navigable - Boolean indicating whether the viewer is navigable.
41685 Viewer.navigablechanged = "navigablechanged";
41687 * Fired every time the viewer navigates to a new node.
41689 * @type {Node} node - Current node.
41691 Viewer.nodechanged = "nodechanged";
41693 * Fired every time the sequence edges of the current node changes.
41695 * @type {IEdgeStatus} status - The edge status object.
41697 Viewer.sequenceedgeschanged = "sequenceedgeschanged";
41699 * Fired every time the spatial edges of the current node changes.
41701 * @type {IEdgeStatus} status - The edge status object.
41703 Viewer.spatialedgeschanged = "spatialedgeschanged";
41705 }(Utils_1.EventEmitter));
41706 exports.Viewer = Viewer;
41708 },{"../Utils":236,"../Viewer":237,"rxjs/Observable":29,"when":223}]},{},[231])(231)
41710 //# sourceMappingURL=mapillary.js.map