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":237,"./api/ModelCreator":238}],226:[function(require,module,exports){
19907 Object.defineProperty(exports, "__esModule", { value: true });
19908 var Component_1 = require("./component/Component");
19909 exports.Component = Component_1.Component;
19910 var ComponentService_1 = require("./component/ComponentService");
19911 exports.ComponentService = ComponentService_1.ComponentService;
19912 var AttributionComponent_1 = require("./component/AttributionComponent");
19913 exports.AttributionComponent = AttributionComponent_1.AttributionComponent;
19914 var BackgroundComponent_1 = require("./component/BackgroundComponent");
19915 exports.BackgroundComponent = BackgroundComponent_1.BackgroundComponent;
19916 var BearingComponent_1 = require("./component/BearingComponent");
19917 exports.BearingComponent = BearingComponent_1.BearingComponent;
19918 var CacheComponent_1 = require("./component/CacheComponent");
19919 exports.CacheComponent = CacheComponent_1.CacheComponent;
19920 var CoverComponent_1 = require("./component/CoverComponent");
19921 exports.CoverComponent = CoverComponent_1.CoverComponent;
19922 var DebugComponent_1 = require("./component/DebugComponent");
19923 exports.DebugComponent = DebugComponent_1.DebugComponent;
19924 var DirectionComponent_1 = require("./component/direction/DirectionComponent");
19925 exports.DirectionComponent = DirectionComponent_1.DirectionComponent;
19926 var DirectionDOMCalculator_1 = require("./component/direction/DirectionDOMCalculator");
19927 exports.DirectionDOMCalculator = DirectionDOMCalculator_1.DirectionDOMCalculator;
19928 var DirectionDOMRenderer_1 = require("./component/direction/DirectionDOMRenderer");
19929 exports.DirectionDOMRenderer = DirectionDOMRenderer_1.DirectionDOMRenderer;
19930 var ImageComponent_1 = require("./component/ImageComponent");
19931 exports.ImageComponent = ImageComponent_1.ImageComponent;
19932 var KeyboardComponent_1 = require("./component/KeyboardComponent");
19933 exports.KeyboardComponent = KeyboardComponent_1.KeyboardComponent;
19934 var LoadingComponent_1 = require("./component/LoadingComponent");
19935 exports.LoadingComponent = LoadingComponent_1.LoadingComponent;
19936 var Marker_1 = require("./component/marker/marker/Marker");
19937 exports.Marker = Marker_1.Marker;
19938 var MarkerComponent_1 = require("./component/marker/MarkerComponent");
19939 exports.MarkerComponent = MarkerComponent_1.MarkerComponent;
19940 var MarkerScene_1 = require("./component/marker/MarkerScene");
19941 exports.MarkerScene = MarkerScene_1.MarkerScene;
19942 var MarkerSet_1 = require("./component/marker/MarkerSet");
19943 exports.MarkerSet = MarkerSet_1.MarkerSet;
19944 var MouseComponent_1 = require("./component/mouse/MouseComponent");
19945 exports.MouseComponent = MouseComponent_1.MouseComponent;
19946 var MouseHandlerBase_1 = require("./component/mouse/MouseHandlerBase");
19947 exports.MouseHandlerBase = MouseHandlerBase_1.MouseHandlerBase;
19948 var BounceHandler_1 = require("./component/mouse/BounceHandler");
19949 exports.BounceHandler = BounceHandler_1.BounceHandler;
19950 var DragPanHandler_1 = require("./component/mouse/DragPanHandler");
19951 exports.DragPanHandler = DragPanHandler_1.DragPanHandler;
19952 var DoubleClickZoomHandler_1 = require("./component/mouse/DoubleClickZoomHandler");
19953 exports.DoubleClickZoomHandler = DoubleClickZoomHandler_1.DoubleClickZoomHandler;
19954 var ScrollZoomHandler_1 = require("./component/mouse/ScrollZoomHandler");
19955 exports.ScrollZoomHandler = ScrollZoomHandler_1.ScrollZoomHandler;
19956 var TouchZoomHandler_1 = require("./component/mouse/TouchZoomHandler");
19957 exports.TouchZoomHandler = TouchZoomHandler_1.TouchZoomHandler;
19958 var Popup_1 = require("./component/popup/popup/Popup");
19959 exports.Popup = Popup_1.Popup;
19960 var PopupComponent_1 = require("./component/popup/PopupComponent");
19961 exports.PopupComponent = PopupComponent_1.PopupComponent;
19962 var NavigationComponent_1 = require("./component/NavigationComponent");
19963 exports.NavigationComponent = NavigationComponent_1.NavigationComponent;
19964 var RouteComponent_1 = require("./component/RouteComponent");
19965 exports.RouteComponent = RouteComponent_1.RouteComponent;
19966 var SequenceComponent_1 = require("./component/sequence/SequenceComponent");
19967 exports.SequenceComponent = SequenceComponent_1.SequenceComponent;
19968 var SequenceDOMRenderer_1 = require("./component/sequence/SequenceDOMRenderer");
19969 exports.SequenceDOMRenderer = SequenceDOMRenderer_1.SequenceDOMRenderer;
19970 var SequenceDOMInteraction_1 = require("./component/sequence/SequenceDOMInteraction");
19971 exports.SequenceDOMInteraction = SequenceDOMInteraction_1.SequenceDOMInteraction;
19972 var ImagePlaneComponent_1 = require("./component/imageplane/ImagePlaneComponent");
19973 exports.ImagePlaneComponent = ImagePlaneComponent_1.ImagePlaneComponent;
19974 var ImagePlaneFactory_1 = require("./component/imageplane/ImagePlaneFactory");
19975 exports.ImagePlaneFactory = ImagePlaneFactory_1.ImagePlaneFactory;
19976 var ImagePlaneGLRenderer_1 = require("./component/imageplane/ImagePlaneGLRenderer");
19977 exports.ImagePlaneGLRenderer = ImagePlaneGLRenderer_1.ImagePlaneGLRenderer;
19978 var ImagePlaneScene_1 = require("./component/imageplane/ImagePlaneScene");
19979 exports.ImagePlaneScene = ImagePlaneScene_1.ImagePlaneScene;
19980 var ImagePlaneShaders_1 = require("./component/imageplane/ImagePlaneShaders");
19981 exports.ImagePlaneShaders = ImagePlaneShaders_1.ImagePlaneShaders;
19982 var SimpleMarker_1 = require("./component/marker/marker/SimpleMarker");
19983 exports.SimpleMarker = SimpleMarker_1.SimpleMarker;
19984 var CircleMarker_1 = require("./component/marker/marker/CircleMarker");
19985 exports.CircleMarker = CircleMarker_1.CircleMarker;
19986 var SliderComponent_1 = require("./component/imageplane/SliderComponent");
19987 exports.SliderComponent = SliderComponent_1.SliderComponent;
19988 var StatsComponent_1 = require("./component/StatsComponent");
19989 exports.StatsComponent = StatsComponent_1.StatsComponent;
19990 var Tag_1 = require("./component/tag/tag/Tag");
19991 exports.Tag = Tag_1.Tag;
19992 var OutlineTag_1 = require("./component/tag/tag/OutlineTag");
19993 exports.OutlineTag = OutlineTag_1.OutlineTag;
19994 var RenderTag_1 = require("./component/tag/tag/RenderTag");
19995 exports.RenderTag = RenderTag_1.RenderTag;
19996 var OutlineRenderTag_1 = require("./component/tag/tag/OutlineRenderTag");
19997 exports.OutlineRenderTag = OutlineRenderTag_1.OutlineRenderTag;
19998 var OutlineCreateTag_1 = require("./component/tag/tag/OutlineCreateTag");
19999 exports.OutlineCreateTag = OutlineCreateTag_1.OutlineCreateTag;
20000 var SpotTag_1 = require("./component/tag/tag/SpotTag");
20001 exports.SpotTag = SpotTag_1.SpotTag;
20002 var SpotRenderTag_1 = require("./component/tag/tag/SpotRenderTag");
20003 exports.SpotRenderTag = SpotRenderTag_1.SpotRenderTag;
20004 var TagComponent_1 = require("./component/tag/TagComponent");
20005 exports.TagComponent = TagComponent_1.TagComponent;
20006 var TagCreator_1 = require("./component/tag/TagCreator");
20007 exports.TagCreator = TagCreator_1.TagCreator;
20008 var TagDOMRenderer_1 = require("./component/tag/TagDOMRenderer");
20009 exports.TagDOMRenderer = TagDOMRenderer_1.TagDOMRenderer;
20010 var TagMode_1 = require("./component/tag/TagMode");
20011 exports.TagMode = TagMode_1.TagMode;
20012 var TagOperation_1 = require("./component/tag/TagOperation");
20013 exports.TagOperation = TagOperation_1.TagOperation;
20014 var TagScene_1 = require("./component/tag/TagScene");
20015 exports.TagScene = TagScene_1.TagScene;
20016 var TagSet_1 = require("./component/tag/TagSet");
20017 exports.TagSet = TagSet_1.TagSet;
20018 var Geometry_1 = require("./component/tag/geometry/Geometry");
20019 exports.Geometry = Geometry_1.Geometry;
20020 var VertexGeometry_1 = require("./component/tag/geometry/VertexGeometry");
20021 exports.VertexGeometry = VertexGeometry_1.VertexGeometry;
20022 var RectGeometry_1 = require("./component/tag/geometry/RectGeometry");
20023 exports.RectGeometry = RectGeometry_1.RectGeometry;
20024 var PointGeometry_1 = require("./component/tag/geometry/PointGeometry");
20025 exports.PointGeometry = PointGeometry_1.PointGeometry;
20026 var PolygonGeometry_1 = require("./component/tag/geometry/PolygonGeometry");
20027 exports.PolygonGeometry = PolygonGeometry_1.PolygonGeometry;
20028 var GeometryTagError_1 = require("./component/tag/error/GeometryTagError");
20029 exports.GeometryTagError = GeometryTagError_1.GeometryTagError;
20031 },{"./component/AttributionComponent":239,"./component/BackgroundComponent":240,"./component/BearingComponent":241,"./component/CacheComponent":242,"./component/Component":243,"./component/ComponentService":244,"./component/CoverComponent":245,"./component/DebugComponent":246,"./component/ImageComponent":247,"./component/KeyboardComponent":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/marker/MarkerComponent":263,"./component/marker/MarkerScene":264,"./component/marker/MarkerSet":265,"./component/marker/marker/CircleMarker":266,"./component/marker/marker/Marker":267,"./component/marker/marker/SimpleMarker":268,"./component/mouse/BounceHandler":269,"./component/mouse/DoubleClickZoomHandler":270,"./component/mouse/DragPanHandler":271,"./component/mouse/MouseComponent":272,"./component/mouse/MouseHandlerBase":273,"./component/mouse/ScrollZoomHandler":274,"./component/mouse/TouchZoomHandler":275,"./component/popup/PopupComponent":277,"./component/popup/popup/Popup":278,"./component/sequence/SequenceComponent":279,"./component/sequence/SequenceDOMInteraction":280,"./component/sequence/SequenceDOMRenderer":281,"./component/tag/TagComponent":283,"./component/tag/TagCreator":284,"./component/tag/TagDOMRenderer":285,"./component/tag/TagMode":286,"./component/tag/TagOperation":287,"./component/tag/TagScene":288,"./component/tag/TagSet":289,"./component/tag/error/GeometryTagError":290,"./component/tag/geometry/Geometry":291,"./component/tag/geometry/PointGeometry":292,"./component/tag/geometry/PolygonGeometry":293,"./component/tag/geometry/RectGeometry":294,"./component/tag/geometry/VertexGeometry":295,"./component/tag/tag/OutlineCreateTag":296,"./component/tag/tag/OutlineRenderTag":297,"./component/tag/tag/OutlineTag":298,"./component/tag/tag/RenderTag":299,"./component/tag/tag/SpotRenderTag":300,"./component/tag/tag/SpotTag":301,"./component/tag/tag/Tag":302}],227:[function(require,module,exports){
20033 Object.defineProperty(exports, "__esModule", { value: true });
20034 var EdgeDirection_1 = require("./graph/edge/EdgeDirection");
20035 exports.EdgeDirection = EdgeDirection_1.EdgeDirection;
20036 var EdgeCalculatorSettings_1 = require("./graph/edge/EdgeCalculatorSettings");
20037 exports.EdgeCalculatorSettings = EdgeCalculatorSettings_1.EdgeCalculatorSettings;
20038 var EdgeCalculatorDirections_1 = require("./graph/edge/EdgeCalculatorDirections");
20039 exports.EdgeCalculatorDirections = EdgeCalculatorDirections_1.EdgeCalculatorDirections;
20040 var EdgeCalculatorCoefficients_1 = require("./graph/edge/EdgeCalculatorCoefficients");
20041 exports.EdgeCalculatorCoefficients = EdgeCalculatorCoefficients_1.EdgeCalculatorCoefficients;
20042 var EdgeCalculator_1 = require("./graph/edge/EdgeCalculator");
20043 exports.EdgeCalculator = EdgeCalculator_1.EdgeCalculator;
20045 },{"./graph/edge/EdgeCalculator":320,"./graph/edge/EdgeCalculatorCoefficients":321,"./graph/edge/EdgeCalculatorDirections":322,"./graph/edge/EdgeCalculatorSettings":323,"./graph/edge/EdgeDirection":324}],228:[function(require,module,exports){
20047 Object.defineProperty(exports, "__esModule", { value: true });
20048 var ArgumentMapillaryError_1 = require("./error/ArgumentMapillaryError");
20049 exports.ArgumentMapillaryError = ArgumentMapillaryError_1.ArgumentMapillaryError;
20050 var GraphMapillaryError_1 = require("./error/GraphMapillaryError");
20051 exports.GraphMapillaryError = GraphMapillaryError_1.GraphMapillaryError;
20052 var MapillaryError_1 = require("./error/MapillaryError");
20053 exports.MapillaryError = MapillaryError_1.MapillaryError;
20055 },{"./error/ArgumentMapillaryError":303,"./error/GraphMapillaryError":304,"./error/MapillaryError":305}],229:[function(require,module,exports){
20057 Object.defineProperty(exports, "__esModule", { value: true });
20058 var Camera_1 = require("./geo/Camera");
20059 exports.Camera = Camera_1.Camera;
20060 var GeoCoords_1 = require("./geo/GeoCoords");
20061 exports.GeoCoords = GeoCoords_1.GeoCoords;
20062 var ViewportCoords_1 = require("./geo/ViewportCoords");
20063 exports.ViewportCoords = ViewportCoords_1.ViewportCoords;
20064 var Spatial_1 = require("./geo/Spatial");
20065 exports.Spatial = Spatial_1.Spatial;
20066 var Transform_1 = require("./geo/Transform");
20067 exports.Transform = Transform_1.Transform;
20069 },{"./geo/Camera":306,"./geo/GeoCoords":307,"./geo/Spatial":308,"./geo/Transform":309,"./geo/ViewportCoords":310}],230:[function(require,module,exports){
20071 Object.defineProperty(exports, "__esModule", { value: true });
20072 var FilterCreator_1 = require("./graph/FilterCreator");
20073 exports.FilterCreator = FilterCreator_1.FilterCreator;
20074 var Graph_1 = require("./graph/Graph");
20075 exports.Graph = Graph_1.Graph;
20076 var GraphCalculator_1 = require("./graph/GraphCalculator");
20077 exports.GraphCalculator = GraphCalculator_1.GraphCalculator;
20078 var GraphService_1 = require("./graph/GraphService");
20079 exports.GraphService = GraphService_1.GraphService;
20080 var ImageLoadingService_1 = require("./graph/ImageLoadingService");
20081 exports.ImageLoadingService = ImageLoadingService_1.ImageLoadingService;
20082 var MeshReader_1 = require("./graph/MeshReader");
20083 exports.MeshReader = MeshReader_1.MeshReader;
20084 var Node_1 = require("./graph/Node");
20085 exports.Node = Node_1.Node;
20086 var NodeCache_1 = require("./graph/NodeCache");
20087 exports.NodeCache = NodeCache_1.NodeCache;
20088 var Sequence_1 = require("./graph/Sequence");
20089 exports.Sequence = Sequence_1.Sequence;
20091 },{"./graph/FilterCreator":311,"./graph/Graph":312,"./graph/GraphCalculator":313,"./graph/GraphService":314,"./graph/ImageLoadingService":315,"./graph/MeshReader":316,"./graph/Node":317,"./graph/NodeCache":318,"./graph/Sequence":319}],231:[function(require,module,exports){
20094 * MapillaryJS is a WebGL JavaScript library for exploring street level imagery
20097 Object.defineProperty(exports, "__esModule", { value: true });
20098 var Edge_1 = require("./Edge");
20099 exports.EdgeDirection = Edge_1.EdgeDirection;
20100 var Render_1 = require("./Render");
20101 exports.RenderMode = Render_1.RenderMode;
20102 var Viewer_1 = require("./Viewer");
20103 exports.Alignment = Viewer_1.Alignment;
20104 exports.ImageSize = Viewer_1.ImageSize;
20105 exports.Viewer = Viewer_1.Viewer;
20106 var TagComponent = require("./component/tag/Tag");
20107 exports.TagComponent = TagComponent;
20108 var MarkerComponent = require("./component/marker/Marker");
20109 exports.MarkerComponent = MarkerComponent;
20110 var PopupComponent = require("./component/popup/Popup");
20111 exports.PopupComponent = PopupComponent;
20113 },{"./Edge":227,"./Render":232,"./Viewer":236,"./component/marker/Marker":262,"./component/popup/Popup":276,"./component/tag/Tag":282}],232:[function(require,module,exports){
20115 Object.defineProperty(exports, "__esModule", { value: true });
20116 var DOMRenderer_1 = require("./render/DOMRenderer");
20117 exports.DOMRenderer = DOMRenderer_1.DOMRenderer;
20118 var GLRenderer_1 = require("./render/GLRenderer");
20119 exports.GLRenderer = GLRenderer_1.GLRenderer;
20120 var GLRenderStage_1 = require("./render/GLRenderStage");
20121 exports.GLRenderStage = GLRenderStage_1.GLRenderStage;
20122 var RenderCamera_1 = require("./render/RenderCamera");
20123 exports.RenderCamera = RenderCamera_1.RenderCamera;
20124 var RenderMode_1 = require("./render/RenderMode");
20125 exports.RenderMode = RenderMode_1.RenderMode;
20126 var RenderService_1 = require("./render/RenderService");
20127 exports.RenderService = RenderService_1.RenderService;
20129 },{"./render/DOMRenderer":325,"./render/GLRenderStage":326,"./render/GLRenderer":327,"./render/RenderCamera":328,"./render/RenderMode":329,"./render/RenderService":330}],233:[function(require,module,exports){
20131 Object.defineProperty(exports, "__esModule", { value: true });
20132 var State_1 = require("./state/State");
20133 exports.State = State_1.State;
20134 var StateBase_1 = require("./state/states/StateBase");
20135 exports.StateBase = StateBase_1.StateBase;
20136 var StateContext_1 = require("./state/StateContext");
20137 exports.StateContext = StateContext_1.StateContext;
20138 var StateService_1 = require("./state/StateService");
20139 exports.StateService = StateService_1.StateService;
20140 var TraversingState_1 = require("./state/states/TraversingState");
20141 exports.TraversingState = TraversingState_1.TraversingState;
20142 var WaitingState_1 = require("./state/states/WaitingState");
20143 exports.WaitingState = WaitingState_1.WaitingState;
20145 },{"./state/State":331,"./state/StateContext":332,"./state/StateService":333,"./state/states/StateBase":334,"./state/states/TraversingState":335,"./state/states/WaitingState":336}],234:[function(require,module,exports){
20147 Object.defineProperty(exports, "__esModule", { value: true });
20148 var ImageTileLoader_1 = require("./tiles/ImageTileLoader");
20149 exports.ImageTileLoader = ImageTileLoader_1.ImageTileLoader;
20150 var ImageTileStore_1 = require("./tiles/ImageTileStore");
20151 exports.ImageTileStore = ImageTileStore_1.ImageTileStore;
20152 var TextureProvider_1 = require("./tiles/TextureProvider");
20153 exports.TextureProvider = TextureProvider_1.TextureProvider;
20154 var RegionOfInterestCalculator_1 = require("./tiles/RegionOfInterestCalculator");
20155 exports.RegionOfInterestCalculator = RegionOfInterestCalculator_1.RegionOfInterestCalculator;
20157 },{"./tiles/ImageTileLoader":337,"./tiles/ImageTileStore":338,"./tiles/RegionOfInterestCalculator":339,"./tiles/TextureProvider":340}],235:[function(require,module,exports){
20159 Object.defineProperty(exports, "__esModule", { value: true });
20160 var EventEmitter_1 = require("./utils/EventEmitter");
20161 exports.EventEmitter = EventEmitter_1.EventEmitter;
20162 var Settings_1 = require("./utils/Settings");
20163 exports.Settings = Settings_1.Settings;
20164 var Urls_1 = require("./utils/Urls");
20165 exports.Urls = Urls_1.Urls;
20167 },{"./utils/EventEmitter":341,"./utils/Settings":342,"./utils/Urls":343}],236:[function(require,module,exports){
20169 Object.defineProperty(exports, "__esModule", { value: true });
20170 var Alignment_1 = require("./viewer/Alignment");
20171 exports.Alignment = Alignment_1.Alignment;
20172 var CacheService_1 = require("./viewer/CacheService");
20173 exports.CacheService = CacheService_1.CacheService;
20174 var ComponentController_1 = require("./viewer/ComponentController");
20175 exports.ComponentController = ComponentController_1.ComponentController;
20176 var Container_1 = require("./viewer/Container");
20177 exports.Container = Container_1.Container;
20178 var Observer_1 = require("./viewer/Observer");
20179 exports.Observer = Observer_1.Observer;
20180 var ImageSize_1 = require("./viewer/ImageSize");
20181 exports.ImageSize = ImageSize_1.ImageSize;
20182 var LoadingService_1 = require("./viewer/LoadingService");
20183 exports.LoadingService = LoadingService_1.LoadingService;
20184 var MouseService_1 = require("./viewer/MouseService");
20185 exports.MouseService = MouseService_1.MouseService;
20186 var Navigator_1 = require("./viewer/Navigator");
20187 exports.Navigator = Navigator_1.Navigator;
20188 var Projection_1 = require("./viewer/Projection");
20189 exports.Projection = Projection_1.Projection;
20190 var SpriteService_1 = require("./viewer/SpriteService");
20191 exports.SpriteService = SpriteService_1.SpriteService;
20192 var TouchService_1 = require("./viewer/TouchService");
20193 exports.TouchService = TouchService_1.TouchService;
20194 var Viewer_1 = require("./viewer/Viewer");
20195 exports.Viewer = Viewer_1.Viewer;
20197 },{"./viewer/Alignment":344,"./viewer/CacheService":345,"./viewer/ComponentController":346,"./viewer/Container":347,"./viewer/ImageSize":348,"./viewer/LoadingService":349,"./viewer/MouseService":350,"./viewer/Navigator":351,"./viewer/Observer":352,"./viewer/Projection":353,"./viewer/SpriteService":354,"./viewer/TouchService":355,"./viewer/Viewer":356}],237:[function(require,module,exports){
20199 /// <reference path="../../typings/index.d.ts" />
20200 Object.defineProperty(exports, "__esModule", { value: true });
20201 var Observable_1 = require("rxjs/Observable");
20202 require("rxjs/add/observable/defer");
20203 require("rxjs/add/observable/fromPromise");
20204 require("rxjs/add/operator/catch");
20205 require("rxjs/add/operator/map");
20206 var API_1 = require("../API");
20210 * @classdesc Provides methods for access of API v3.
20212 var APIv3 = (function () {
20214 * Create a new api v3 instance.
20216 * @param {number} clientId - Client id for API requests.
20217 * @param {number} [token] - Optional bearer token for API requests of
20218 * protected resources.
20219 * @param {ModelCreator} [creator] - Optional model creator instance.
20221 function APIv3(clientId, token, creator) {
20222 this._clientId = clientId;
20223 this._modelCreator = creator != null ? creator : new API_1.ModelCreator();
20224 this._model = this._modelCreator.createModel(clientId, token);
20225 this._pageCount = 999;
20226 this._pathImageByKey = "imageByKey";
20227 this._pathImageCloseTo = "imageCloseTo";
20228 this._pathImagesByH = "imagesByH";
20229 this._pathImageViewAdd = "imageViewAdd";
20230 this._pathSequenceByKey = "sequenceByKey";
20231 this._pathSequenceViewAdd = "sequenceViewAdd";
20232 this._propertiesCore = [
20237 this._propertiesFill = [
20242 this._propertiesKey = [
20245 this._propertiesSequence = [
20248 this._propertiesSpatial = [
20262 this._propertiesUser = [
20266 APIv3.prototype.imageByKeyFill$ = function (keys) {
20267 return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
20268 this._pathImageByKey,
20270 this._propertiesKey
20271 .concat(this._propertiesFill)
20272 .concat(this._propertiesSpatial),
20273 this._propertiesKey
20274 .concat(this._propertiesUser)
20276 .map(function (value) {
20278 throw new Error("Images (" + keys.join(", ") + ") could not be found.");
20280 return value.json.imageByKey;
20281 }), this._pathImageByKey, keys);
20283 APIv3.prototype.imageByKeyFull$ = function (keys) {
20284 return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
20285 this._pathImageByKey,
20287 this._propertiesKey
20288 .concat(this._propertiesCore)
20289 .concat(this._propertiesFill)
20290 .concat(this._propertiesSpatial),
20291 this._propertiesKey
20292 .concat(this._propertiesUser)
20294 .map(function (value) {
20296 throw new Error("Images (" + keys.join(", ") + ") could not be found.");
20298 return value.json.imageByKey;
20299 }), this._pathImageByKey, keys);
20301 APIv3.prototype.imageCloseTo$ = function (lat, lon) {
20302 var lonLat = lon + ":" + lat;
20303 return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
20304 this._pathImageCloseTo,
20306 this._propertiesKey
20307 .concat(this._propertiesCore)
20308 .concat(this._propertiesFill)
20309 .concat(this._propertiesSpatial),
20310 this._propertiesKey
20311 .concat(this._propertiesUser)
20313 .map(function (value) {
20314 return value != null ? value.json.imageCloseTo[lonLat] : null;
20315 }), this._pathImageCloseTo, [lonLat]);
20317 APIv3.prototype.imagesByH$ = function (hs) {
20319 return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
20320 this._pathImagesByH,
20322 { from: 0, to: this._pageCount },
20323 this._propertiesKey
20324 .concat(this._propertiesCore),
20325 this._propertiesKey
20327 .map(function (value) {
20328 if (value == null) {
20329 value = { json: { imagesByH: {} } };
20330 for (var _i = 0, hs_1 = hs; _i < hs_1.length; _i++) {
20332 value.json.imagesByH[h] = {};
20333 for (var i = 0; i <= _this._pageCount; i++) {
20334 value.json.imagesByH[h][i] = null;
20338 return value.json.imagesByH;
20339 }), this._pathImagesByH, hs);
20341 APIv3.prototype.imageViewAdd$ = function (keys) {
20342 return this._catchInvalidateCall$(this._wrapPromise$(this._model.call([this._pathImageViewAdd], [keys])), this._pathImageViewAdd, keys);
20344 APIv3.prototype.invalidateImageByKey = function (keys) {
20345 this._invalidateGet(this._pathImageByKey, keys);
20347 APIv3.prototype.invalidateImagesByH = function (hs) {
20348 this._invalidateGet(this._pathImagesByH, hs);
20350 APIv3.prototype.invalidateSequenceByKey = function (sKeys) {
20351 this._invalidateGet(this._pathSequenceByKey, sKeys);
20353 APIv3.prototype.setToken = function (token) {
20354 this._model.invalidate([]);
20355 this._model = null;
20356 this._model = this._modelCreator.createModel(this._clientId, token);
20358 APIv3.prototype.sequenceByKey$ = function (sequenceKeys) {
20359 return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
20360 this._pathSequenceByKey,
20362 this._propertiesKey
20363 .concat(this._propertiesSequence)
20365 .map(function (value) {
20366 return value.json.sequenceByKey;
20367 }), this._pathSequenceByKey, sequenceKeys);
20369 APIv3.prototype.sequenceViewAdd$ = function (sequenceKeys) {
20370 return this._catchInvalidateCall$(this._wrapPromise$(this._model.call([this._pathSequenceViewAdd], [sequenceKeys])), this._pathSequenceViewAdd, sequenceKeys);
20372 Object.defineProperty(APIv3.prototype, "clientId", {
20374 return this._clientId;
20379 APIv3.prototype._catchInvalidateGet$ = function (observable, path, paths) {
20382 .catch(function (error) {
20383 _this._invalidateGet(path, paths);
20387 APIv3.prototype._catchInvalidateCall$ = function (observable, path, paths) {
20390 .catch(function (error) {
20391 _this._invalidateCall(path, paths);
20395 APIv3.prototype._invalidateGet = function (path, paths) {
20396 this._model.invalidate([path, paths]);
20398 APIv3.prototype._invalidateCall = function (path, paths) {
20399 this._model.invalidate([path], [paths]);
20401 APIv3.prototype._wrapPromise$ = function (promise) {
20402 return Observable_1.Observable.defer(function () { return Observable_1.Observable.fromPromise(promise); });
20406 exports.APIv3 = APIv3;
20407 exports.default = APIv3;
20409 },{"../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}],238:[function(require,module,exports){
20411 /// <reference path="../../typings/index.d.ts" />
20412 Object.defineProperty(exports, "__esModule", { value: true });
20413 var falcor = require("falcor");
20414 var HttpDataSource = require("falcor-http-datasource");
20415 var Utils_1 = require("../Utils");
20417 * @class ModelCreator
20419 * @classdesc Creates API models.
20421 var ModelCreator = (function () {
20422 function ModelCreator() {
20425 * Creates a Falcor model.
20427 * @description Max cache size will be set to 16 MB. Authorization
20428 * header will be added if bearer token is supplied.
20430 * @param {number} clientId - Client id for API requests.
20431 * @param {number} [token] - Optional bearer token for API requests of
20432 * protected resources.
20433 * @returns {falcor.Model} Falcor model for HTTP requests.
20435 ModelCreator.prototype.createModel = function (clientId, token) {
20436 var configuration = {
20438 withCredentials: false,
20440 if (token != null) {
20441 configuration.headers = { "Authorization": "Bearer " + token };
20443 return new falcor.Model({
20444 maxSize: 16 * 1024 * 1024,
20445 source: new HttpDataSource(Utils_1.Urls.falcorModel(clientId), configuration),
20448 return ModelCreator;
20450 exports.ModelCreator = ModelCreator;
20451 exports.default = ModelCreator;
20453 },{"../Utils":235,"falcor":15,"falcor-http-datasource":10}],239:[function(require,module,exports){
20455 /// <reference path="../../typings/index.d.ts" />
20456 var __extends = (this && this.__extends) || (function () {
20457 var extendStatics = Object.setPrototypeOf ||
20458 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20459 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
20460 return function (d, b) {
20461 extendStatics(d, b);
20462 function __() { this.constructor = d; }
20463 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20466 Object.defineProperty(exports, "__esModule", { value: true });
20467 var vd = require("virtual-dom");
20468 var Component_1 = require("../Component");
20469 var AttributionComponent = (function (_super) {
20470 __extends(AttributionComponent, _super);
20471 function AttributionComponent(name, container, navigator) {
20472 return _super.call(this, name, container, navigator) || this;
20474 AttributionComponent.prototype._activate = function () {
20476 this._disposable = this._navigator.stateService.currentNode$
20477 .map(function (node) {
20478 return { name: _this._name, vnode: _this._getAttributionNode(node.username, node.key) };
20480 .subscribe(this._container.domRenderer.render$);
20482 AttributionComponent.prototype._deactivate = function () {
20483 this._disposable.unsubscribe();
20485 AttributionComponent.prototype._getDefaultConfiguration = function () {
20488 AttributionComponent.prototype._getAttributionNode = function (username, photoId) {
20489 return vd.h("div.Attribution", {}, [
20490 vd.h("a", { href: "https://www.mapillary.com/app/user/" + username,
20492 textContent: "@" + username,
20494 vd.h("span", { textContent: "|" }, []),
20495 vd.h("a", { href: "https://www.mapillary.com/app/?pKey=" + photoId + "&focus=photo",
20497 textContent: "mapillary.com",
20501 AttributionComponent.componentName = "attribution";
20502 return AttributionComponent;
20503 }(Component_1.Component));
20504 exports.AttributionComponent = AttributionComponent;
20505 Component_1.ComponentService.register(AttributionComponent);
20506 exports.default = AttributionComponent;
20508 },{"../Component":226,"virtual-dom":182}],240:[function(require,module,exports){
20510 /// <reference path="../../typings/index.d.ts" />
20511 var __extends = (this && this.__extends) || (function () {
20512 var extendStatics = Object.setPrototypeOf ||
20513 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20514 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
20515 return function (d, b) {
20516 extendStatics(d, b);
20517 function __() { this.constructor = d; }
20518 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20521 Object.defineProperty(exports, "__esModule", { value: true });
20522 var vd = require("virtual-dom");
20523 var Component_1 = require("../Component");
20524 var BackgroundComponent = (function (_super) {
20525 __extends(BackgroundComponent, _super);
20526 function BackgroundComponent(name, container, navigator) {
20527 return _super.call(this, name, container, navigator) || this;
20529 BackgroundComponent.prototype._activate = function () {
20530 this._container.domRenderer.render$
20531 .next({ name: this._name, vnode: this._getBackgroundNode("The viewer can't display the given photo.") });
20533 BackgroundComponent.prototype._deactivate = function () {
20536 BackgroundComponent.prototype._getDefaultConfiguration = function () {
20539 BackgroundComponent.prototype._getBackgroundNode = function (notice) {
20540 // todo: add condition for when to display the DOM node
20541 return vd.h("div.BackgroundWrapper", {}, [
20542 vd.h("p", { textContent: notice }, []),
20545 BackgroundComponent.componentName = "background";
20546 return BackgroundComponent;
20547 }(Component_1.Component));
20548 exports.BackgroundComponent = BackgroundComponent;
20549 Component_1.ComponentService.register(BackgroundComponent);
20550 exports.default = BackgroundComponent;
20552 },{"../Component":226,"virtual-dom":182}],241:[function(require,module,exports){
20554 /// <reference path="../../typings/index.d.ts" />
20555 var __extends = (this && this.__extends) || (function () {
20556 var extendStatics = Object.setPrototypeOf ||
20557 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20558 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
20559 return function (d, b) {
20560 extendStatics(d, b);
20561 function __() { this.constructor = d; }
20562 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20565 Object.defineProperty(exports, "__esModule", { value: true });
20566 var vd = require("virtual-dom");
20567 var Observable_1 = require("rxjs/Observable");
20568 var Component_1 = require("../Component");
20569 var Geo_1 = require("../Geo");
20570 var BearingComponent = (function (_super) {
20571 __extends(BearingComponent, _super);
20572 function BearingComponent(name, container, navigator) {
20573 var _this = _super.call(this, name, container, navigator) || this;
20574 _this._spatial = new Geo_1.Spatial();
20575 _this._svgNamespace = "http://www.w3.org/2000/svg";
20576 _this._distinctThreshold = Math.PI / 90;
20579 BearingComponent.prototype._activate = function () {
20581 var nodeBearingFov$ = this._navigator.stateService.currentState$
20582 .distinctUntilChanged(undefined, function (frame) {
20583 return frame.state.currentNode.key;
20585 .map(function (frame) {
20586 var node = frame.state.currentNode;
20587 var transform = frame.state.currentTransform;
20589 var hFov_1 = 2 * Math.PI * node.gpano.CroppedAreaImageWidthPixels / node.gpano.FullPanoWidthPixels;
20590 return [_this._spatial.degToRad(node.ca), hFov_1];
20592 var size = Math.max(transform.basicWidth, transform.basicHeight);
20594 console.warn("Original image size (" + transform.basicWidth + ", " + transform.basicHeight + ") is invalid (" + node.key + ". " +
20595 "Not showing available fov.");
20597 var hFov = size > 0 ?
20598 2 * Math.atan(0.5 * transform.basicWidth / (size * transform.focal)) :
20600 return [_this._spatial.degToRad(node.ca), hFov];
20602 .distinctUntilChanged(function (a1, a2) {
20603 return Math.abs(a2[0] - a1[0]) < _this._distinctThreshold &&
20604 Math.abs(a2[1] - a1[1]) < _this._distinctThreshold;
20606 var cameraBearingFov$ = this._container.renderService.renderCamera$
20607 .map(function (rc) {
20608 var vFov = _this._spatial.degToRad(rc.perspective.fov);
20609 var hFov = rc.perspective.aspect === Number.POSITIVE_INFINITY ?
20611 Math.atan(rc.perspective.aspect * Math.tan(0.5 * vFov)) * 2;
20612 return [_this._spatial.azimuthalToBearing(rc.rotation.phi), hFov];
20614 .distinctUntilChanged(function (a1, a2) {
20615 return Math.abs(a2[0] - a1[0]) < _this._distinctThreshold &&
20616 Math.abs(a2[1] - a1[1]) < _this._distinctThreshold;
20618 this._renderSubscription = Observable_1.Observable
20619 .combineLatest(nodeBearingFov$, cameraBearingFov$)
20620 .map(function (args) {
20621 var background = vd.h("div.BearingIndicatorBackground", { oncontextmenu: function (event) { event.preventDefault(); } }, [
20622 vd.h("div.BearingIndicatorBackgroundRectangle", {}, []),
20623 vd.h("div.BearingIndicatorBackgroundCircle", {}, []),
20625 var north = vd.h("div.BearingIndicatorNorth", {}, []);
20626 var nodeSector = _this._createCircleSector(args[0][0], args[0][1], "#000");
20627 var cameraSector = _this._createCircleSector(args[1][0], args[1][1], "#fff");
20628 var compass = _this._createCircleSectorCompass(nodeSector, cameraSector);
20631 vnode: vd.h("div.BearingIndicator", {}, [
20638 .subscribe(this._container.domRenderer.render$);
20640 BearingComponent.prototype._deactivate = function () {
20641 this._renderSubscription.unsubscribe();
20643 BearingComponent.prototype._getDefaultConfiguration = function () {
20646 BearingComponent.prototype._createCircleSectorCompass = function (nodeSector, cameraSector) {
20647 var group = vd.h("g", {
20648 attributes: { transform: "translate(1,1)" },
20649 namespace: this._svgNamespace,
20650 }, [nodeSector, cameraSector]);
20651 var centerCircle = vd.h("circle", {
20658 "stroke-width": "0.0833333",
20660 namespace: this._svgNamespace,
20662 var svg = vd.h("svg", {
20663 attributes: { viewBox: "0 0 2 2" },
20664 namespace: this._svgNamespace,
20669 position: "absolute",
20672 }, [group, centerCircle]);
20675 BearingComponent.prototype._createCircleSector = function (bearing, fov, fill) {
20676 if (fov > 2 * Math.PI - Math.PI / 90) {
20677 return vd.h("circle", {
20678 attributes: { cx: "0", cy: "0", fill: fill, r: "1" },
20679 namespace: this._svgNamespace,
20682 var arcStart = bearing - fov / 2 - Math.PI / 2;
20683 var arcEnd = arcStart + fov;
20684 var startX = Math.cos(arcStart);
20685 var startY = Math.sin(arcStart);
20686 var endX = Math.cos(arcEnd);
20687 var endY = Math.sin(arcEnd);
20688 var largeArc = fov >= Math.PI ? 1 : 0;
20689 var description = "M 0 0 " + startX + " " + startY + " A 1 1 0 " + largeArc + " 1 " + endX + " " + endY;
20690 return vd.h("path", {
20691 attributes: { d: description, fill: fill },
20692 namespace: this._svgNamespace,
20695 BearingComponent.componentName = "bearing";
20696 return BearingComponent;
20697 }(Component_1.Component));
20698 exports.BearingComponent = BearingComponent;
20699 Component_1.ComponentService.register(BearingComponent);
20700 exports.default = BearingComponent;
20702 },{"../Component":226,"../Geo":229,"rxjs/Observable":29,"virtual-dom":182}],242:[function(require,module,exports){
20704 var __extends = (this && this.__extends) || (function () {
20705 var extendStatics = Object.setPrototypeOf ||
20706 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20707 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
20708 return function (d, b) {
20709 extendStatics(d, b);
20710 function __() { this.constructor = d; }
20711 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20714 Object.defineProperty(exports, "__esModule", { value: true });
20715 var Observable_1 = require("rxjs/Observable");
20716 require("rxjs/add/observable/combineLatest");
20717 require("rxjs/add/observable/from");
20718 require("rxjs/add/observable/merge");
20719 require("rxjs/add/observable/of");
20720 require("rxjs/add/observable/zip");
20721 require("rxjs/add/operator/catch");
20722 require("rxjs/add/operator/combineLatest");
20723 require("rxjs/add/operator/distinct");
20724 require("rxjs/add/operator/expand");
20725 require("rxjs/add/operator/filter");
20726 require("rxjs/add/operator/map");
20727 require("rxjs/add/operator/merge");
20728 require("rxjs/add/operator/mergeMap");
20729 require("rxjs/add/operator/mergeAll");
20730 require("rxjs/add/operator/skip");
20731 require("rxjs/add/operator/switchMap");
20732 var Edge_1 = require("../Edge");
20733 var Component_1 = require("../Component");
20734 var CacheComponent = (function (_super) {
20735 __extends(CacheComponent, _super);
20736 function CacheComponent(name, container, navigator) {
20737 return _super.call(this, name, container, navigator) || this;
20740 * Set the cache depth.
20742 * Configures the cache depth. The cache depth can be different for
20743 * different edge direction types.
20745 * @param {ICacheDepth} depth - Cache depth structure.
20747 CacheComponent.prototype.setDepth = function (depth) {
20748 this.configure({ depth: depth });
20750 CacheComponent.prototype._activate = function () {
20752 this._sequenceSubscription = Observable_1.Observable
20753 .combineLatest(this._navigator.stateService.currentNode$
20754 .switchMap(function (node) {
20755 return node.sequenceEdges$;
20757 .filter(function (status) {
20758 return status.cached;
20759 }), this._configuration$)
20760 .switchMap(function (nc) {
20761 var status = nc[0];
20762 var configuration = nc[1];
20763 var sequenceDepth = Math.max(0, Math.min(4, configuration.depth.sequence));
20764 var next$ = _this._cache$(status.edges, Edge_1.EdgeDirection.Next, sequenceDepth);
20765 var prev$ = _this._cache$(status.edges, Edge_1.EdgeDirection.Prev, sequenceDepth);
20766 return Observable_1.Observable
20767 .merge(next$, prev$)
20768 .catch(function (error, caught) {
20769 console.error("Failed to cache sequence edges.", error);
20770 return Observable_1.Observable.empty();
20773 .subscribe(function () { });
20774 this._spatialSubscription = this._navigator.stateService.currentNode$
20775 .switchMap(function (node) {
20776 return Observable_1.Observable
20777 .combineLatest(Observable_1.Observable.of(node), node.spatialEdges$
20778 .filter(function (status) {
20779 return status.cached;
20782 .combineLatest(this._configuration$, function (ns, configuration) {
20783 return [ns[0], ns[1], configuration];
20785 .switchMap(function (args) {
20786 var node = args[0];
20787 var edges = args[1].edges;
20788 var depth = args[2].depth;
20789 var panoDepth = Math.max(0, Math.min(2, depth.pano));
20790 var stepDepth = node.pano ? 0 : Math.max(0, Math.min(3, depth.step));
20791 var turnDepth = node.pano ? 0 : Math.max(0, Math.min(1, depth.turn));
20792 var pano$ = _this._cache$(edges, Edge_1.EdgeDirection.Pano, panoDepth);
20793 var forward$ = _this._cache$(edges, Edge_1.EdgeDirection.StepForward, stepDepth);
20794 var backward$ = _this._cache$(edges, Edge_1.EdgeDirection.StepBackward, stepDepth);
20795 var left$ = _this._cache$(edges, Edge_1.EdgeDirection.StepLeft, stepDepth);
20796 var right$ = _this._cache$(edges, Edge_1.EdgeDirection.StepRight, stepDepth);
20797 var turnLeft$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnLeft, turnDepth);
20798 var turnRight$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnRight, turnDepth);
20799 var turnU$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnU, turnDepth);
20800 return Observable_1.Observable
20801 .merge(forward$, backward$, left$, right$, pano$, turnLeft$, turnRight$, turnU$)
20802 .catch(function (error, caught) {
20803 console.error("Failed to cache spatial edges.", error);
20804 return Observable_1.Observable.empty();
20807 .subscribe(function () { });
20809 CacheComponent.prototype._deactivate = function () {
20810 this._sequenceSubscription.unsubscribe();
20811 this._spatialSubscription.unsubscribe();
20813 CacheComponent.prototype._getDefaultConfiguration = function () {
20814 return { depth: { pano: 1, sequence: 2, step: 1, turn: 0 } };
20816 CacheComponent.prototype._cache$ = function (edges, direction, depth) {
20818 return Observable_1.Observable
20819 .zip(Observable_1.Observable.of(edges), Observable_1.Observable.of(depth))
20820 .expand(function (ed) {
20823 var edgesDepths$ = [];
20825 for (var _i = 0, es_1 = es; _i < es_1.length; _i++) {
20826 var edge = es_1[_i];
20827 if (edge.data.direction === direction) {
20828 edgesDepths$.push(Observable_1.Observable
20829 .zip(_this._navigator.graphService.cacheNode$(edge.to)
20830 .mergeMap(function (n) {
20831 return _this._nodeToEdges$(n, direction);
20832 }), Observable_1.Observable.of(d - 1)));
20836 return Observable_1.Observable
20837 .from(edgesDepths$)
20842 CacheComponent.prototype._nodeToEdges$ = function (node, direction) {
20843 return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
20844 node.sequenceEdges$ :
20845 node.spatialEdges$)
20846 .first(function (status) {
20847 return status.cached;
20849 .map(function (status) {
20850 return status.edges;
20853 CacheComponent.componentName = "cache";
20854 return CacheComponent;
20855 }(Component_1.Component));
20856 exports.CacheComponent = CacheComponent;
20857 Component_1.ComponentService.register(CacheComponent);
20858 exports.default = CacheComponent;
20860 },{"../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}],243:[function(require,module,exports){
20862 var __extends = (this && this.__extends) || (function () {
20863 var extendStatics = Object.setPrototypeOf ||
20864 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
20865 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
20866 return function (d, b) {
20867 extendStatics(d, b);
20868 function __() { this.constructor = d; }
20869 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
20872 Object.defineProperty(exports, "__esModule", { value: true });
20873 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
20874 var Subject_1 = require("rxjs/Subject");
20875 require("rxjs/add/operator/publishReplay");
20876 require("rxjs/add/operator/scan");
20877 require("rxjs/add/operator/startWith");
20878 var Utils_1 = require("../Utils");
20879 var Component = (function (_super) {
20880 __extends(Component, _super);
20881 function Component(name, container, navigator) {
20882 var _this = _super.call(this) || this;
20883 _this._activated$ = new BehaviorSubject_1.BehaviorSubject(false);
20884 _this._configurationSubject$ = new Subject_1.Subject();
20885 _this._activated = false;
20886 _this._container = container;
20887 _this._name = name;
20888 _this._navigator = navigator;
20889 _this._configuration$ =
20890 _this._configurationSubject$
20891 .startWith(_this.defaultConfiguration)
20892 .scan(function (conf, newConf) {
20893 for (var key in newConf) {
20894 if (newConf.hasOwnProperty(key)) {
20895 conf[key] = newConf[key];
20902 _this._configuration$.subscribe(function () { });
20905 Object.defineProperty(Component.prototype, "activated", {
20907 return this._activated;
20912 Object.defineProperty(Component.prototype, "activated$", {
20914 return this._activated$;
20919 Object.defineProperty(Component.prototype, "defaultConfiguration", {
20921 * Get default configuration.
20923 * @returns {TConfiguration} Default configuration for component.
20926 return this._getDefaultConfiguration();
20931 Object.defineProperty(Component.prototype, "configuration$", {
20933 return this._configuration$;
20938 Object.defineProperty(Component.prototype, "name", {
20945 Component.prototype.activate = function (conf) {
20946 if (this._activated) {
20949 if (conf !== undefined) {
20950 this._configurationSubject$.next(conf);
20952 this._activated = true;
20954 this._activated$.next(true);
20956 Component.prototype.configure = function (conf) {
20957 this._configurationSubject$.next(conf);
20959 Component.prototype.deactivate = function () {
20960 if (!this._activated) {
20963 this._activated = false;
20964 this._deactivate();
20965 this._container.domRenderer.clear(this._name);
20966 this._container.glRenderer.clear(this._name);
20967 this._activated$.next(false);
20970 * Detect the viewer's new width and height and resize the component's
20971 * rendered elements accordingly if applicable.
20973 Component.prototype.resize = function () { return; };
20975 * Component name. Used when interacting with component through the Viewer's API.
20977 Component.componentName = "not_worthy";
20979 }(Utils_1.EventEmitter));
20980 exports.Component = Component;
20981 exports.default = Component;
20983 },{"../Utils":235,"rxjs/BehaviorSubject":26,"rxjs/Subject":34,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":73,"rxjs/add/operator/startWith":78}],244:[function(require,module,exports){
20985 /// <reference path="../../typings/index.d.ts" />
20986 Object.defineProperty(exports, "__esModule", { value: true });
20987 var _ = require("underscore");
20988 var Error_1 = require("../Error");
20989 var ComponentService = (function () {
20990 function ComponentService(container, navigator) {
20991 this._components = {};
20992 this._container = container;
20993 this._navigator = navigator;
20994 for (var _i = 0, _a = _.values(ComponentService.registeredComponents); _i < _a.length; _i++) {
20995 var component = _a[_i];
20996 this._components[component.componentName] = {
20998 component: new component(component.componentName, container, navigator),
21001 this._coverComponent = new ComponentService.registeredCoverComponent("cover", container, navigator);
21002 this._coverComponent.activate();
21003 this._coverActivated = true;
21005 ComponentService.register = function (component) {
21006 if (ComponentService.registeredComponents[component.componentName] === undefined) {
21007 ComponentService.registeredComponents[component.componentName] = component;
21010 ComponentService.registerCover = function (coverComponent) {
21011 ComponentService.registeredCoverComponent = coverComponent;
21013 ComponentService.prototype.activateCover = function () {
21014 if (this._coverActivated) {
21017 this._coverActivated = true;
21018 for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
21019 var component = _a[_i];
21020 if (component.active) {
21021 component.component.deactivate();
21026 ComponentService.prototype.deactivateCover = function () {
21027 if (!this._coverActivated) {
21030 this._coverActivated = false;
21031 for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
21032 var component = _a[_i];
21033 if (component.active) {
21034 component.component.activate();
21039 ComponentService.prototype.activate = function (name) {
21040 this._checkName(name);
21041 this._components[name].active = true;
21042 if (!this._coverActivated) {
21043 this.get(name).activate();
21046 ComponentService.prototype.configure = function (name, conf) {
21047 this._checkName(name);
21048 this.get(name).configure(conf);
21050 ComponentService.prototype.deactivate = function (name) {
21051 this._checkName(name);
21052 this._components[name].active = false;
21053 if (!this._coverActivated) {
21054 this.get(name).deactivate();
21057 ComponentService.prototype.resize = function () {
21058 for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
21059 var component = _a[_i];
21060 component.component.resize();
21063 ComponentService.prototype.get = function (name) {
21064 return this._components[name].component;
21066 ComponentService.prototype.getCover = function () {
21067 return this._coverComponent;
21069 ComponentService.prototype._checkName = function (name) {
21070 if (!(name in this._components)) {
21071 throw new Error_1.ArgumentMapillaryError("Component does not exist: " + name);
21074 ComponentService.registeredComponents = {};
21075 return ComponentService;
21077 exports.ComponentService = ComponentService;
21078 exports.default = ComponentService;
21080 },{"../Error":228,"underscore":178}],245:[function(require,module,exports){
21082 /// <reference path="../../typings/index.d.ts" />
21083 var __extends = (this && this.__extends) || (function () {
21084 var extendStatics = Object.setPrototypeOf ||
21085 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21086 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21087 return function (d, b) {
21088 extendStatics(d, b);
21089 function __() { this.constructor = d; }
21090 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21093 Object.defineProperty(exports, "__esModule", { value: true });
21094 var vd = require("virtual-dom");
21095 require("rxjs/add/operator/filter");
21096 require("rxjs/add/operator/map");
21097 require("rxjs/add/operator/withLatestFrom");
21098 var Component_1 = require("../Component");
21099 var CoverComponent = (function (_super) {
21100 __extends(CoverComponent, _super);
21101 function CoverComponent(name, container, navigator) {
21102 return _super.call(this, name, container, navigator) || this;
21104 CoverComponent.prototype._activate = function () {
21106 this._keyDisposable = this._navigator.stateService.currentNode$
21107 .withLatestFrom(this._configuration$, function (node, configuration) {
21108 return [node, configuration];
21110 .filter(function (nc) {
21111 return nc[0].key !== nc[1].key;
21113 .map(function (nc) { return nc[0]; })
21114 .map(function (node) {
21115 return { key: node.key, src: node.image.src };
21117 .subscribe(this._configurationSubject$);
21118 this._disposable = this._configuration$
21119 .map(function (conf) {
21121 return { name: _this._name, vnode: vd.h("div", []) };
21123 if (!conf.visible) {
21124 return { name: _this._name, vnode: vd.h("div.Cover.CoverDone", [_this._getCoverBackgroundVNode(conf)]) };
21126 return { name: _this._name, vnode: _this._getCoverButtonVNode(conf) };
21128 .subscribe(this._container.domRenderer.render$);
21130 CoverComponent.prototype._deactivate = function () {
21131 this._disposable.unsubscribe();
21132 this._keyDisposable.unsubscribe();
21134 CoverComponent.prototype._getDefaultConfiguration = function () {
21135 return { "loading": false, "visible": true };
21137 CoverComponent.prototype._getCoverButtonVNode = function (conf) {
21139 var cover = conf.loading ? "div.Cover.CoverLoading" : "div.Cover";
21140 return vd.h(cover, [
21141 this._getCoverBackgroundVNode(conf),
21142 vd.h("button.CoverButton", { onclick: function () { _this.configure({ loading: true }); } }, ["Explore"]),
21143 vd.h("a.CoverLogo", { href: "https://www.mapillary.com", target: "_blank" }, []),
21146 CoverComponent.prototype._getCoverBackgroundVNode = function (conf) {
21147 var url = conf.src != null ?
21148 "url(" + conf.src + ")" :
21149 "url(https://d1cuyjsrcm0gby.cloudfront.net/" + conf.key + "/thumb-640.jpg)";
21150 var properties = { style: { backgroundImage: url } };
21152 if (conf.loading) {
21153 children.push(vd.h("div.Spinner", {}, []));
21155 children.push(vd.h("div.CoverBackgroundGradient", {}, []));
21156 return vd.h("div.CoverBackground", properties, children);
21158 CoverComponent.componentName = "cover";
21159 return CoverComponent;
21160 }(Component_1.Component));
21161 exports.CoverComponent = CoverComponent;
21162 Component_1.ComponentService.registerCover(CoverComponent);
21163 exports.default = CoverComponent;
21165 },{"../Component":226,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/withLatestFrom":83,"virtual-dom":182}],246:[function(require,module,exports){
21167 /// <reference path="../../typings/index.d.ts" />
21168 var __extends = (this && this.__extends) || (function () {
21169 var extendStatics = Object.setPrototypeOf ||
21170 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21171 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21172 return function (d, b) {
21173 extendStatics(d, b);
21174 function __() { this.constructor = d; }
21175 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21178 Object.defineProperty(exports, "__esModule", { value: true });
21179 var _ = require("underscore");
21180 var vd = require("virtual-dom");
21181 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
21182 require("rxjs/add/operator/combineLatest");
21183 var Component_1 = require("../Component");
21184 var DebugComponent = (function (_super) {
21185 __extends(DebugComponent, _super);
21186 function DebugComponent(name, container, navigator) {
21187 var _this = _super.call(this, name, container, navigator) || this;
21188 _this._open$ = new BehaviorSubject_1.BehaviorSubject(false);
21189 _this._displaying = false;
21192 DebugComponent.prototype._activate = function () {
21194 this._disposable = this._navigator.stateService.currentState$
21195 .combineLatest(this._open$, this._navigator.imageLoadingService.loadstatus$, function (frame, open, loadStatus) {
21196 return { name: _this._name, vnode: _this._getDebugVNode(open, _this._getDebugInfo(frame, loadStatus)) };
21198 .subscribe(this._container.domRenderer.render$);
21200 DebugComponent.prototype._deactivate = function () {
21201 this._disposable.unsubscribe();
21203 DebugComponent.prototype._getDefaultConfiguration = function () {
21206 DebugComponent.prototype._getDebugInfo = function (frame, loadStatus) {
21208 ret.push(vd.h("h2", "Node"));
21209 if (frame.state.currentNode) {
21210 ret.push(vd.h("p", "currentNode: " + frame.state.currentNode.key));
21212 if (frame.state.previousNode) {
21213 ret.push(vd.h("p", "previousNode: " + frame.state.previousNode.key));
21215 ret.push(vd.h("h2", "Loading"));
21219 for (var _i = 0, _a = _.values(loadStatus); _i < _a.length; _i++) {
21220 var loadStat = _a[_i];
21221 total += loadStat.loaded;
21222 if (loadStat.loaded !== loadStat.total) {
21229 ret.push(vd.h("p", "Loaded Images: " + loaded));
21230 ret.push(vd.h("p", "Loading Images: " + loading));
21231 ret.push(vd.h("p", "Total bytes loaded: " + total));
21232 ret.push(vd.h("h2", "Camera"));
21233 ret.push(vd.h("p", "camera.position.x: " + frame.state.camera.position.x));
21234 ret.push(vd.h("p", "camera.position.y: " + frame.state.camera.position.y));
21235 ret.push(vd.h("p", "camera.position.z: " + frame.state.camera.position.z));
21236 ret.push(vd.h("p", "camera.lookat.x: " + frame.state.camera.lookat.x));
21237 ret.push(vd.h("p", "camera.lookat.y: " + frame.state.camera.lookat.y));
21238 ret.push(vd.h("p", "camera.lookat.z: " + frame.state.camera.lookat.z));
21239 ret.push(vd.h("p", "camera.up.x: " + frame.state.camera.up.x));
21240 ret.push(vd.h("p", "camera.up.y: " + frame.state.camera.up.y));
21241 ret.push(vd.h("p", "camera.up.z: " + frame.state.camera.up.z));
21244 DebugComponent.prototype._getDebugVNode = function (open, info) {
21246 return vd.h("div.Debug", {}, [
21247 vd.h("h2", {}, ["Debug"]),
21248 this._getDebugVNodeButton(open),
21249 vd.h("pre", {}, info),
21253 return this._getDebugVNodeButton(open);
21256 DebugComponent.prototype._getDebugVNodeButton = function (open) {
21257 var buttonText = open ? "Disable Debug" : "D";
21258 var buttonCssClass = open ? "" : ".DebugButtonFixed";
21260 return vd.h("button.DebugButton" + buttonCssClass, { onclick: this._closeDebugElement.bind(this) }, [buttonText]);
21263 return vd.h("button.DebugButton" + buttonCssClass, { onclick: this._openDebugElement.bind(this) }, [buttonText]);
21266 DebugComponent.prototype._closeDebugElement = function (open) {
21267 this._open$.next(false);
21269 DebugComponent.prototype._openDebugElement = function () {
21270 this._open$.next(true);
21272 DebugComponent.componentName = "debug";
21273 return DebugComponent;
21274 }(Component_1.Component));
21275 exports.DebugComponent = DebugComponent;
21276 Component_1.ComponentService.register(DebugComponent);
21277 exports.default = DebugComponent;
21279 },{"../Component":226,"rxjs/BehaviorSubject":26,"rxjs/add/operator/combineLatest":53,"underscore":178,"virtual-dom":182}],247:[function(require,module,exports){
21281 /// <reference path="../../typings/index.d.ts" />
21282 var __extends = (this && this.__extends) || (function () {
21283 var extendStatics = Object.setPrototypeOf ||
21284 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21285 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21286 return function (d, b) {
21287 extendStatics(d, b);
21288 function __() { this.constructor = d; }
21289 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21292 Object.defineProperty(exports, "__esModule", { value: true });
21293 var vd = require("virtual-dom");
21294 require("rxjs/add/operator/combineLatest");
21295 var Component_1 = require("../Component");
21296 var ImageComponent = (function (_super) {
21297 __extends(ImageComponent, _super);
21298 function ImageComponent(name, container, navigator) {
21299 var _this = _super.call(this, name, container, navigator) || this;
21300 _this._canvasId = container.id + "-" + _this._name;
21303 ImageComponent.prototype._activate = function () {
21305 this.drawSubscription = this._container.domRenderer.element$
21306 .combineLatest(this._navigator.stateService.currentNode$, function (element, node) {
21307 var canvas = document.getElementById(_this._canvasId);
21308 return { canvas: canvas, node: node };
21310 .subscribe(function (canvasNode) {
21311 var canvas = canvasNode.canvas;
21312 var node = canvasNode.node;
21313 if (!node || !canvas) {
21316 var adaptableDomRenderer = canvas.parentElement;
21317 var width = adaptableDomRenderer.offsetWidth;
21318 var height = adaptableDomRenderer.offsetHeight;
21319 canvas.width = width;
21320 canvas.height = height;
21321 var ctx = canvas.getContext("2d");
21322 ctx.drawImage(node.image, 0, 0, width, height);
21324 this._container.domRenderer.renderAdaptive$.next({ name: this._name, vnode: vd.h("canvas#" + this._canvasId, []) });
21326 ImageComponent.prototype._deactivate = function () {
21327 this.drawSubscription.unsubscribe();
21329 ImageComponent.prototype._getDefaultConfiguration = function () {
21332 ImageComponent.componentName = "image";
21333 return ImageComponent;
21334 }(Component_1.Component));
21335 exports.ImageComponent = ImageComponent;
21336 Component_1.ComponentService.register(ImageComponent);
21337 exports.default = ImageComponent;
21339 },{"../Component":226,"rxjs/add/operator/combineLatest":53,"virtual-dom":182}],248:[function(require,module,exports){
21341 var __extends = (this && this.__extends) || (function () {
21342 var extendStatics = Object.setPrototypeOf ||
21343 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21344 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21345 return function (d, b) {
21346 extendStatics(d, b);
21347 function __() { this.constructor = d; }
21348 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21351 Object.defineProperty(exports, "__esModule", { value: true });
21352 var Observable_1 = require("rxjs/Observable");
21353 require("rxjs/add/observable/fromEvent");
21354 require("rxjs/add/operator/withLatestFrom");
21355 var Edge_1 = require("../Edge");
21356 var Component_1 = require("../Component");
21357 var Geo_1 = require("../Geo");
21358 var KeyboardComponent = (function (_super) {
21359 __extends(KeyboardComponent, _super);
21360 function KeyboardComponent(name, container, navigator) {
21361 var _this = _super.call(this, name, container, navigator) || this;
21362 _this._spatial = new Geo_1.Spatial();
21363 _this._perspectiveDirections = [
21364 Edge_1.EdgeDirection.StepForward,
21365 Edge_1.EdgeDirection.StepBackward,
21366 Edge_1.EdgeDirection.StepLeft,
21367 Edge_1.EdgeDirection.StepRight,
21368 Edge_1.EdgeDirection.TurnLeft,
21369 Edge_1.EdgeDirection.TurnRight,
21370 Edge_1.EdgeDirection.TurnU,
21374 KeyboardComponent.prototype._activate = function () {
21376 var sequenceEdges$ = this._navigator.stateService.currentNode$
21377 .switchMap(function (node) {
21378 return node.sequenceEdges$;
21380 var spatialEdges$ = this._navigator.stateService.currentNode$
21381 .switchMap(function (node) {
21382 return node.spatialEdges$;
21384 this._disposable = Observable_1.Observable
21385 .fromEvent(document, "keydown")
21386 .withLatestFrom(this._navigator.stateService.currentState$, sequenceEdges$, spatialEdges$, function (event, frame, sequenceEdges, spatialEdges) {
21387 return { event: event, frame: frame, sequenceEdges: sequenceEdges, spatialEdges: spatialEdges };
21389 .subscribe(function (kf) {
21390 if (!kf.frame.state.currentNode.pano) {
21391 _this._navigatePerspective(kf.event, kf.sequenceEdges, kf.spatialEdges);
21394 _this._navigatePanorama(kf.event, kf.sequenceEdges, kf.spatialEdges, kf.frame.state.camera);
21398 KeyboardComponent.prototype._deactivate = function () {
21399 this._disposable.unsubscribe();
21401 KeyboardComponent.prototype._getDefaultConfiguration = function () {
21404 KeyboardComponent.prototype._navigatePanorama = function (event, sequenceEdges, spatialEdges, camera) {
21405 var navigationAngle = 0;
21406 var stepDirection = null;
21407 var sequenceDirection = null;
21408 var phi = this._rotationFromCamera(camera).phi;
21409 switch (event.keyCode) {
21411 if (event.shiftKey || event.altKey) {
21414 navigationAngle = Math.PI / 2 + phi;
21415 stepDirection = Edge_1.EdgeDirection.StepLeft;
21418 if (event.shiftKey) {
21421 if (event.altKey) {
21422 sequenceDirection = Edge_1.EdgeDirection.Next;
21425 navigationAngle = phi;
21426 stepDirection = Edge_1.EdgeDirection.StepForward;
21429 if (event.shiftKey || event.altKey) {
21432 navigationAngle = -Math.PI / 2 + phi;
21433 stepDirection = Edge_1.EdgeDirection.StepRight;
21436 if (event.shiftKey) {
21439 if (event.altKey) {
21440 sequenceDirection = Edge_1.EdgeDirection.Prev;
21443 navigationAngle = Math.PI + phi;
21444 stepDirection = Edge_1.EdgeDirection.StepBackward;
21449 event.preventDefault();
21450 if (sequenceDirection != null) {
21451 this._moveInDir(sequenceDirection, sequenceEdges);
21454 if (stepDirection == null || !spatialEdges.cached) {
21457 navigationAngle = this._spatial.wrapAngle(navigationAngle);
21458 var threshold = Math.PI / 4;
21459 var edges = spatialEdges.edges.filter(function (e) {
21460 return e.data.direction === Edge_1.EdgeDirection.Pano ||
21461 e.data.direction === stepDirection;
21463 var smallestAngle = Number.MAX_VALUE;
21465 for (var _i = 0, edges_1 = edges; _i < edges_1.length; _i++) {
21466 var edge = edges_1[_i];
21467 var angle = Math.abs(this._spatial.wrapAngle(edge.data.worldMotionAzimuth - navigationAngle));
21468 if (angle < Math.min(smallestAngle, threshold)) {
21469 smallestAngle = angle;
21473 if (toKey == null) {
21476 this._navigator.moveToKey$(toKey)
21477 .subscribe(function (n) { return; }, function (e) { console.error(e); });
21479 KeyboardComponent.prototype._rotationFromCamera = function (camera) {
21480 var direction = camera.lookat.clone().sub(camera.position);
21481 var upProjection = direction.clone().dot(camera.up);
21482 var planeProjection = direction.clone().sub(camera.up.clone().multiplyScalar(upProjection));
21483 var phi = Math.atan2(planeProjection.y, planeProjection.x);
21484 var theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
21485 return { phi: phi, theta: theta };
21487 KeyboardComponent.prototype._navigatePerspective = function (event, sequenceEdges, spatialEdges) {
21488 var direction = null;
21489 var sequenceDirection = null;
21490 switch (event.keyCode) {
21492 if (event.altKey) {
21495 direction = event.shiftKey ? Edge_1.EdgeDirection.TurnLeft : Edge_1.EdgeDirection.StepLeft;
21498 if (event.altKey) {
21499 sequenceDirection = Edge_1.EdgeDirection.Next;
21502 direction = event.shiftKey ? Edge_1.EdgeDirection.Pano : Edge_1.EdgeDirection.StepForward;
21505 if (event.altKey) {
21508 direction = event.shiftKey ? Edge_1.EdgeDirection.TurnRight : Edge_1.EdgeDirection.StepRight;
21511 if (event.altKey) {
21512 sequenceDirection = Edge_1.EdgeDirection.Prev;
21515 direction = event.shiftKey ? Edge_1.EdgeDirection.TurnU : Edge_1.EdgeDirection.StepBackward;
21520 event.preventDefault();
21521 if (sequenceDirection != null) {
21522 this._moveInDir(sequenceDirection, sequenceEdges);
21525 this._moveInDir(direction, spatialEdges);
21527 KeyboardComponent.prototype._moveInDir = function (direction, edgeStatus) {
21528 if (!edgeStatus.cached) {
21531 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
21533 if (edge.data.direction === direction) {
21534 this._navigator.moveToKey$(edge.to)
21535 .subscribe(function (n) { return; }, function (e) { console.error(e); });
21540 KeyboardComponent.componentName = "keyboard";
21541 return KeyboardComponent;
21542 }(Component_1.Component));
21543 exports.KeyboardComponent = KeyboardComponent;
21544 Component_1.ComponentService.register(KeyboardComponent);
21545 exports.default = KeyboardComponent;
21547 },{"../Component":226,"../Edge":227,"../Geo":229,"rxjs/Observable":29,"rxjs/add/observable/fromEvent":42,"rxjs/add/operator/withLatestFrom":83}],249:[function(require,module,exports){
21549 /// <reference path="../../typings/index.d.ts" />
21550 var __extends = (this && this.__extends) || (function () {
21551 var extendStatics = Object.setPrototypeOf ||
21552 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21553 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21554 return function (d, b) {
21555 extendStatics(d, b);
21556 function __() { this.constructor = d; }
21557 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21560 Object.defineProperty(exports, "__esModule", { value: true });
21561 var _ = require("underscore");
21562 var vd = require("virtual-dom");
21563 require("rxjs/add/operator/combineLatest");
21564 var Component_1 = require("../Component");
21565 var LoadingComponent = (function (_super) {
21566 __extends(LoadingComponent, _super);
21567 function LoadingComponent(name, container, navigator) {
21568 return _super.call(this, name, container, navigator) || this;
21570 LoadingComponent.prototype._activate = function () {
21572 this._loadingSubscription = this._navigator.loadingService.loading$
21573 .combineLatest(this._navigator.imageLoadingService.loadstatus$, function (loading, loadStatus) {
21575 return { name: "loading", vnode: _this._getBarVNode(100) };
21579 for (var _i = 0, _a = _.values(loadStatus); _i < _a.length; _i++) {
21580 var loadStat = _a[_i];
21581 if (loadStat.loaded !== loadStat.total) {
21582 loaded += loadStat.loaded;
21583 total += loadStat.total;
21586 var percentage = 100;
21588 percentage = (loaded / total) * 100;
21590 return { name: _this._name, vnode: _this._getBarVNode(percentage) };
21592 .subscribe(this._container.domRenderer.render$);
21594 LoadingComponent.prototype._deactivate = function () {
21595 this._loadingSubscription.unsubscribe();
21597 LoadingComponent.prototype._getDefaultConfiguration = function () {
21600 LoadingComponent.prototype._getBarVNode = function (percentage) {
21601 var loadingBarStyle = {};
21602 var loadingContainerStyle = {};
21603 if (percentage !== 100) {
21604 loadingBarStyle.width = percentage.toFixed(0) + "%";
21605 loadingBarStyle.opacity = "1";
21608 loadingBarStyle.width = "100%";
21609 loadingBarStyle.opacity = "0";
21611 return vd.h("div.Loading", { style: loadingContainerStyle }, [vd.h("div.LoadingBar", { style: loadingBarStyle }, [])]);
21613 LoadingComponent.componentName = "loading";
21614 return LoadingComponent;
21615 }(Component_1.Component));
21616 exports.LoadingComponent = LoadingComponent;
21617 Component_1.ComponentService.register(LoadingComponent);
21618 exports.default = LoadingComponent;
21620 },{"../Component":226,"rxjs/add/operator/combineLatest":53,"underscore":178,"virtual-dom":182}],250:[function(require,module,exports){
21622 /// <reference path="../../typings/index.d.ts" />
21623 var __extends = (this && this.__extends) || (function () {
21624 var extendStatics = Object.setPrototypeOf ||
21625 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21626 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21627 return function (d, b) {
21628 extendStatics(d, b);
21629 function __() { this.constructor = d; }
21630 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21633 Object.defineProperty(exports, "__esModule", { value: true });
21634 var vd = require("virtual-dom");
21635 var Observable_1 = require("rxjs/Observable");
21636 require("rxjs/add/operator/map");
21637 require("rxjs/add/operator/first");
21638 var Edge_1 = require("../Edge");
21639 var Component_1 = require("../Component");
21640 var NavigationComponent = (function (_super) {
21641 __extends(NavigationComponent, _super);
21642 function NavigationComponent(name, container, navigator) {
21643 var _this = _super.call(this, name, container, navigator) || this;
21644 _this._dirNames = {};
21645 _this._dirNames[Edge_1.EdgeDirection.StepForward] = "Forward";
21646 _this._dirNames[Edge_1.EdgeDirection.StepBackward] = "Backward";
21647 _this._dirNames[Edge_1.EdgeDirection.StepLeft] = "Left";
21648 _this._dirNames[Edge_1.EdgeDirection.StepRight] = "Right";
21649 _this._dirNames[Edge_1.EdgeDirection.TurnLeft] = "Turnleft";
21650 _this._dirNames[Edge_1.EdgeDirection.TurnRight] = "Turnright";
21651 _this._dirNames[Edge_1.EdgeDirection.TurnU] = "Turnaround";
21654 NavigationComponent.prototype._activate = function () {
21656 this._renderSubscription = this._navigator.stateService.currentNode$
21657 .switchMap(function (node) {
21659 Observable_1.Observable.of([]) :
21660 Observable_1.Observable.combineLatest(node.sequenceEdges$, node.spatialEdges$, function (seq, spa) {
21661 return seq.edges.concat(spa.edges);
21664 .map(function (edges) {
21666 for (var _i = 0, edges_1 = edges; _i < edges_1.length; _i++) {
21667 var edge = edges_1[_i];
21668 var direction = edge.data.direction;
21669 var name_1 = _this._dirNames[direction];
21670 if (name_1 == null) {
21673 btns.push(_this._createVNode(direction, name_1));
21675 return { name: _this._name, vnode: vd.h("div.NavigationComponent", btns) };
21677 .subscribe(this._container.domRenderer.render$);
21679 NavigationComponent.prototype._deactivate = function () {
21680 this._renderSubscription.unsubscribe();
21682 NavigationComponent.prototype._getDefaultConfiguration = function () {
21685 NavigationComponent.prototype._createVNode = function (direction, name) {
21687 return vd.h("span.Direction.Direction" + name, {
21688 onclick: function (ev) {
21689 _this._navigator.moveDir$(direction)
21690 .subscribe(function (node) { return; }, function (error) { console.error(error); });
21694 NavigationComponent.componentName = "navigation";
21695 return NavigationComponent;
21696 }(Component_1.Component));
21697 exports.NavigationComponent = NavigationComponent;
21698 Component_1.ComponentService.register(NavigationComponent);
21699 exports.default = NavigationComponent;
21701 },{"../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){
21703 /// <reference path="../../typings/index.d.ts" />
21704 var __extends = (this && this.__extends) || (function () {
21705 var extendStatics = Object.setPrototypeOf ||
21706 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21707 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21708 return function (d, b) {
21709 extendStatics(d, b);
21710 function __() { this.constructor = d; }
21711 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21714 Object.defineProperty(exports, "__esModule", { value: true });
21715 var _ = require("underscore");
21716 var vd = require("virtual-dom");
21717 var Observable_1 = require("rxjs/Observable");
21718 require("rxjs/add/observable/fromPromise");
21719 require("rxjs/add/observable/of");
21720 require("rxjs/add/operator/combineLatest");
21721 require("rxjs/add/operator/distinct");
21722 require("rxjs/add/operator/distinctUntilChanged");
21723 require("rxjs/add/operator/filter");
21724 require("rxjs/add/operator/map");
21725 require("rxjs/add/operator/mergeMap");
21726 require("rxjs/add/operator/pluck");
21727 require("rxjs/add/operator/scan");
21728 var Component_1 = require("../Component");
21729 var DescriptionState = (function () {
21730 function DescriptionState() {
21732 return DescriptionState;
21734 var RouteState = (function () {
21735 function RouteState() {
21739 var RouteTrack = (function () {
21740 function RouteTrack() {
21741 this.nodeInstructions = [];
21742 this.nodeInstructionsOrdered = [];
21746 var RouteComponent = (function (_super) {
21747 __extends(RouteComponent, _super);
21748 function RouteComponent(name, container, navigator) {
21749 return _super.call(this, name, container, navigator) || this;
21751 RouteComponent.prototype._activate = function () {
21753 var _slowedStream$;
21754 _slowedStream$ = this._navigator.stateService.currentState$.filter(function (frame) {
21755 return (frame.id % 2) === 0;
21756 }).filter(function (frame) {
21757 return frame.state.nodesAhead < 15;
21758 }).distinctUntilChanged(undefined, function (frame) {
21759 return frame.state.lastNode.key;
21762 _routeTrack$ = this.configuration$.mergeMap(function (conf) {
21763 return Observable_1.Observable.from(conf.paths);
21764 }).distinct(function (p) {
21765 return p.sequenceKey;
21766 }).mergeMap(function (path) {
21767 return _this._navigator.apiV3.sequenceByKey$([path.sequenceKey])
21768 .map(function (sequenceByKey) {
21769 return sequenceByKey[path.sequenceKey];
21771 }).combineLatest(this.configuration$, function (sequence, conf) {
21773 var instructionPlaces = [];
21774 for (var _i = 0, _a = conf.paths; _i < _a.length; _i++) {
21776 if (path.sequenceKey === sequence.key) {
21777 var nodeInstructions = [];
21778 var saveKey = false;
21779 for (var _b = 0, _c = sequence.keys; _b < _c.length; _b++) {
21781 if (path.startKey === key) {
21785 var description = null;
21786 for (var _d = 0, _e = path.infoKeys; _d < _e.length; _d++) {
21787 var infoKey = _e[_d];
21788 if (infoKey.key === key) {
21789 description = infoKey.description;
21792 nodeInstructions.push({ description: description, key: key });
21794 if (path.stopKey === key) {
21798 instructionPlaces.push({ nodeInstructions: nodeInstructions, place: i });
21802 return instructionPlaces;
21803 }).scan(function (routeTrack, instructionPlaces) {
21804 for (var _i = 0, instructionPlaces_1 = instructionPlaces; _i < instructionPlaces_1.length; _i++) {
21805 var instructionPlace = instructionPlaces_1[_i];
21806 routeTrack.nodeInstructionsOrdered[instructionPlace.place] = instructionPlace.nodeInstructions;
21808 routeTrack.nodeInstructions = _.flatten(routeTrack.nodeInstructionsOrdered);
21810 }, new RouteTrack());
21811 this._disposable = _slowedStream$
21812 .combineLatest(_routeTrack$, this.configuration$, function (frame, routeTrack, conf) {
21813 return { conf: conf, frame: frame, routeTrack: routeTrack };
21814 }).scan(function (routeState, rtAndFrame) {
21815 if (rtAndFrame.conf.playing === undefined || rtAndFrame.conf.playing) {
21816 routeState.routeTrack = rtAndFrame.routeTrack;
21817 routeState.currentNode = rtAndFrame.frame.state.currentNode;
21818 routeState.lastNode = rtAndFrame.frame.state.lastNode;
21819 routeState.playing = true;
21822 _this._navigator.stateService.cutNodes();
21823 routeState.playing = false;
21826 }, new RouteState())
21827 .filter(function (routeState) {
21828 return routeState.playing;
21829 }).filter(function (routeState) {
21830 for (var _i = 0, _a = routeState.routeTrack.nodeInstructions; _i < _a.length; _i++) {
21831 var nodeInstruction = _a[_i];
21832 if (!nodeInstruction) {
21835 if (nodeInstruction.key === routeState.lastNode.key) {
21840 }).distinctUntilChanged(undefined, function (routeState) {
21841 return routeState.lastNode.key;
21842 }).mergeMap(function (routeState) {
21844 for (var _i = 0, _a = routeState.routeTrack.nodeInstructions; _i < _a.length; _i++) {
21845 var nodeInstruction = _a[_i];
21846 if (nodeInstruction.key === routeState.lastNode.key) {
21851 var nextInstruction = routeState.routeTrack.nodeInstructions[i + 1];
21852 if (!nextInstruction) {
21853 return Observable_1.Observable.of(null);
21855 return _this._navigator.graphService.cacheNode$(nextInstruction.key);
21856 }).combineLatest(this.configuration$, function (node, conf) {
21857 return { conf: conf, node: node };
21858 }).filter(function (cAN) {
21859 return cAN.node !== null && cAN.conf.playing;
21860 }).pluck("node").subscribe(this._navigator.stateService.appendNode$);
21861 this._disposableDescription = this._navigator.stateService.currentNode$
21862 .combineLatest(_routeTrack$, this.configuration$, function (node, routeTrack, conf) {
21863 if (conf.playing !== undefined && !conf.playing) {
21866 var description = null;
21867 for (var _i = 0, _a = routeTrack.nodeInstructions; _i < _a.length; _i++) {
21868 var nodeInstruction = _a[_i];
21869 if (nodeInstruction.key === node.key) {
21870 description = nodeInstruction.description;
21874 return description;
21875 }).scan(function (descriptionState, description) {
21876 if (description !== descriptionState.description && description !== null) {
21877 descriptionState.description = description;
21878 descriptionState.showsLeft = 6;
21881 descriptionState.showsLeft--;
21883 if (description === "quit") {
21884 descriptionState.description = null;
21886 return descriptionState;
21887 }, new DescriptionState()).map(function (descriptionState) {
21888 if (descriptionState.showsLeft > 0 && descriptionState.description) {
21889 return { name: _this._name, vnode: _this._getRouteAnnotationNode(descriptionState.description) };
21892 return { name: _this._name, vnode: vd.h("div", []) };
21894 }).subscribe(this._container.domRenderer.render$);
21896 RouteComponent.prototype._deactivate = function () {
21897 this._disposable.unsubscribe();
21898 this._disposableDescription.unsubscribe();
21900 RouteComponent.prototype._getDefaultConfiguration = function () {
21903 RouteComponent.prototype.play = function () {
21904 this.configure({ playing: true });
21906 RouteComponent.prototype.stop = function () {
21907 this.configure({ playing: false });
21909 RouteComponent.prototype._getRouteAnnotationNode = function (description) {
21910 return vd.h("div.RouteFrame", {}, [
21911 vd.h("p", { textContent: description }, []),
21914 RouteComponent.componentName = "route";
21915 return RouteComponent;
21916 }(Component_1.Component));
21917 exports.RouteComponent = RouteComponent;
21918 Component_1.ComponentService.register(RouteComponent);
21919 exports.default = RouteComponent;
21921 },{"../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){
21923 var __extends = (this && this.__extends) || (function () {
21924 var extendStatics = Object.setPrototypeOf ||
21925 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21926 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
21927 return function (d, b) {
21928 extendStatics(d, b);
21929 function __() { this.constructor = d; }
21930 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
21933 Object.defineProperty(exports, "__esModule", { value: true });
21934 var Observable_1 = require("rxjs/Observable");
21935 require("rxjs/add/operator/buffer");
21936 require("rxjs/add/operator/debounceTime");
21937 require("rxjs/add/operator/filter");
21938 require("rxjs/add/operator/map");
21939 require("rxjs/add/operator/scan");
21940 var Component_1 = require("../Component");
21941 var StatsComponent = (function (_super) {
21942 __extends(StatsComponent, _super);
21943 function StatsComponent(name, container, navigator) {
21944 return _super.call(this, name, container, navigator) || this;
21946 StatsComponent.prototype._activate = function () {
21948 this._sequenceSubscription = this._navigator.stateService.currentNode$
21949 .scan(function (keys, node) {
21950 var sKey = node.sequenceKey;
21952 if (!(sKey in keys.reported)) {
21953 keys.report = [sKey];
21954 keys.reported[sKey] = true;
21957 }, { report: [], reported: {} })
21958 .filter(function (keys) {
21959 return keys.report.length > 0;
21961 .mergeMap(function (keys) {
21962 return _this._navigator.apiV3.sequenceViewAdd$(keys.report)
21963 .catch(function (error, caught) {
21964 console.error("Failed to report sequence stats (" + keys.report + ")", error);
21965 return Observable_1.Observable.empty();
21968 .subscribe(function () { });
21969 this._imageSubscription = this._navigator.stateService.currentNode$
21970 .map(function (node) {
21973 .buffer(this._navigator.stateService.currentNode$.debounceTime(5000))
21974 .scan(function (keys, newKeys) {
21976 for (var _i = 0, newKeys_1 = newKeys; _i < newKeys_1.length; _i++) {
21977 var key = newKeys_1[_i];
21978 if (!(key in keys.reported)) {
21979 keys.report.push(key);
21980 keys.reported[key] = true;
21984 }, { report: [], reported: {} })
21985 .filter(function (keys) {
21986 return keys.report.length > 0;
21988 .mergeMap(function (keys) {
21989 return _this._navigator.apiV3.imageViewAdd$(keys.report)
21990 .catch(function (error, caught) {
21991 console.error("Failed to report image stats (" + keys.report + ")", error);
21992 return Observable_1.Observable.empty();
21995 .subscribe(function () { });
21997 StatsComponent.prototype._deactivate = function () {
21998 this._sequenceSubscription.unsubscribe();
21999 this._imageSubscription.unsubscribe();
22001 StatsComponent.prototype._getDefaultConfiguration = function () {
22004 StatsComponent.componentName = "stats";
22005 return StatsComponent;
22006 }(Component_1.Component));
22007 exports.StatsComponent = StatsComponent;
22008 Component_1.ComponentService.register(StatsComponent);
22009 exports.default = StatsComponent;
22011 },{"../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){
22013 /// <reference path="../../../typings/index.d.ts" />
22014 var __extends = (this && this.__extends) || (function () {
22015 var extendStatics = Object.setPrototypeOf ||
22016 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
22017 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
22018 return function (d, b) {
22019 extendStatics(d, b);
22020 function __() { this.constructor = d; }
22021 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22024 Object.defineProperty(exports, "__esModule", { value: true });
22025 var vd = require("virtual-dom");
22026 var Observable_1 = require("rxjs/Observable");
22027 var Subject_1 = require("rxjs/Subject");
22028 require("rxjs/add/observable/combineLatest");
22029 require("rxjs/add/operator/do");
22030 require("rxjs/add/operator/distinctUntilChanged");
22031 require("rxjs/add/operator/filter");
22032 require("rxjs/add/operator/map");
22033 require("rxjs/add/operator/share");
22034 var Component_1 = require("../../Component");
22036 * @class DirectionComponent
22037 * @classdesc Component showing navigation arrows for steps and turns.
22039 var DirectionComponent = (function (_super) {
22040 __extends(DirectionComponent, _super);
22041 function DirectionComponent(name, container, navigator) {
22042 var _this = _super.call(this, name, container, navigator) || this;
22043 _this._renderer = new Component_1.DirectionDOMRenderer(_this.defaultConfiguration, container.element);
22044 _this._hoveredKeySubject$ = new Subject_1.Subject();
22045 _this._hoveredKey$ = _this._hoveredKeySubject$.share();
22048 Object.defineProperty(DirectionComponent.prototype, "hoveredKey$", {
22050 * Get hovered key observable.
22052 * @description An observable emitting the key of the node for the direction
22053 * arrow that is being hovered. When the mouse leaves a direction arrow null
22056 * @returns {Observable<string>}
22059 return this._hoveredKey$;
22065 * Set highlight key.
22067 * @description The arrow pointing towards the node corresponding to the
22068 * highlight key will be highlighted.
22070 * @param {string} highlightKey Key of node to be highlighted if existing
22073 DirectionComponent.prototype.setHighlightKey = function (highlightKey) {
22074 this.configure({ highlightKey: highlightKey });
22077 * Set min width of container element.
22079 * @description Set min width of the non transformed container element holding
22080 * the navigation arrows. If the min width is larger than the max width the
22081 * min width value will be used.
22083 * The container element is automatically resized when the resize
22084 * method on the Viewer class is called.
22086 * @param {number} minWidth
22088 DirectionComponent.prototype.setMinWidth = function (minWidth) {
22089 this.configure({ minWidth: minWidth });
22092 * Set max width of container element.
22094 * @description Set max width of the non transformed container element holding
22095 * the navigation arrows. If the min width is larger than the max width the
22096 * min width value will be used.
22098 * The container element is automatically resized when the resize
22099 * method on the Viewer class is called.
22101 * @param {number} minWidth
22103 DirectionComponent.prototype.setMaxWidth = function (maxWidth) {
22104 this.configure({ maxWidth: maxWidth });
22107 DirectionComponent.prototype.resize = function () {
22108 this._renderer.resize(this._container.element);
22110 DirectionComponent.prototype._activate = function () {
22112 this._configurationSubscription = this._configuration$
22113 .subscribe(function (configuration) {
22114 _this._renderer.setConfiguration(configuration);
22116 this._nodeSubscription = this._navigator.stateService.currentNode$
22117 .do(function (node) {
22118 _this._container.domRenderer.render$.next({ name: _this._name, vnode: vd.h("div", {}, []) });
22119 _this._renderer.setNode(node);
22121 .withLatestFrom(this._configuration$)
22122 .switchMap(function (nc) {
22124 var configuration = nc[1];
22125 return node.spatialEdges$
22126 .withLatestFrom(configuration.distinguishSequence ?
22127 _this._navigator.graphService
22128 .cacheSequence$(node.sequenceKey)
22129 .catch(function (error, caught) {
22130 console.error("Failed to cache sequence (" + node.sequenceKey + ")", error);
22131 return Observable_1.Observable.empty();
22133 Observable_1.Observable.of(null));
22135 .subscribe(function (es) {
22136 _this._renderer.setEdges(es[0], es[1]);
22138 this._renderCameraSubscription = this._container.renderService.renderCameraFrame$
22139 .do(function (renderCamera) {
22140 _this._renderer.setRenderCamera(renderCamera);
22142 .map(function (renderCamera) {
22143 return _this._renderer;
22145 .filter(function (renderer) {
22146 return renderer.needsRender;
22148 .map(function (renderer) {
22149 return { name: _this._name, vnode: renderer.render(_this._navigator) };
22151 .subscribe(this._container.domRenderer.render$);
22152 this._hoveredKeySubscription = Observable_1.Observable
22154 this._container.domRenderer.element$,
22155 this._container.renderService.renderCamera$,
22156 this._container.mouseService.mouseMove$.startWith(null),
22157 this._container.mouseService.mouseUp$.startWith(null),
22158 ], function (e, rc, mm, mu) {
22161 .map(function (element) {
22162 var elements = element.getElementsByClassName("DirectionsPerspective");
22163 for (var i = 0; i < elements.length; i++) {
22164 var hovered = elements.item(i).querySelector(":hover");
22165 if (hovered != null && hovered.hasAttribute("data-key")) {
22166 return hovered.getAttribute("data-key");
22171 .distinctUntilChanged()
22172 .subscribe(this._hoveredKeySubject$);
22174 DirectionComponent.prototype._deactivate = function () {
22175 this._configurationSubscription.unsubscribe();
22176 this._nodeSubscription.unsubscribe();
22177 this._renderCameraSubscription.unsubscribe();
22178 this._hoveredKeySubscription.unsubscribe();
22180 DirectionComponent.prototype._getDefaultConfiguration = function () {
22182 distinguishSequence: false,
22188 DirectionComponent.componentName = "direction";
22189 return DirectionComponent;
22190 }(Component_1.Component));
22191 exports.DirectionComponent = DirectionComponent;
22192 Component_1.ComponentService.register(DirectionComponent);
22193 exports.default = DirectionComponent;
22195 },{"../../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){
22197 Object.defineProperty(exports, "__esModule", { value: true });
22198 var Geo_1 = require("../../Geo");
22200 * @class DirectionDOMCalculator
22201 * @classdesc Helper class for calculating DOM CSS properties.
22203 var DirectionDOMCalculator = (function () {
22204 function DirectionDOMCalculator(configuration, element) {
22205 this._spatial = new Geo_1.Spatial();
22206 this._minThresholdWidth = 320;
22207 this._maxThresholdWidth = 1480;
22208 this._minThresholdHeight = 240;
22209 this._maxThresholdHeight = 820;
22210 this._configure(configuration);
22211 this._resize(element);
22214 Object.defineProperty(DirectionDOMCalculator.prototype, "minWidth", {
22216 return this._minWidth;
22221 Object.defineProperty(DirectionDOMCalculator.prototype, "maxWidth", {
22223 return this._maxWidth;
22228 Object.defineProperty(DirectionDOMCalculator.prototype, "containerWidth", {
22230 return this._containerWidth;
22235 Object.defineProperty(DirectionDOMCalculator.prototype, "containerWidthCss", {
22237 return this._containerWidthCss;
22242 Object.defineProperty(DirectionDOMCalculator.prototype, "containerMarginCss", {
22244 return this._containerMarginCss;
22249 Object.defineProperty(DirectionDOMCalculator.prototype, "containerLeftCss", {
22251 return this._containerLeftCss;
22256 Object.defineProperty(DirectionDOMCalculator.prototype, "containerHeight", {
22258 return this._containerHeight;
22263 Object.defineProperty(DirectionDOMCalculator.prototype, "containerHeightCss", {
22265 return this._containerHeightCss;
22270 Object.defineProperty(DirectionDOMCalculator.prototype, "containerBottomCss", {
22272 return this._containerBottomCss;
22277 Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleSize", {
22279 return this._stepCircleSize;
22284 Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleSizeCss", {
22286 return this._stepCircleSizeCss;
22291 Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleMarginCss", {
22293 return this._stepCircleMarginCss;
22298 Object.defineProperty(DirectionDOMCalculator.prototype, "turnCircleSize", {
22300 return this._turnCircleSize;
22305 Object.defineProperty(DirectionDOMCalculator.prototype, "turnCircleSizeCss", {
22307 return this._turnCircleSizeCss;
22312 Object.defineProperty(DirectionDOMCalculator.prototype, "outerRadius", {
22314 return this._outerRadius;
22319 Object.defineProperty(DirectionDOMCalculator.prototype, "innerRadius", {
22321 return this._innerRadius;
22326 Object.defineProperty(DirectionDOMCalculator.prototype, "shadowOffset", {
22328 return this._shadowOffset;
22334 * Configures the min and max width values.
22336 * @param {IDirectionConfiguration} configuration Configuration
22337 * with min and max width values.
22339 DirectionDOMCalculator.prototype.configure = function (configuration) {
22340 this._configure(configuration);
22344 * Resizes all properties according to the width and height
22347 * @param {HTMLElement} element The container element from which to extract
22348 * the width and height.
22350 DirectionDOMCalculator.prototype.resize = function (element) {
22351 this._resize(element);
22355 * Calculates the coordinates on the unit circle for an angle.
22357 * @param {number} angle Angle in radians.
22358 * @returns {Array<number>} The x and y coordinates on the unit circle.
22360 DirectionDOMCalculator.prototype.angleToCoordinates = function (angle) {
22361 return [Math.cos(angle), Math.sin(angle)];
22364 * Calculates the coordinates on the unit circle for the
22365 * relative angle between the first and second angle.
22367 * @param {number} first Angle in radians.
22368 * @param {number} second Angle in radians.
22369 * @returns {Array<number>} The x and y coordinates on the unit circle
22370 * for the relative angle between the first and second angle.
22372 DirectionDOMCalculator.prototype.relativeAngleToCoordiantes = function (first, second) {
22373 var relativeAngle = this._spatial.wrapAngle(first - second);
22374 return this.angleToCoordinates(relativeAngle);
22376 DirectionDOMCalculator.prototype._configure = function (configuration) {
22377 this._minWidth = configuration.minWidth;
22378 this._maxWidth = this._getMaxWidth(configuration.minWidth, configuration.maxWidth);
22380 DirectionDOMCalculator.prototype._resize = function (element) {
22381 this._elementWidth = element.offsetWidth;
22382 this._elementHeight = element.offsetHeight;
22384 DirectionDOMCalculator.prototype._reset = function () {
22385 this._containerWidth = this._getContainerWidth(this._elementWidth, this._elementHeight);
22386 this._containerHeight = this._getContainerHeight(this.containerWidth);
22387 this._stepCircleSize = this._getStepCircleDiameter(this._containerHeight);
22388 this._turnCircleSize = this._getTurnCircleDiameter(this.containerHeight);
22389 this._outerRadius = this._getOuterRadius(this._containerHeight);
22390 this._innerRadius = this._getInnerRadius(this._containerHeight);
22391 this._shadowOffset = 3;
22392 this._containerWidthCss = this._numberToCssPixels(this._containerWidth);
22393 this._containerMarginCss = this._numberToCssPixels(-0.5 * this._containerWidth);
22394 this._containerLeftCss = this._numberToCssPixels(Math.floor(0.5 * this._elementWidth));
22395 this._containerHeightCss = this._numberToCssPixels(this._containerHeight);
22396 this._containerBottomCss = this._numberToCssPixels(Math.floor(-0.08 * this._containerHeight));
22397 this._stepCircleSizeCss = this._numberToCssPixels(this._stepCircleSize);
22398 this._stepCircleMarginCss = this._numberToCssPixels(-0.5 * this._stepCircleSize);
22399 this._turnCircleSizeCss = this._numberToCssPixels(this._turnCircleSize);
22401 DirectionDOMCalculator.prototype._getContainerWidth = function (elementWidth, elementHeight) {
22402 var relativeWidth = (elementWidth - this._minThresholdWidth) / (this._maxThresholdWidth - this._minThresholdWidth);
22403 var relativeHeight = (elementHeight - this._minThresholdHeight) / (this._maxThresholdHeight - this._minThresholdHeight);
22404 var coeff = Math.max(0, Math.min(1, Math.min(relativeWidth, relativeHeight)));
22405 coeff = 0.04 * Math.round(25 * coeff);
22406 return this._minWidth + coeff * (this._maxWidth - this._minWidth);
22408 DirectionDOMCalculator.prototype._getContainerHeight = function (containerWidth) {
22409 return 0.77 * containerWidth;
22411 DirectionDOMCalculator.prototype._getStepCircleDiameter = function (containerHeight) {
22412 return 0.34 * containerHeight;
22414 DirectionDOMCalculator.prototype._getTurnCircleDiameter = function (containerHeight) {
22415 return 0.3 * containerHeight;
22417 DirectionDOMCalculator.prototype._getOuterRadius = function (containerHeight) {
22418 return 0.31 * containerHeight;
22420 DirectionDOMCalculator.prototype._getInnerRadius = function (containerHeight) {
22421 return 0.125 * containerHeight;
22423 DirectionDOMCalculator.prototype._numberToCssPixels = function (value) {
22424 return value + "px";
22426 DirectionDOMCalculator.prototype._getMaxWidth = function (value, minWidth) {
22427 return value > minWidth ? value : minWidth;
22429 return DirectionDOMCalculator;
22431 exports.DirectionDOMCalculator = DirectionDOMCalculator;
22432 exports.default = DirectionDOMCalculator;
22434 },{"../../Geo":229}],255:[function(require,module,exports){
22436 /// <reference path="../../../typings/index.d.ts" />
22437 Object.defineProperty(exports, "__esModule", { value: true });
22438 var vd = require("virtual-dom");
22439 var Component_1 = require("../../Component");
22440 var Edge_1 = require("../../Edge");
22441 var Geo_1 = require("../../Geo");
22443 * @class DirectionDOMRenderer
22444 * @classdesc DOM renderer for direction arrows.
22446 var DirectionDOMRenderer = (function () {
22447 function DirectionDOMRenderer(configuration, element) {
22448 this._isEdge = false;
22449 this._spatial = new Geo_1.Spatial();
22450 this._calculator = new Component_1.DirectionDOMCalculator(configuration, element);
22452 this._rotation = { phi: 0, theta: 0 };
22453 this._epsilon = 0.5 * Math.PI / 180;
22454 this._highlightKey = null;
22455 this._distinguishSequence = false;
22456 this._needsRender = false;
22457 this._stepEdges = [];
22458 this._turnEdges = [];
22459 this._panoEdges = [];
22460 this._sequenceEdgeKeys = [];
22461 this._stepDirections = [
22462 Edge_1.EdgeDirection.StepForward,
22463 Edge_1.EdgeDirection.StepBackward,
22464 Edge_1.EdgeDirection.StepLeft,
22465 Edge_1.EdgeDirection.StepRight,
22467 this._turnDirections = [
22468 Edge_1.EdgeDirection.TurnLeft,
22469 Edge_1.EdgeDirection.TurnRight,
22470 Edge_1.EdgeDirection.TurnU,
22472 this._turnNames = {};
22473 this._turnNames[Edge_1.EdgeDirection.TurnLeft] = "TurnLeft";
22474 this._turnNames[Edge_1.EdgeDirection.TurnRight] = "TurnRight";
22475 this._turnNames[Edge_1.EdgeDirection.TurnU] = "TurnAround";
22476 // detects IE 8-11, then Edge 20+.
22477 var isIE = !!document.documentMode;
22478 this._isEdge = !isIE && !!window.StyleMedia;
22480 Object.defineProperty(DirectionDOMRenderer.prototype, "needsRender", {
22482 * Get needs render.
22484 * @returns {boolean} Value indicating whether render should be called.
22487 return this._needsRender;
22493 * Renders virtual DOM elements.
22495 * @description Calling render resets the needs render property.
22497 DirectionDOMRenderer.prototype.render = function (navigator) {
22498 this._needsRender = false;
22499 var rotation = this._rotation;
22502 if (this._node.pano) {
22503 steps = steps.concat(this._createPanoArrows(navigator, rotation));
22506 steps = steps.concat(this._createPerspectiveToPanoArrows(navigator, rotation));
22507 steps = steps.concat(this._createStepArrows(navigator, rotation));
22508 turns = turns.concat(this._createTurnArrows(navigator));
22510 return this._getContainer(steps, turns, rotation);
22512 DirectionDOMRenderer.prototype.setEdges = function (edgeStatus, sequence) {
22513 this._setEdges(edgeStatus, sequence);
22514 this._setNeedsRender();
22517 * Set node for which to show edges.
22519 * @param {Node} node
22521 DirectionDOMRenderer.prototype.setNode = function (node) {
22523 this._clearEdges();
22524 this._setNeedsRender();
22527 * Set the render camera to use for calculating rotations.
22529 * @param {RenderCamera} renderCamera
22531 DirectionDOMRenderer.prototype.setRenderCamera = function (renderCamera) {
22532 var rotation = renderCamera.rotation;
22533 if (Math.abs(rotation.phi - this._rotation.phi) < this._epsilon) {
22536 this._rotation = rotation;
22537 this._setNeedsRender();
22540 * Set configuration values.
22542 * @param {IDirectionConfiguration} configuration
22544 DirectionDOMRenderer.prototype.setConfiguration = function (configuration) {
22545 var needsRender = false;
22546 if (this._highlightKey !== configuration.highlightKey ||
22547 this._distinguishSequence !== configuration.distinguishSequence) {
22548 this._highlightKey = configuration.highlightKey;
22549 this._distinguishSequence = configuration.distinguishSequence;
22550 needsRender = true;
22552 if (this._calculator.minWidth !== configuration.minWidth ||
22553 this._calculator.maxWidth !== configuration.maxWidth) {
22554 this._calculator.configure(configuration);
22555 needsRender = true;
22558 this._setNeedsRender();
22562 * Detect the element's width and height and resize
22563 * elements accordingly.
22565 * @param {HTMLElement} element Viewer container element.
22567 DirectionDOMRenderer.prototype.resize = function (element) {
22568 this._calculator.resize(element);
22569 this._setNeedsRender();
22571 DirectionDOMRenderer.prototype._setNeedsRender = function () {
22572 if (this._node != null) {
22573 this._needsRender = true;
22576 DirectionDOMRenderer.prototype._clearEdges = function () {
22577 this._stepEdges = [];
22578 this._turnEdges = [];
22579 this._panoEdges = [];
22580 this._sequenceEdgeKeys = [];
22582 DirectionDOMRenderer.prototype._setEdges = function (edgeStatus, sequence) {
22583 this._stepEdges = [];
22584 this._turnEdges = [];
22585 this._panoEdges = [];
22586 this._sequenceEdgeKeys = [];
22587 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
22589 var direction = edge.data.direction;
22590 if (this._stepDirections.indexOf(direction) > -1) {
22591 this._stepEdges.push(edge);
22594 if (this._turnDirections.indexOf(direction) > -1) {
22595 this._turnEdges.push(edge);
22598 if (edge.data.direction === Edge_1.EdgeDirection.Pano) {
22599 this._panoEdges.push(edge);
22602 if (this._distinguishSequence && sequence != null) {
22603 var edges = this._panoEdges
22604 .concat(this._stepEdges)
22605 .concat(this._turnEdges);
22606 for (var _b = 0, edges_1 = edges; _b < edges_1.length; _b++) {
22607 var edge = edges_1[_b];
22608 var edgeKey = edge.to;
22609 for (var _c = 0, _d = sequence.keys; _c < _d.length; _c++) {
22610 var sequenceKey = _d[_c];
22611 if (sequenceKey === edgeKey) {
22612 this._sequenceEdgeKeys.push(edgeKey);
22619 DirectionDOMRenderer.prototype._createPanoArrows = function (navigator, rotation) {
22621 for (var _i = 0, _a = this._panoEdges; _i < _a.length; _i++) {
22622 var panoEdge = _a[_i];
22623 arrows.push(this._createVNodeByKey(navigator, panoEdge.to, panoEdge.data.worldMotionAzimuth, rotation, this._calculator.outerRadius, "DirectionsArrowPano"));
22625 for (var _b = 0, _c = this._stepEdges; _b < _c.length; _b++) {
22626 var stepEdge = _c[_b];
22627 arrows.push(this._createPanoToPerspectiveArrow(navigator, stepEdge.to, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction));
22631 DirectionDOMRenderer.prototype._createPanoToPerspectiveArrow = function (navigator, key, azimuth, rotation, direction) {
22632 var threshold = Math.PI / 8;
22633 var relativePhi = rotation.phi;
22634 switch (direction) {
22635 case Edge_1.EdgeDirection.StepBackward:
22636 relativePhi = rotation.phi - Math.PI;
22638 case Edge_1.EdgeDirection.StepLeft:
22639 relativePhi = rotation.phi + Math.PI / 2;
22641 case Edge_1.EdgeDirection.StepRight:
22642 relativePhi = rotation.phi - Math.PI / 2;
22647 if (Math.abs(this._spatial.wrapAngle(azimuth - relativePhi)) < threshold) {
22648 return this._createVNodeByKey(navigator, key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowStep");
22650 return this._createVNodeDisabled(key, azimuth, rotation);
22652 DirectionDOMRenderer.prototype._createPerspectiveToPanoArrows = function (navigator, rotation) {
22654 for (var _i = 0, _a = this._panoEdges; _i < _a.length; _i++) {
22655 var panoEdge = _a[_i];
22656 arrows.push(this._createVNodeByKey(navigator, panoEdge.to, panoEdge.data.worldMotionAzimuth, rotation, this._calculator.innerRadius, "DirectionsArrowPano", true));
22660 DirectionDOMRenderer.prototype._createStepArrows = function (navigator, rotation) {
22662 for (var _i = 0, _a = this._stepEdges; _i < _a.length; _i++) {
22663 var stepEdge = _a[_i];
22664 arrows.push(this._createVNodeByDirection(navigator, stepEdge.to, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction));
22668 DirectionDOMRenderer.prototype._createTurnArrows = function (navigator) {
22670 for (var _i = 0, _a = this._turnEdges; _i < _a.length; _i++) {
22671 var turnEdge = _a[_i];
22672 var direction = turnEdge.data.direction;
22673 var name_1 = this._turnNames[direction];
22674 turns.push(this._createVNodeByTurn(navigator, turnEdge.to, name_1, direction));
22678 DirectionDOMRenderer.prototype._createVNodeByKey = function (navigator, key, azimuth, rotation, offset, className, shiftVertically) {
22679 var onClick = function (e) {
22680 navigator.moveToKey$(key)
22681 .subscribe(function (node) { return; }, function (error) { console.error(error); });
22683 return this._createVNode(key, azimuth, rotation, offset, className, "DirectionsCircle", onClick, shiftVertically);
22685 DirectionDOMRenderer.prototype._createVNodeByDirection = function (navigator, key, azimuth, rotation, direction) {
22686 var onClick = function (e) {
22687 navigator.moveDir$(direction)
22688 .subscribe(function (node) { return; }, function (error) { console.error(error); });
22690 return this._createVNode(key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowStep", "DirectionsCircle", onClick);
22692 DirectionDOMRenderer.prototype._createVNodeByTurn = function (navigator, key, className, direction) {
22693 var onClick = function (e) {
22694 navigator.moveDir$(direction)
22695 .subscribe(function (node) { return; }, function (error) { console.error(error); });
22698 height: this._calculator.turnCircleSizeCss,
22699 transform: "rotate(0)",
22700 width: this._calculator.turnCircleSizeCss,
22702 switch (direction) {
22703 case Edge_1.EdgeDirection.TurnLeft:
22704 style.left = "5px";
22707 case Edge_1.EdgeDirection.TurnRight:
22708 style.right = "5px";
22711 case Edge_1.EdgeDirection.TurnU:
22712 style.left = "5px";
22713 style.bottom = "5px";
22718 var circleProperties = {
22725 var circleClassName = "TurnCircle";
22726 if (this._sequenceEdgeKeys.indexOf(key) > -1) {
22727 circleClassName += "Sequence";
22729 if (this._highlightKey === key) {
22730 circleClassName += "Highlight";
22732 var turn = vd.h("div." + className, {}, []);
22733 return vd.h("div." + circleClassName, circleProperties, [turn]);
22735 DirectionDOMRenderer.prototype._createVNodeDisabled = function (key, azimuth, rotation) {
22736 return this._createVNode(key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowDisabled", "DirectionsCircleDisabled");
22738 DirectionDOMRenderer.prototype._createVNode = function (key, azimuth, rotation, radius, className, circleClassName, onClick, shiftVertically) {
22739 var translation = this._calculator.angleToCoordinates(azimuth - rotation.phi);
22740 // rotate 90 degrees clockwise and flip over X-axis
22741 var translationX = Math.round(-radius * translation[1] + 0.5 * this._calculator.containerWidth);
22742 var translationY = Math.round(-radius * translation[0] + 0.5 * this._calculator.containerHeight);
22743 var shadowTranslation = this._calculator.relativeAngleToCoordiantes(azimuth, rotation.phi);
22744 var shadowOffset = this._calculator.shadowOffset;
22745 var shadowTranslationX = -shadowOffset * shadowTranslation[1];
22746 var shadowTranslationY = shadowOffset * shadowTranslation[0];
22747 var filter = "drop-shadow(" + shadowTranslationX + "px " + shadowTranslationY + "px 1px rgba(0,0,0,0.8))";
22750 "-webkit-filter": filter,
22754 var chevron = vd.h("div." + className, properties, []);
22755 var azimuthDeg = -this._spatial.radToDeg(azimuth - rotation.phi);
22756 var circleTransform = shiftVertically ?
22757 "translate(" + translationX + "px, " + translationY + "px) rotate(" + azimuthDeg + "deg) translateZ(-0.01px)" :
22758 "translate(" + translationX + "px, " + translationY + "px) rotate(" + azimuthDeg + "deg)";
22759 var circleProperties = {
22760 attributes: { "data-key": key },
22763 height: this._calculator.stepCircleSizeCss,
22764 marginLeft: this._calculator.stepCircleMarginCss,
22765 marginTop: this._calculator.stepCircleMarginCss,
22766 transform: circleTransform,
22767 width: this._calculator.stepCircleSizeCss,
22770 if (this._sequenceEdgeKeys.indexOf(key) > -1) {
22771 circleClassName += "Sequence";
22773 if (this._highlightKey === key) {
22774 circleClassName += "Highlight";
22776 return vd.h("div." + circleClassName, circleProperties, [chevron]);
22778 DirectionDOMRenderer.prototype._getContainer = function (steps, turns, rotation) {
22779 // edge does not handle hover on perspective transforms.
22780 var transform = this._isEdge ?
22782 "perspective(" + this._calculator.containerWidthCss + ") rotateX(60deg)";
22784 oncontextmenu: function (event) { event.preventDefault(); },
22786 bottom: this._calculator.containerBottomCss,
22787 height: this._calculator.containerHeightCss,
22788 left: this._calculator.containerLeftCss,
22789 marginLeft: this._calculator.containerMarginCss,
22790 transform: transform,
22791 width: this._calculator.containerWidthCss,
22794 return vd.h("div.DirectionsPerspective", properties, turns.concat(steps));
22796 return DirectionDOMRenderer;
22798 exports.DirectionDOMRenderer = DirectionDOMRenderer;
22799 exports.default = DirectionDOMRenderer;
22801 },{"../../Component":226,"../../Edge":227,"../../Geo":229,"virtual-dom":182}],256:[function(require,module,exports){
22803 var __extends = (this && this.__extends) || (function () {
22804 var extendStatics = Object.setPrototypeOf ||
22805 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
22806 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
22807 return function (d, b) {
22808 extendStatics(d, b);
22809 function __() { this.constructor = d; }
22810 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
22813 Object.defineProperty(exports, "__esModule", { value: true });
22814 var Observable_1 = require("rxjs/Observable");
22815 var Subject_1 = require("rxjs/Subject");
22816 require("rxjs/add/operator/catch");
22817 require("rxjs/add/operator/combineLatest");
22818 require("rxjs/add/operator/debounceTime");
22819 require("rxjs/add/operator/distinctUntilChanged");
22820 require("rxjs/add/operator/filter");
22821 require("rxjs/add/operator/map");
22822 require("rxjs/add/operator/pairwise");
22823 require("rxjs/add/operator/publish");
22824 require("rxjs/add/operator/publishReplay");
22825 require("rxjs/add/operator/scan");
22826 require("rxjs/add/operator/skipWhile");
22827 require("rxjs/add/operator/startWith");
22828 require("rxjs/add/operator/switchMap");
22829 require("rxjs/add/operator/takeUntil");
22830 require("rxjs/add/operator/withLatestFrom");
22831 var Component_1 = require("../../Component");
22832 var Render_1 = require("../../Render");
22833 var Tiles_1 = require("../../Tiles");
22834 var Utils_1 = require("../../Utils");
22835 var ImagePlaneComponent = (function (_super) {
22836 __extends(ImagePlaneComponent, _super);
22837 function ImagePlaneComponent(name, container, navigator) {
22838 var _this = _super.call(this, name, container, navigator) || this;
22839 _this._imageTileLoader = new Tiles_1.ImageTileLoader(Utils_1.Urls.tileScheme, Utils_1.Urls.tileDomain, Utils_1.Urls.origin);
22840 _this._roiCalculator = new Tiles_1.RegionOfInterestCalculator();
22841 _this._rendererOperation$ = new Subject_1.Subject();
22842 _this._rendererCreator$ = new Subject_1.Subject();
22843 _this._rendererDisposer$ = new Subject_1.Subject();
22844 _this._renderer$ = _this._rendererOperation$
22845 .scan(function (renderer, operation) {
22846 return operation(renderer);
22848 .filter(function (renderer) {
22849 return renderer != null;
22851 .distinctUntilChanged(undefined, function (renderer) {
22852 return renderer.frameId;
22854 _this._rendererCreator$
22856 return function (renderer) {
22857 if (renderer != null) {
22858 throw new Error("Multiple image plane states can not be created at the same time");
22860 return new Component_1.ImagePlaneGLRenderer();
22863 .subscribe(_this._rendererOperation$);
22864 _this._rendererDisposer$
22866 return function (renderer) {
22867 renderer.dispose();
22871 .subscribe(_this._rendererOperation$);
22874 ImagePlaneComponent.prototype._activate = function () {
22876 this._rendererSubscription = this._renderer$
22877 .map(function (renderer) {
22881 frameId: renderer.frameId,
22882 needsRender: renderer.needsRender,
22883 render: renderer.render.bind(renderer),
22884 stage: Render_1.GLRenderStage.Background,
22887 renderer.clearNeedsRender();
22890 .subscribe(this._container.glRenderer.render$);
22891 this._rendererCreator$.next(null);
22892 this._stateSubscription = this._navigator.stateService.currentState$
22893 .map(function (frame) {
22894 return function (renderer) {
22895 renderer.updateFrame(frame);
22899 .subscribe(this._rendererOperation$);
22900 var textureProvider$ = this._navigator.stateService.currentState$
22901 .distinctUntilChanged(undefined, function (frame) {
22902 return frame.state.currentNode.key;
22904 .combineLatest(this._configuration$)
22905 .filter(function (args) {
22906 return args[1].imageTiling === true;
22908 .map(function (args) {
22911 .withLatestFrom(this._container.glRenderer.webGLRenderer$, this._container.renderService.size$)
22912 .map(function (args) {
22913 var state = args[0].state;
22914 var renderer = args[1];
22915 var viewportSize = args[2];
22916 var currentNode = state.currentNode;
22917 var currentTransform = state.currentTransform;
22918 var tileSize = Math.max(viewportSize.width, viewportSize.height) > 1024 ? 1024 : 512;
22919 return new Tiles_1.TextureProvider(currentNode.key, currentTransform.basicWidth, currentTransform.basicHeight, tileSize, currentNode.image, _this._imageTileLoader, new Tiles_1.ImageTileStore(), renderer);
22923 this._textureProviderSubscription = textureProvider$.subscribe(function () { });
22924 this._setTextureProviderSubscription = textureProvider$
22925 .map(function (provider) {
22926 return function (renderer) {
22927 renderer.setTextureProvider(provider.key, provider);
22931 .subscribe(this._rendererOperation$);
22932 this._abortTextureProviderSubscription = textureProvider$
22934 .subscribe(function (pair) {
22935 var previous = pair[0];
22938 var roiTrigger$ = this._container.renderService.renderCameraFrame$
22939 .map(function (renderCamera) {
22941 renderCamera.camera.position.clone(),
22942 renderCamera.camera.lookat.clone(),
22943 renderCamera.zoom.valueOf()
22947 .skipWhile(function (pls) {
22948 return pls[1][2] - pls[0][2] < 0 || pls[1][2] === 0;
22950 .map(function (pls) {
22951 var samePosition = pls[0][0].equals(pls[1][0]);
22952 var sameLookat = pls[0][1].equals(pls[1][1]);
22953 var sameZoom = pls[0][2] === pls[1][2];
22954 return samePosition && sameLookat && sameZoom;
22956 .distinctUntilChanged()
22957 .filter(function (stalled) {
22960 .switchMap(function (stalled) {
22961 return _this._container.renderService.renderCameraFrame$
22964 .withLatestFrom(this._container.renderService.size$, this._navigator.stateService.currentTransform$);
22965 this._setRegionOfInterestSubscription = textureProvider$
22966 .switchMap(function (provider) {
22968 .map(function (args) {
22970 _this._roiCalculator.computeRegionOfInterest(args[0], args[1], args[2]),
22975 .filter(function (args) {
22976 return !args[1].disposed;
22978 .subscribe(function (args) {
22980 var provider = args[1];
22981 provider.setRegionOfInterest(roi);
22983 var hasTexture$ = textureProvider$
22984 .switchMap(function (provider) {
22985 return provider.hasTexture$;
22990 this._hasTextureSubscription = hasTexture$.subscribe(function () { });
22991 var nodeImage$ = this._navigator.stateService.currentNode$
22992 .debounceTime(1000)
22993 .withLatestFrom(hasTexture$)
22994 .filter(function (args) {
22997 .map(function (args) {
23000 .filter(function (node) {
23002 Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize :
23003 Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize;
23005 .switchMap(function (node) {
23006 var baseImageSize = node.pano ?
23007 Utils_1.Settings.basePanoramaSize :
23008 Utils_1.Settings.baseImageSize;
23009 if (Math.max(node.image.width, node.image.height) > baseImageSize) {
23010 return Observable_1.Observable.empty();
23013 .cacheImage$(Utils_1.Settings.maxImageSize)
23014 .map(function (n) {
23015 return [n.image, n];
23018 .takeUntil(hasTexture$
23019 .filter(function (hasTexture) {
23022 .catch(function (error, caught) {
23023 console.error("Failed to fetch high res image (" + node.key + ")", error);
23024 return Observable_1.Observable.empty();
23029 this._updateBackgroundSubscription = nodeImage$
23030 .withLatestFrom(textureProvider$)
23031 .subscribe(function (args) {
23032 if (args[0][1].key !== args[1].key ||
23033 args[1].disposed) {
23036 args[1].updateBackground(args[0][0]);
23038 this._updateTextureImageSubscription = nodeImage$
23039 .map(function (imn) {
23040 return function (renderer) {
23041 renderer.updateTextureImage(imn[0], imn[1]);
23045 .subscribe(this._rendererOperation$);
23047 ImagePlaneComponent.prototype._deactivate = function () {
23048 this._rendererDisposer$.next(null);
23049 this._abortTextureProviderSubscription.unsubscribe();
23050 this._hasTextureSubscription.unsubscribe();
23051 this._rendererSubscription.unsubscribe();
23052 this._setRegionOfInterestSubscription.unsubscribe();
23053 this._setTextureProviderSubscription.unsubscribe();
23054 this._stateSubscription.unsubscribe();
23055 this._textureProviderSubscription.unsubscribe();
23056 this._updateBackgroundSubscription.unsubscribe();
23057 this._updateTextureImageSubscription.unsubscribe();
23059 ImagePlaneComponent.prototype._getDefaultConfiguration = function () {
23060 return { imageTiling: false };
23062 ImagePlaneComponent.componentName = "imagePlane";
23063 return ImagePlaneComponent;
23064 }(Component_1.Component));
23065 exports.ImagePlaneComponent = ImagePlaneComponent;
23066 Component_1.ComponentService.register(ImagePlaneComponent);
23067 exports.default = ImagePlaneComponent;
23069 },{"../../Component":226,"../../Render":232,"../../Tiles":234,"../../Utils":235,"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){
23071 /// <reference path="../../../typings/index.d.ts" />
23072 Object.defineProperty(exports, "__esModule", { value: true });
23073 var THREE = require("three");
23074 var Component_1 = require("../../Component");
23075 var ImagePlaneFactory = (function () {
23076 function ImagePlaneFactory(imagePlaneDepth, imageSphereRadius) {
23077 this._imagePlaneDepth = imagePlaneDepth != null ? imagePlaneDepth : 200;
23078 this._imageSphereRadius = imageSphereRadius != null ? imageSphereRadius : 200;
23080 ImagePlaneFactory.prototype.createMesh = function (node, transform) {
23081 var mesh = node.pano ?
23082 this._createImageSphere(node, transform) :
23083 this._createImagePlane(node, transform);
23086 ImagePlaneFactory.prototype._createImageSphere = function (node, transform) {
23087 var texture = this._createTexture(node.image);
23088 var materialParameters = this._createSphereMaterialParameters(transform, texture);
23089 var material = new THREE.ShaderMaterial(materialParameters);
23090 var mesh = this._useMesh(transform, node) ?
23091 new THREE.Mesh(this._getImageSphereGeo(transform, node), material) :
23092 new THREE.Mesh(this._getFlatImageSphereGeo(transform), material);
23095 ImagePlaneFactory.prototype._createImagePlane = function (node, transform) {
23096 var texture = this._createTexture(node.image);
23097 var materialParameters = this._createPlaneMaterialParameters(transform, texture);
23098 var material = new THREE.ShaderMaterial(materialParameters);
23099 var geometry = this._useMesh(transform, node) ?
23100 this._getImagePlaneGeo(transform, node) :
23101 this._getFlatImagePlaneGeo(transform);
23102 return new THREE.Mesh(geometry, material);
23104 ImagePlaneFactory.prototype._createSphereMaterialParameters = function (transform, texture) {
23105 var gpano = transform.gpano;
23106 var halfCroppedWidth = (gpano.FullPanoWidthPixels - gpano.CroppedAreaImageWidthPixels) / 2;
23107 var phiShift = 2 * Math.PI * (gpano.CroppedAreaLeftPixels - halfCroppedWidth) / gpano.FullPanoWidthPixels;
23108 var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels;
23109 var halfCroppedHeight = (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels) / 2;
23110 var thetaShift = Math.PI * (halfCroppedHeight - gpano.CroppedAreaTopPixels) / gpano.FullPanoHeightPixels;
23111 var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels;
23112 var materialParameters = {
23114 fragmentShader: Component_1.ImagePlaneShaders.equirectangular.fragment,
23115 side: THREE.DoubleSide,
23132 value: transform.rt,
23140 value: thetaLength,
23147 vertexShader: Component_1.ImagePlaneShaders.equirectangular.vertex,
23149 return materialParameters;
23151 ImagePlaneFactory.prototype._createPlaneMaterialParameters = function (transform, texture) {
23152 var materialParameters = {
23154 fragmentShader: Component_1.ImagePlaneShaders.perspective.fragment,
23155 side: THREE.DoubleSide,
23160 value: new THREE.Vector4(0, 0, 1, 1),
23168 value: transform.projectorMatrix(),
23175 vertexShader: Component_1.ImagePlaneShaders.perspective.vertex,
23177 return materialParameters;
23179 ImagePlaneFactory.prototype._createTexture = function (image) {
23180 var texture = new THREE.Texture(image);
23181 texture.minFilter = THREE.LinearFilter;
23182 texture.needsUpdate = true;
23185 ImagePlaneFactory.prototype._useMesh = function (transform, node) {
23186 return node.mesh.vertices.length && transform.hasValidScale;
23188 ImagePlaneFactory.prototype._getImageSphereGeo = function (transform, node) {
23189 var t = new THREE.Matrix4().getInverse(transform.srt);
23190 // push everything at least 5 meters in front of the camera
23191 var minZ = 5.0 * transform.scale;
23192 var maxZ = this._imageSphereRadius * transform.scale;
23193 var vertices = node.mesh.vertices;
23194 var numVertices = vertices.length / 3;
23195 var positions = new Float32Array(vertices.length);
23196 for (var i = 0; i < numVertices; ++i) {
23198 var x = vertices[index + 0];
23199 var y = vertices[index + 1];
23200 var z = vertices[index + 2];
23201 var l = Math.sqrt(x * x + y * y + z * z);
23202 var boundedL = Math.max(minZ, Math.min(l, maxZ));
23203 var factor = boundedL / l;
23204 var p = new THREE.Vector3(x * factor, y * factor, z * factor);
23206 positions[index + 0] = p.x;
23207 positions[index + 1] = p.y;
23208 positions[index + 2] = p.z;
23210 var faces = node.mesh.faces;
23211 var indices = new Uint16Array(faces.length);
23212 for (var i = 0; i < faces.length; ++i) {
23213 indices[i] = faces[i];
23215 var geometry = new THREE.BufferGeometry();
23216 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
23217 geometry.setIndex(new THREE.BufferAttribute(indices, 1));
23220 ImagePlaneFactory.prototype._getImagePlaneGeo = function (transform, node) {
23221 var t = new THREE.Matrix4().getInverse(transform.srt);
23222 // push everything at least 5 meters in front of the camera
23223 var minZ = 5.0 * transform.scale;
23224 var maxZ = this._imagePlaneDepth * transform.scale;
23225 var vertices = node.mesh.vertices;
23226 var numVertices = vertices.length / 3;
23227 var positions = new Float32Array(vertices.length);
23228 for (var i = 0; i < numVertices; ++i) {
23230 var x = vertices[index + 0];
23231 var y = vertices[index + 1];
23232 var z = vertices[index + 2];
23233 var boundedZ = Math.max(minZ, Math.min(z, maxZ));
23234 var factor = boundedZ / z;
23235 var p = new THREE.Vector3(x * factor, y * factor, boundedZ);
23237 positions[index + 0] = p.x;
23238 positions[index + 1] = p.y;
23239 positions[index + 2] = p.z;
23241 var faces = node.mesh.faces;
23242 var indices = new Uint16Array(faces.length);
23243 for (var i = 0; i < faces.length; ++i) {
23244 indices[i] = faces[i];
23246 var geometry = new THREE.BufferGeometry();
23247 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
23248 geometry.setIndex(new THREE.BufferAttribute(indices, 1));
23251 ImagePlaneFactory.prototype._getFlatImageSphereGeo = function (transform) {
23252 var gpano = transform.gpano;
23253 var phiStart = 2 * Math.PI * gpano.CroppedAreaLeftPixels / gpano.FullPanoWidthPixels;
23254 var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels;
23255 var thetaStart = Math.PI *
23256 (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels - gpano.CroppedAreaTopPixels) /
23257 gpano.FullPanoHeightPixels;
23258 var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels;
23259 var geometry = new THREE.SphereGeometry(this._imageSphereRadius, 20, 40, phiStart - Math.PI / 2, phiLength, thetaStart, thetaLength);
23260 geometry.applyMatrix(new THREE.Matrix4().getInverse(transform.rt));
23263 ImagePlaneFactory.prototype._getFlatImagePlaneGeo = function (transform) {
23264 var width = transform.width;
23265 var height = transform.height;
23266 var size = Math.max(width, height);
23267 var dx = width / 2.0 / size;
23268 var dy = height / 2.0 / size;
23270 vertices.push(transform.unprojectSfM([-dx, -dy], this._imagePlaneDepth));
23271 vertices.push(transform.unprojectSfM([dx, -dy], this._imagePlaneDepth));
23272 vertices.push(transform.unprojectSfM([dx, dy], this._imagePlaneDepth));
23273 vertices.push(transform.unprojectSfM([-dx, dy], this._imagePlaneDepth));
23274 var positions = new Float32Array(12);
23275 for (var i = 0; i < vertices.length; i++) {
23277 positions[index + 0] = vertices[i][0];
23278 positions[index + 1] = vertices[i][1];
23279 positions[index + 2] = vertices[i][2];
23281 var indices = new Uint16Array(6);
23288 var geometry = new THREE.BufferGeometry();
23289 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
23290 geometry.setIndex(new THREE.BufferAttribute(indices, 1));
23293 return ImagePlaneFactory;
23295 exports.ImagePlaneFactory = ImagePlaneFactory;
23296 exports.default = ImagePlaneFactory;
23298 },{"../../Component":226,"three":176}],258:[function(require,module,exports){
23300 /// <reference path="../../../typings/index.d.ts" />
23301 Object.defineProperty(exports, "__esModule", { value: true });
23302 var Component_1 = require("../../Component");
23303 var Geo_1 = require("../../Geo");
23304 var ImagePlaneGLRenderer = (function () {
23305 function ImagePlaneGLRenderer() {
23306 this._imagePlaneFactory = new Component_1.ImagePlaneFactory();
23307 this._imagePlaneScene = new Component_1.ImagePlaneScene();
23309 this._alphaOld = 0;
23310 this._fadeOutSpeed = 0.05;
23311 this._lastCamera = new Geo_1.Camera();
23312 this._epsilon = 0.000001;
23313 this._currentKey = null;
23314 this._previousKey = null;
23315 this._providerDisposers = {};
23317 this._needsRender = false;
23319 Object.defineProperty(ImagePlaneGLRenderer.prototype, "frameId", {
23321 return this._frameId;
23326 Object.defineProperty(ImagePlaneGLRenderer.prototype, "needsRender", {
23328 return this._needsRender;
23333 ImagePlaneGLRenderer.prototype.indicateNeedsRender = function () {
23334 this._needsRender = true;
23336 ImagePlaneGLRenderer.prototype.updateFrame = function (frame) {
23337 this._updateFrameId(frame.id);
23338 this._needsRender = this._updateAlpha(frame.state.alpha) || this._needsRender;
23339 this._needsRender = this._updateAlphaOld(frame.state.alpha) || this._needsRender;
23340 this._needsRender = this._updateImagePlanes(frame.state) || this._needsRender;
23342 ImagePlaneGLRenderer.prototype.setTextureProvider = function (key, provider) {
23344 if (key !== this._currentKey) {
23347 var createdSubscription = provider.textureCreated$
23348 .subscribe(function (texture) {
23349 _this._updateTexture(texture);
23351 var updatedSubscription = provider.textureUpdated$
23352 .subscribe(function (updated) {
23353 _this._needsRender = true;
23355 var dispose = function () {
23356 createdSubscription.unsubscribe();
23357 updatedSubscription.unsubscribe();
23358 provider.dispose();
23360 if (key in this._providerDisposers) {
23361 var disposeProvider = this._providerDisposers[key];
23363 delete this._providerDisposers[key];
23365 this._providerDisposers[key] = dispose;
23367 ImagePlaneGLRenderer.prototype._updateTexture = function (texture) {
23368 this._needsRender = true;
23369 for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
23370 var plane = _a[_i];
23371 var material = plane.material;
23372 var oldTexture = material.uniforms.projectorTex.value;
23373 material.uniforms.projectorTex.value = null;
23374 oldTexture.dispose();
23375 material.uniforms.projectorTex.value = texture;
23378 ImagePlaneGLRenderer.prototype.updateTextureImage = function (image, node) {
23379 if (this._currentKey !== node.key) {
23382 this._needsRender = true;
23383 for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
23384 var plane = _a[_i];
23385 var material = plane.material;
23386 var texture = material.uniforms.projectorTex.value;
23387 texture.image = image;
23388 texture.needsUpdate = true;
23391 ImagePlaneGLRenderer.prototype.render = function (perspectiveCamera, renderer) {
23392 var planeAlpha = this._imagePlaneScene.imagePlanesOld.length ? 1 : this._alpha;
23393 for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
23394 var plane = _a[_i];
23395 plane.material.uniforms.opacity.value = planeAlpha;
23397 for (var _b = 0, _c = this._imagePlaneScene.imagePlanesOld; _b < _c.length; _b++) {
23398 var plane = _c[_b];
23399 plane.material.uniforms.opacity.value = this._alphaOld;
23401 renderer.render(this._imagePlaneScene.scene, perspectiveCamera);
23402 renderer.render(this._imagePlaneScene.sceneOld, perspectiveCamera);
23403 for (var _d = 0, _e = this._imagePlaneScene.imagePlanes; _d < _e.length; _d++) {
23404 var plane = _e[_d];
23405 plane.material.uniforms.opacity.value = this._alpha;
23407 renderer.render(this._imagePlaneScene.scene, perspectiveCamera);
23409 ImagePlaneGLRenderer.prototype.clearNeedsRender = function () {
23410 this._needsRender = false;
23412 ImagePlaneGLRenderer.prototype.dispose = function () {
23413 this._imagePlaneScene.clear();
23415 ImagePlaneGLRenderer.prototype._updateFrameId = function (frameId) {
23416 this._frameId = frameId;
23418 ImagePlaneGLRenderer.prototype._updateAlpha = function (alpha) {
23419 if (alpha === this._alpha) {
23422 this._alpha = alpha;
23425 ImagePlaneGLRenderer.prototype._updateAlphaOld = function (alpha) {
23426 if (alpha < 1 || this._alphaOld === 0) {
23429 this._alphaOld = Math.max(0, this._alphaOld - this._fadeOutSpeed);
23432 ImagePlaneGLRenderer.prototype._updateImagePlanes = function (state) {
23433 if (state.currentNode == null || state.currentNode.key === this._currentKey) {
23436 var previousKey = state.previousNode != null ? state.previousNode.key : null;
23437 var currentKey = state.currentNode.key;
23438 if (this._previousKey !== previousKey &&
23439 this._previousKey !== currentKey &&
23440 this._previousKey in this._providerDisposers) {
23441 var disposeProvider = this._providerDisposers[this._previousKey];
23443 delete this._providerDisposers[this._previousKey];
23445 if (previousKey != null) {
23446 if (previousKey !== this._currentKey && previousKey !== this._previousKey) {
23447 var previousMesh = this._imagePlaneFactory.createMesh(state.previousNode, state.previousTransform);
23448 this._imagePlaneScene.updateImagePlanes([previousMesh]);
23450 this._previousKey = previousKey;
23452 this._currentKey = currentKey;
23453 var currentMesh = this._imagePlaneFactory.createMesh(state.currentNode, state.currentTransform);
23454 this._imagePlaneScene.updateImagePlanes([currentMesh]);
23455 this._alphaOld = 1;
23458 return ImagePlaneGLRenderer;
23460 exports.ImagePlaneGLRenderer = ImagePlaneGLRenderer;
23461 exports.default = ImagePlaneGLRenderer;
23463 },{"../../Component":226,"../../Geo":229}],259:[function(require,module,exports){
23465 /// <reference path="../../../typings/index.d.ts" />
23466 Object.defineProperty(exports, "__esModule", { value: true });
23467 var THREE = require("three");
23468 var ImagePlaneScene = (function () {
23469 function ImagePlaneScene() {
23470 this.scene = new THREE.Scene();
23471 this.sceneOld = new THREE.Scene();
23472 this.imagePlanes = [];
23473 this.imagePlanesOld = [];
23475 ImagePlaneScene.prototype.updateImagePlanes = function (planes) {
23476 this._dispose(this.imagePlanesOld, this.sceneOld);
23477 for (var _i = 0, _a = this.imagePlanes; _i < _a.length; _i++) {
23478 var plane = _a[_i];
23479 this.scene.remove(plane);
23480 this.sceneOld.add(plane);
23482 for (var _b = 0, planes_1 = planes; _b < planes_1.length; _b++) {
23483 var plane = planes_1[_b];
23484 this.scene.add(plane);
23486 this.imagePlanesOld = this.imagePlanes;
23487 this.imagePlanes = planes;
23489 ImagePlaneScene.prototype.addImagePlanes = function (planes) {
23490 for (var _i = 0, planes_2 = planes; _i < planes_2.length; _i++) {
23491 var plane = planes_2[_i];
23492 this.scene.add(plane);
23493 this.imagePlanes.push(plane);
23496 ImagePlaneScene.prototype.addImagePlanesOld = function (planes) {
23497 for (var _i = 0, planes_3 = planes; _i < planes_3.length; _i++) {
23498 var plane = planes_3[_i];
23499 this.sceneOld.add(plane);
23500 this.imagePlanesOld.push(plane);
23503 ImagePlaneScene.prototype.setImagePlanes = function (planes) {
23505 this.addImagePlanes(planes);
23507 ImagePlaneScene.prototype.setImagePlanesOld = function (planes) {
23509 this.addImagePlanesOld(planes);
23511 ImagePlaneScene.prototype.clear = function () {
23515 ImagePlaneScene.prototype._clear = function () {
23516 this._dispose(this.imagePlanes, this.scene);
23517 this.imagePlanes.length = 0;
23519 ImagePlaneScene.prototype._clearOld = function () {
23520 this._dispose(this.imagePlanesOld, this.sceneOld);
23521 this.imagePlanesOld.length = 0;
23523 ImagePlaneScene.prototype._dispose = function (planes, scene) {
23524 for (var _i = 0, planes_4 = planes; _i < planes_4.length; _i++) {
23525 var plane = planes_4[_i];
23526 scene.remove(plane);
23527 plane.geometry.dispose();
23528 plane.material.dispose();
23529 var texture = plane.material.uniforms.projectorTex.value;
23530 if (texture != null) {
23535 return ImagePlaneScene;
23537 exports.ImagePlaneScene = ImagePlaneScene;
23538 exports.default = ImagePlaneScene;
23540 },{"three":176}],260:[function(require,module,exports){
23542 /// <reference path="../../../typings/index.d.ts" />
23543 Object.defineProperty(exports, "__esModule", { value: true });
23545 var path = require("path");
23546 var ImagePlaneShaders = (function () {
23547 function ImagePlaneShaders() {
23549 ImagePlaneShaders.equirectangular = {
23550 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}",
23551 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}",
23553 ImagePlaneShaders.perspective = {
23554 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}",
23555 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}",
23557 return ImagePlaneShaders;
23559 exports.ImagePlaneShaders = ImagePlaneShaders;
23561 },{"path":22}],261:[function(require,module,exports){
23563 /// <reference path="../../../typings/index.d.ts" />
23564 var __extends = (this && this.__extends) || (function () {
23565 var extendStatics = Object.setPrototypeOf ||
23566 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23567 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23568 return function (d, b) {
23569 extendStatics(d, b);
23570 function __() { this.constructor = d; }
23571 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23574 Object.defineProperty(exports, "__esModule", { value: true });
23575 var Observable_1 = require("rxjs/Observable");
23576 var Subject_1 = require("rxjs/Subject");
23577 require("rxjs/add/observable/combineLatest");
23578 require("rxjs/add/observable/fromEvent");
23579 require("rxjs/add/observable/of");
23580 require("rxjs/add/observable/zip");
23581 require("rxjs/add/operator/distinctUntilChanged");
23582 require("rxjs/add/operator/filter");
23583 require("rxjs/add/operator/first");
23584 require("rxjs/add/operator/map");
23585 require("rxjs/add/operator/merge");
23586 require("rxjs/add/operator/mergeMap");
23587 require("rxjs/add/operator/scan");
23588 require("rxjs/add/operator/switchMap");
23589 require("rxjs/add/operator/withLatestFrom");
23590 require("rxjs/add/operator/zip");
23591 var State_1 = require("../../State");
23592 var Render_1 = require("../../Render");
23593 var Utils_1 = require("../../Utils");
23594 var Component_1 = require("../../Component");
23595 var SliderState = (function () {
23596 function SliderState() {
23597 this._imagePlaneFactory = new Component_1.ImagePlaneFactory();
23598 this._imagePlaneScene = new Component_1.ImagePlaneScene();
23599 this._currentKey = null;
23600 this._previousKey = null;
23601 this._currentPano = false;
23603 this._glNeedsRender = false;
23604 this._domNeedsRender = true;
23607 Object.defineProperty(SliderState.prototype, "frameId", {
23609 return this._frameId;
23614 Object.defineProperty(SliderState.prototype, "curtain", {
23616 return this._curtain;
23621 Object.defineProperty(SliderState.prototype, "glNeedsRender", {
23623 return this._glNeedsRender;
23628 Object.defineProperty(SliderState.prototype, "domNeedsRender", {
23630 return this._domNeedsRender;
23635 Object.defineProperty(SliderState.prototype, "sliderVisible", {
23637 return this._sliderVisible;
23639 set: function (value) {
23640 this._sliderVisible = value;
23641 this._domNeedsRender = true;
23646 Object.defineProperty(SliderState.prototype, "disabled", {
23648 return this._currentKey == null ||
23649 this._previousKey == null ||
23655 SliderState.prototype.update = function (frame) {
23656 this._updateFrameId(frame.id);
23657 var needsRender = this._updateImagePlanes(frame.state);
23658 this._domNeedsRender = needsRender || this._domNeedsRender;
23659 needsRender = this._updateCurtain(frame.state.alpha) || needsRender;
23660 this._glNeedsRender = needsRender || this._glNeedsRender;
23662 SliderState.prototype.updateTexture = function (image, node) {
23663 var imagePlanes = node.key === this._currentKey ?
23664 this._imagePlaneScene.imagePlanes :
23665 node.key === this._previousKey ?
23666 this._imagePlaneScene.imagePlanesOld :
23668 if (imagePlanes.length === 0) {
23671 this._glNeedsRender = true;
23672 for (var _i = 0, imagePlanes_1 = imagePlanes; _i < imagePlanes_1.length; _i++) {
23673 var plane = imagePlanes_1[_i];
23674 var material = plane.material;
23675 var texture = material.uniforms.projectorTex.value;
23676 texture.image = image;
23677 texture.needsUpdate = true;
23680 SliderState.prototype.render = function (perspectiveCamera, renderer) {
23681 if (!this.disabled) {
23682 renderer.render(this._imagePlaneScene.sceneOld, perspectiveCamera);
23684 renderer.render(this._imagePlaneScene.scene, perspectiveCamera);
23686 SliderState.prototype.dispose = function () {
23687 this._imagePlaneScene.clear();
23689 SliderState.prototype.clearGLNeedsRender = function () {
23690 this._glNeedsRender = false;
23692 SliderState.prototype.clearDomNeedsRender = function () {
23693 this._domNeedsRender = false;
23695 SliderState.prototype._updateFrameId = function (frameId) {
23696 this._frameId = frameId;
23698 SliderState.prototype._updateImagePlanes = function (state) {
23699 if (state.currentNode == null) {
23702 var needsRender = false;
23703 if (state.previousNode != null && this._previousKey !== state.previousNode.key) {
23704 needsRender = true;
23705 this._previousKey = state.previousNode.key;
23706 this._imagePlaneScene.setImagePlanesOld([
23707 this._imagePlaneFactory.createMesh(state.previousNode, state.previousTransform),
23710 if (this._currentKey !== state.currentNode.key) {
23711 needsRender = true;
23712 this._currentKey = state.currentNode.key;
23713 this._currentPano = state.currentNode.pano;
23714 this._imagePlaneScene.setImagePlanes([
23715 this._imagePlaneFactory.createMesh(state.currentNode, state.currentTransform),
23717 if (!this.disabled) {
23718 this._updateBbox();
23721 return needsRender;
23723 SliderState.prototype._updateCurtain = function (alpha) {
23724 if (this.disabled ||
23725 Math.abs(this._curtain - alpha) < 0.001) {
23728 this._curtain = alpha;
23729 this._updateBbox();
23732 SliderState.prototype._updateBbox = function () {
23733 for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
23734 var plane = _a[_i];
23735 var shaderMaterial = plane.material;
23736 var bbox = shaderMaterial.uniforms.bbox.value;
23737 bbox.z = this._curtain;
23740 return SliderState;
23742 var SliderComponent = (function (_super) {
23743 __extends(SliderComponent, _super);
23745 * Create a new slider component instance.
23746 * @class SliderComponent
23748 function SliderComponent(name, container, navigator) {
23749 var _this = _super.call(this, name, container, navigator) || this;
23750 _this._sliderStateOperation$ = new Subject_1.Subject();
23751 _this._sliderStateCreator$ = new Subject_1.Subject();
23752 _this._sliderStateDisposer$ = new Subject_1.Subject();
23753 _this._sliderState$ = _this._sliderStateOperation$
23754 .scan(function (sliderState, operation) {
23755 return operation(sliderState);
23757 .filter(function (sliderState) {
23758 return sliderState != null;
23760 .distinctUntilChanged(undefined, function (sliderState) {
23761 return sliderState.frameId;
23763 _this._sliderStateCreator$
23765 return function (sliderState) {
23766 if (sliderState != null) {
23767 throw new Error("Multiple slider states can not be created at the same time");
23769 return new SliderState();
23772 .subscribe(_this._sliderStateOperation$);
23773 _this._sliderStateDisposer$
23775 return function (sliderState) {
23776 sliderState.dispose();
23780 .subscribe(_this._sliderStateOperation$);
23784 * Set the image keys.
23786 * Configures the component to show the image planes for the supplied image keys.
23788 * @param {keys} ISliderKeys - Slider keys object specifying the images to be shown in the foreground and the background.
23790 SliderComponent.prototype.setKeys = function (keys) {
23791 this.configure({ keys: keys });
23794 * Set the initial position.
23796 * Configures the intial position of the slider. The inital position value will be used when the component is activated.
23798 * @param {number} initialPosition - Initial slider position.
23800 SliderComponent.prototype.setInitialPosition = function (initialPosition) {
23801 this.configure({ initialPosition: initialPosition });
23804 * Set the value controlling if the slider is visible.
23806 * @param {boolean} sliderVisible - Value indicating if the slider should be visible or not.
23808 SliderComponent.prototype.setSliderVisible = function (sliderVisible) {
23809 this.configure({ sliderVisible: sliderVisible });
23811 SliderComponent.prototype._activate = function () {
23813 this._sliderContainer = this._createElement("div", "mapillary-js-slider-container", this._container.element);
23814 this._sliderWrapper = this._createElement("div", "SliderWrapper", this._sliderContainer);
23815 this._sliderControl = this._createElement("input", "SliderControl", this._sliderWrapper);
23816 this._sliderControl.setAttribute("type", "range");
23817 this._sliderControl.setAttribute("min", "0");
23818 this._sliderControl.setAttribute("max", "1000");
23819 this._sliderControl.style.visibility = "hidden";
23820 this._moveToHandler = function (e) {
23821 var curtain = Number(e.target.value) / 1000;
23822 _this._navigator.stateService.moveTo(curtain);
23824 this._sliderControl.addEventListener("input", this._moveToHandler);
23825 this._sliderControl.addEventListener("change", this._moveToHandler);
23826 Observable_1.Observable
23827 .combineLatest(this._navigator.stateService.state$, this._configuration$)
23829 .subscribe(function (_a) {
23830 var state = _a[0], configuration = _a[1];
23831 if (state === State_1.State.Traversing) {
23832 _this._navigator.stateService.wait();
23833 var position = configuration.initialPosition != null ? configuration.initialPosition : 1;
23834 _this._sliderControl.value = (1000 * position).toString();
23835 _this._navigator.stateService.moveTo(position);
23838 this._glRenderSubscription = this._sliderState$
23839 .map(function (sliderState) {
23843 frameId: sliderState.frameId,
23844 needsRender: sliderState.glNeedsRender,
23845 render: sliderState.render.bind(sliderState),
23846 stage: Render_1.GLRenderStage.Background,
23849 sliderState.clearGLNeedsRender();
23852 .subscribe(this._container.glRenderer.render$);
23853 this._domRenderSubscription = this._sliderState$
23854 .filter(function (sliderState) {
23855 return sliderState.domNeedsRender;
23857 .subscribe(function (sliderState) {
23858 _this._sliderControl.value = (1000 * sliderState.curtain).toString();
23859 var visibility = sliderState.disabled || !sliderState.sliderVisible ? "hidden" : "visible";
23860 _this._sliderControl.style.visibility = visibility;
23861 sliderState.clearDomNeedsRender();
23863 this._sliderStateCreator$.next(null);
23864 this._stateSubscription = this._navigator.stateService.currentState$
23865 .map(function (frame) {
23866 return function (sliderState) {
23867 sliderState.update(frame);
23868 return sliderState;
23871 .subscribe(this._sliderStateOperation$);
23872 this._setSliderVisibleSubscription = this._configuration$
23873 .map(function (configuration) {
23874 return configuration.sliderVisible == null || configuration.sliderVisible;
23876 .distinctUntilChanged()
23877 .map(function (sliderVisible) {
23878 return function (sliderState) {
23879 sliderState.sliderVisible = sliderVisible;
23880 return sliderState;
23883 .subscribe(this._sliderStateOperation$);
23884 this._setKeysSubscription = this._configuration$
23885 .filter(function (configuration) {
23886 return configuration.keys != null;
23888 .switchMap(function (configuration) {
23889 return Observable_1.Observable
23890 .zip(_this._catchCacheNode$(configuration.keys.background), _this._catchCacheNode$(configuration.keys.foreground))
23891 .map(function (nodes) {
23892 return { background: nodes[0], foreground: nodes[1] };
23894 .zip(_this._navigator.stateService.currentState$.first())
23895 .map(function (nf) {
23896 return { nodes: nf[0], state: nf[1].state };
23899 .subscribe(function (co) {
23900 if (co.state.currentNode != null &&
23901 co.state.previousNode != null &&
23902 co.state.currentNode.key === co.nodes.foreground.key &&
23903 co.state.previousNode.key === co.nodes.background.key) {
23906 if (co.state.currentNode.key === co.nodes.background.key) {
23907 _this._navigator.stateService.setNodes([co.nodes.foreground]);
23910 if (co.state.currentNode.key === co.nodes.foreground.key &&
23911 co.state.trajectory.length === 1) {
23912 _this._navigator.stateService.prependNodes([co.nodes.background]);
23915 _this._navigator.stateService.setNodes([co.nodes.background]);
23916 _this._navigator.stateService.setNodes([co.nodes.foreground]);
23920 var previousNode$ = this._navigator.stateService.currentState$
23921 .map(function (frame) {
23922 return frame.state.previousNode;
23924 .filter(function (node) {
23925 return node != null;
23927 .distinctUntilChanged(undefined, function (node) {
23930 this._nodeSubscription = Observable_1.Observable
23931 .merge(previousNode$, this._navigator.stateService.currentNode$)
23932 .filter(function (node) {
23934 Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize :
23935 Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize;
23937 .mergeMap(function (node) {
23938 var baseImageSize = node.pano ?
23939 Utils_1.Settings.basePanoramaSize :
23940 Utils_1.Settings.baseImageSize;
23941 if (Math.max(node.image.width, node.image.height) > baseImageSize) {
23942 return Observable_1.Observable.empty();
23944 return node.cacheImage$(Utils_1.Settings.maxImageSize)
23945 .map(function (n) {
23946 return [n.image, n];
23948 .catch(function (error, caught) {
23949 console.error("Failed to fetch high res slider image (" + node.key + ")", error);
23950 return Observable_1.Observable.empty();
23953 .map(function (_a) {
23954 var element = _a[0], node = _a[1];
23955 return function (sliderState) {
23956 sliderState.updateTexture(element, node);
23957 return sliderState;
23960 .subscribe(this._sliderStateOperation$);
23962 SliderComponent.prototype._deactivate = function () {
23964 this._navigator.stateService.state$
23966 .subscribe(function (state) {
23967 if (state === State_1.State.Waiting) {
23968 _this._navigator.stateService.traverse();
23971 this._sliderStateDisposer$.next(null);
23972 this._setKeysSubscription.unsubscribe();
23973 this._setSliderVisibleSubscription.unsubscribe();
23974 this._stateSubscription.unsubscribe();
23975 this._glRenderSubscription.unsubscribe();
23976 this._domRenderSubscription.unsubscribe();
23977 this._nodeSubscription.unsubscribe();
23978 this.configure({ keys: null });
23979 this._sliderControl.removeEventListener("input", this._moveToHandler);
23980 this._sliderControl.removeEventListener("change", this._moveToHandler);
23981 this._container.element.removeChild(this._sliderContainer);
23982 this._moveToHandler = null;
23983 this._sliderControl = null;
23984 this._sliderWrapper = null;
23985 this._sliderContainer = null;
23987 SliderComponent.prototype._getDefaultConfiguration = function () {
23990 SliderComponent.prototype._catchCacheNode$ = function (key) {
23991 return this._navigator.graphService.cacheNode$(key)
23992 .catch(function (error, caught) {
23993 console.error("Failed to cache slider node (" + key + ")", error);
23994 return Observable_1.Observable.empty();
23997 SliderComponent.prototype._createElement = function (tagName, className, container) {
23998 var element = document.createElement(tagName);
24000 element.className = className;
24003 container.appendChild(element);
24007 SliderComponent.componentName = "slider";
24008 return SliderComponent;
24009 }(Component_1.Component));
24010 exports.SliderComponent = SliderComponent;
24011 Component_1.ComponentService.register(SliderComponent);
24012 exports.default = SliderComponent;
24014 },{"../../Component":226,"../../Render":232,"../../State":233,"../../Utils":235,"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){
24016 Object.defineProperty(exports, "__esModule", { value: true });
24017 var MarkerComponent_1 = require("./MarkerComponent");
24018 exports.MarkerComponent = MarkerComponent_1.MarkerComponent;
24019 var SimpleMarker_1 = require("./marker/SimpleMarker");
24020 exports.SimpleMarker = SimpleMarker_1.SimpleMarker;
24021 var CircleMarker_1 = require("./marker/CircleMarker");
24022 exports.CircleMarker = CircleMarker_1.CircleMarker;
24024 },{"./MarkerComponent":263,"./marker/CircleMarker":266,"./marker/SimpleMarker":268}],263:[function(require,module,exports){
24026 /// <reference path="../../../typings/index.d.ts" />
24027 var __extends = (this && this.__extends) || (function () {
24028 var extendStatics = Object.setPrototypeOf ||
24029 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24030 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24031 return function (d, b) {
24032 extendStatics(d, b);
24033 function __() { this.constructor = d; }
24034 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24037 Object.defineProperty(exports, "__esModule", { value: true });
24038 var THREE = require("three");
24039 var when = require("when");
24040 var Observable_1 = require("rxjs/Observable");
24041 require("rxjs/add/observable/combineLatest");
24042 require("rxjs/add/operator/distinctUntilChanged");
24043 require("rxjs/add/operator/map");
24044 var Component_1 = require("../../Component");
24045 var Render_1 = require("../../Render");
24046 var Graph_1 = require("../../Graph");
24047 var Geo_1 = require("../../Geo");
24049 * @class MarkerComponent
24051 * @classdesc Component for showing and editing 3D marker objects.
24053 * The `add` method is used for adding new markers or replacing
24054 * markers already in the set.
24056 * If a marker already in the set has the same
24057 * id as one of the markers added, the old marker will be removed and
24058 * the added marker will take its place.
24060 * It is not possible to update markers in the set by updating any properties
24061 * directly on the marker object. Markers need to be replaced by
24062 * re-adding them for updates to geographic position or configuration
24065 * Markers added to the marker component can be either interactive
24066 * or non-interactive. Different marker types define their behavior.
24067 * Markers with interaction support can be configured with options
24068 * to respond to dragging inside the viewer and be detected when
24069 * retrieving markers from pixel points with the `getMarkerIdAt` method.
24071 * To retrive and use the marker component
24075 * var viewer = new Mapillary.Viewer(
24079 * { component: { marker: true } });
24081 * var markerComponent = viewer.getComponent("marker");
24084 var MarkerComponent = (function (_super) {
24085 __extends(MarkerComponent, _super);
24086 function MarkerComponent(name, container, navigator) {
24087 var _this = _super.call(this, name, container, navigator) || this;
24088 _this._relativeGroundAltitude = -2;
24089 _this._geoCoords = new Geo_1.GeoCoords();
24090 _this._graphCalculator = new Graph_1.GraphCalculator();
24091 _this._markerScene = new Component_1.MarkerScene();
24092 _this._markerSet = new Component_1.MarkerSet();
24093 _this._viewportCoords = new Geo_1.ViewportCoords();
24097 * Add markers to the marker set or replace markers in the marker set.
24099 * @description If a marker already in the set has the same
24100 * id as one of the markers added, the old marker will be removed
24101 * the added marker will take its place.
24103 * Any marker inside the visible bounding bbox
24104 * will be initialized and placed in the viewer.
24106 * @param {Array<Marker>} markers - Markers to add.
24108 * @example ```markerComponent.add([marker1, marker2]);```
24110 MarkerComponent.prototype.add = function (markers) {
24111 this._markerSet.add(markers);
24114 * Returns the marker in the marker set with the specified id, or
24115 * undefined if the id matches no marker.
24117 * @param {string} markerId - Id of the marker.
24119 * @example ```var marker = markerComponent.get("markerId");```
24122 MarkerComponent.prototype.get = function (markerId) {
24123 return this._markerSet.get(markerId);
24126 * Returns an array of all markers.
24128 * @example ```var markers = markerComponent.getAll();```
24130 MarkerComponent.prototype.getAll = function () {
24131 return this._markerSet.getAll();
24134 * Returns the id of the interactive marker closest to the current camera
24135 * position at the specified point.
24137 * @description Notice that the pixelPoint argument requires x, y
24138 * coordinates from pixel space.
24140 * With this function, you can use the coordinates provided by mouse
24141 * events to get information out of the marker component.
24143 * If no interactive geometry of an interactive marker exist at the pixel
24144 * point, `null` will be returned.
24146 * @param {Array<number>} pixelPoint - Pixel coordinates on the viewer element.
24147 * @returns {string} Id of the interactive marker closest to the camera. If no
24148 * interactive marker exist at the pixel point, `null` will be returned.
24152 * markerComponent.getMarkerIdAt([100, 100])
24153 * .then((markerId) => { console.log(markerId); });
24156 MarkerComponent.prototype.getMarkerIdAt = function (pixelPoint) {
24158 return when.promise(function (resolve, reject) {
24159 _this._container.renderService.renderCamera$
24161 .map(function (render) {
24162 var viewport = _this._viewportCoords
24163 .canvasToViewport(pixelPoint[0], pixelPoint[1], _this._container.element);
24164 var id = _this._markerScene.intersectObjects(viewport, render.perspective);
24167 .subscribe(function (id) {
24169 }, function (error) {
24175 * Check if a marker exist in the marker set.
24177 * @param {string} markerId - Id of the marker.
24179 * @example ```var markerExists = markerComponent.has("markerId");```
24181 MarkerComponent.prototype.has = function (markerId) {
24182 return this._markerSet.has(markerId);
24185 * Remove markers with the specified ids from the marker set.
24187 * @param {Array<string>} markerIds - Ids for markers to remove.
24189 * @example ```markerComponent.remove(["id-1", "id-2"]);```
24191 MarkerComponent.prototype.remove = function (markerIds) {
24192 this._markerSet.remove(markerIds);
24195 * Remove all markers from the marker set.
24197 * @example ```markerComponent.removeAll();```
24199 MarkerComponent.prototype.removeAll = function () {
24200 this._markerSet.removeAll();
24202 MarkerComponent.prototype._activate = function () {
24204 var groundAltitude$ = this._navigator.stateService.currentState$
24205 .map(function (frame) {
24206 return frame.state.camera.position.z + _this._relativeGroundAltitude;
24208 .distinctUntilChanged(function (a1, a2) {
24209 return Math.abs(a1 - a2) < 0.01;
24213 var geoInitiated$ = Observable_1.Observable
24214 .combineLatest(groundAltitude$, this._navigator.stateService.reference$)
24216 .map(function () { })
24219 var clampedConfiguration$ = this._configuration$
24220 .map(function (configuration) {
24221 return { visibleBBoxSize: Math.max(1, Math.min(200, configuration.visibleBBoxSize)) };
24223 var currentlatLon$ = this._navigator.stateService.currentNode$
24224 .map(function (node) { return node.latLon; })
24227 var visibleBBox$ = Observable_1.Observable
24228 .combineLatest(clampedConfiguration$, currentlatLon$)
24229 .map(function (_a) {
24230 var configuration = _a[0], latLon = _a[1];
24231 return _this._graphCalculator
24232 .boundingBoxCorners(latLon, configuration.visibleBBoxSize / 2);
24236 var visibleMarkers$ = Observable_1.Observable
24237 .combineLatest(Observable_1.Observable
24238 .of(this._markerSet)
24239 .concat(this._markerSet.changed$), visibleBBox$)
24240 .map(function (_a) {
24241 var set = _a[0], bbox = _a[1];
24242 return set.search(bbox);
24244 this._setChangedSubscription = geoInitiated$
24245 .switchMap(function () {
24246 return visibleMarkers$
24247 .withLatestFrom(_this._navigator.stateService.reference$, groundAltitude$);
24249 .subscribe(function (_a) {
24250 var markers = _a[0], reference = _a[1], alt = _a[2];
24251 var geoCoords = _this._geoCoords;
24252 var markerScene = _this._markerScene;
24253 var sceneMarkers = markerScene.markers;
24254 var markersToRemove = Object.assign({}, sceneMarkers);
24255 for (var _i = 0, markers_1 = markers; _i < markers_1.length; _i++) {
24256 var marker = markers_1[_i];
24257 if (marker.id in sceneMarkers) {
24258 delete markersToRemove[marker.id];
24261 var point3d = geoCoords
24262 .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
24263 markerScene.add(marker, point3d);
24266 for (var id in markersToRemove) {
24267 if (!markersToRemove.hasOwnProperty(id)) {
24270 markerScene.remove(id);
24273 this._markersUpdatedSubscription = geoInitiated$
24274 .switchMap(function () {
24275 return _this._markerSet.updated$
24276 .withLatestFrom(visibleBBox$, _this._navigator.stateService.reference$, groundAltitude$);
24278 .subscribe(function (_a) {
24279 var markers = _a[0], _b = _a[1], sw = _b[0], ne = _b[1], reference = _a[2], alt = _a[3];
24280 var geoCoords = _this._geoCoords;
24281 var markerScene = _this._markerScene;
24282 for (var _i = 0, markers_2 = markers; _i < markers_2.length; _i++) {
24283 var marker = markers_2[_i];
24284 var exists = markerScene.has(marker.id);
24285 var visible = marker.latLon.lat > sw.lat &&
24286 marker.latLon.lat < ne.lat &&
24287 marker.latLon.lon > sw.lon &&
24288 marker.latLon.lon < ne.lon;
24290 var point3d = geoCoords
24291 .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
24292 markerScene.add(marker, point3d);
24294 else if (!visible && exists) {
24295 markerScene.remove(marker.id);
24299 this._referenceSubscription = this._navigator.stateService.reference$
24301 .withLatestFrom(groundAltitude$)
24302 .subscribe(function (_a) {
24303 var reference = _a[0], alt = _a[1];
24304 var geoCoords = _this._geoCoords;
24305 var markerScene = _this._markerScene;
24306 for (var _i = 0, _b = markerScene.getAll(); _i < _b.length; _i++) {
24307 var marker = _b[_i];
24308 var point3d = geoCoords
24309 .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
24310 markerScene.update(marker.id, point3d);
24313 this._adjustHeightSubscription = groundAltitude$
24315 .withLatestFrom(this._navigator.stateService.reference$, currentlatLon$)
24316 .subscribe(function (_a) {
24317 var alt = _a[0], reference = _a[1], latLon = _a[2];
24318 var geoCoords = _this._geoCoords;
24319 var markerScene = _this._markerScene;
24320 var position = geoCoords
24321 .geodeticToEnu(latLon.lat, latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
24322 for (var _i = 0, _b = markerScene.getAll(); _i < _b.length; _i++) {
24323 var marker = _b[_i];
24324 var point3d = geoCoords
24325 .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
24326 var distanceX = point3d[0] - position[0];
24327 var distanceY = point3d[1] - position[1];
24328 var groundDistance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
24329 if (groundDistance > 50) {
24332 markerScene.lerpAltitude(marker.id, alt, Math.min(1, Math.max(0, 1.2 - 1.2 * groundDistance / 50)));
24335 this._renderSubscription = this._navigator.stateService.currentState$
24336 .map(function (frame) {
24337 var scene = _this._markerScene;
24342 needsRender: scene.needsRender,
24343 render: scene.render.bind(scene),
24344 stage: Render_1.GLRenderStage.Foreground,
24348 .subscribe(this._container.glRenderer.render$);
24349 var hoveredMarkerId$ = Observable_1.Observable
24350 .combineLatest(this._container.renderService.renderCamera$, this._container.mouseService.mouseMove$)
24351 .map(function (_a) {
24352 var render = _a[0], event = _a[1];
24353 var element = _this._container.element;
24354 var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
24355 var viewport = _this._viewportCoords.canvasToViewport(canvasX, canvasY, element);
24356 var markerId = _this._markerScene.intersectObjects(viewport, render.perspective);
24361 var draggingStarted$ = this._container.mouseService
24362 .filtered$(this._name, this._container.mouseService.mouseDragStart$)
24363 .map(function (event) {
24366 var draggingStopped$ = this._container.mouseService
24367 .filtered$(this._name, this._container.mouseService.mouseDragEnd$)
24368 .map(function (event) {
24371 var dragging$ = Observable_1.Observable
24372 .merge(draggingStarted$, draggingStopped$)
24374 this._dragEventSubscription = draggingStarted$
24375 .withLatestFrom(hoveredMarkerId$)
24376 .merge(Observable_1.Observable
24377 .combineLatest(draggingStopped$, Observable_1.Observable.of(null)))
24378 .startWith([false, null])
24380 .subscribe(function (_a) {
24381 var previous = _a[0], current = _a[1];
24382 var dragging = current[0];
24383 var eventType = dragging ? MarkerComponent.dragstart : MarkerComponent.dragend;
24384 var id = dragging ? current[1] : previous[1];
24385 var marker = _this._markerScene.get(id);
24386 var markerEvent = { marker: marker, target: _this, type: eventType };
24387 _this.fire(eventType, markerEvent);
24389 this._mouseClaimSubscription = Observable_1.Observable
24390 .combineLatest(this._container.mouseService.active$, hoveredMarkerId$, dragging$)
24391 .map(function (_a) {
24392 var active = _a[0], markerId = _a[1], dragging = _a[2];
24393 return (!active && markerId != null) || dragging;
24395 .distinctUntilChanged()
24396 .subscribe(function (hovered) {
24398 _this._container.mouseService.claimMouse(_this._name, 1);
24401 _this._container.mouseService.unclaimMouse(_this._name);
24404 var offset$ = this._container.mouseService
24405 .filtered$(this._name, this._container.mouseService.mouseDragStart$)
24406 .withLatestFrom(hoveredMarkerId$, this._container.renderService.renderCamera$)
24407 .map(function (_a) {
24408 var e = _a[0], id = _a[1], r = _a[2];
24409 var marker = _this._markerScene.get(id);
24410 var element = _this._container.element;
24411 var _b = _this._viewportCoords.projectToCanvas(marker.geometry.position.toArray(), element, r.perspective), groundCanvasX = _b[0], groundCanvasY = _b[1];
24412 var _c = _this._viewportCoords.canvasPosition(e, element), canvasX = _c[0], canvasY = _c[1];
24413 var offset = [canvasX - groundCanvasX, canvasY - groundCanvasY];
24414 return [marker, offset, r];
24418 this._updateMarkerSubscription = this._container.mouseService
24419 .filtered$(this._name, this._container.mouseService.mouseDrag$)
24420 .withLatestFrom(offset$, this._navigator.stateService.reference$, clampedConfiguration$)
24421 .subscribe(function (_a) {
24422 var event = _a[0], _b = _a[1], marker = _b[0], offset = _b[1], render = _b[2], reference = _a[2], configuration = _a[3];
24423 if (!_this._markerScene.has(marker.id)) {
24426 var element = _this._container.element;
24427 var _c = _this._viewportCoords.canvasPosition(event, element), canvasX = _c[0], canvasY = _c[1];
24428 var groundX = canvasX - offset[0];
24429 var groundY = canvasY - offset[1];
24430 var _d = _this._viewportCoords
24431 .canvasToViewport(groundX, groundY, element), viewportX = _d[0], viewportY = _d[1];
24432 var direction = new THREE.Vector3(viewportX, viewportY, 1)
24433 .unproject(render.perspective)
24434 .sub(render.perspective.position)
24436 var distance = Math.min(_this._relativeGroundAltitude / direction.z, configuration.visibleBBoxSize / 2 - 0.1);
24437 if (distance < 0) {
24440 var intersection = direction
24442 .multiplyScalar(distance)
24443 .add(render.perspective.position);
24444 intersection.z = render.perspective.position.z + _this._relativeGroundAltitude;
24445 var _e = _this._geoCoords
24446 .enuToGeodetic(intersection.x, intersection.y, intersection.z, reference.lat, reference.lon, reference.alt), lat = _e[0], lon = _e[1];
24447 _this._markerScene.update(marker.id, intersection.toArray(), { lat: lat, lon: lon });
24448 _this._markerSet.update(marker);
24449 var markerEvent = { marker: marker, target: _this, type: MarkerComponent.changed };
24450 _this.fire(MarkerComponent.changed, markerEvent);
24453 MarkerComponent.prototype._deactivate = function () {
24454 this._adjustHeightSubscription.unsubscribe();
24455 this._dragEventSubscription.unsubscribe();
24456 this._markersUpdatedSubscription.unsubscribe();
24457 this._mouseClaimSubscription.unsubscribe();
24458 this._referenceSubscription.unsubscribe();
24459 this._renderSubscription.unsubscribe();
24460 this._setChangedSubscription.unsubscribe();
24461 this._updateMarkerSubscription.unsubscribe();
24462 this._markerScene.clear();
24464 MarkerComponent.prototype._getDefaultConfiguration = function () {
24465 return { visibleBBoxSize: 100 };
24467 MarkerComponent.componentName = "marker";
24469 * Fired when the position of a marker is changed.
24471 * @type {IMarkerEvent} markerEvent - Marker event data.
24474 * markerComponent.on("changed", function(e) {
24475 * console.log(e.marker.id, e.marker.latLon);
24479 MarkerComponent.changed = "changed";
24481 * Fired when a marker drag interaction starts.
24483 * @type {IMarkerEvent} markerEvent - Marker event data.
24486 * markerComponent.on("dragstart", function(e) {
24487 * console.log(e.marker.id, e.marker.latLon);
24491 MarkerComponent.dragstart = "dragstart";
24493 * Fired when a marker drag interaction ends.
24495 * @type {IMarkerEvent} markerEvent - Marker event data.
24498 * markerComponent.on("dragend", function(e) {
24499 * console.log(e.marker.id, e.marker.latLon);
24503 MarkerComponent.dragend = "dragend";
24504 return MarkerComponent;
24505 }(Component_1.Component));
24506 exports.MarkerComponent = MarkerComponent;
24507 Component_1.ComponentService.register(MarkerComponent);
24508 exports.default = MarkerComponent;
24510 },{"../../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}],264:[function(require,module,exports){
24512 /// <reference path="../../../typings/index.d.ts" />
24513 Object.defineProperty(exports, "__esModule", { value: true });
24514 var THREE = require("three");
24515 var MarkerScene = (function () {
24516 function MarkerScene(scene, raycaster) {
24517 this._needsRender = false;
24518 this._interactiveObjects = [];
24519 this._markers = {};
24520 this._objectMarkers = {};
24521 this._raycaster = !!raycaster ? raycaster : new THREE.Raycaster();
24522 this._scene = !!scene ? scene : new THREE.Scene();
24524 Object.defineProperty(MarkerScene.prototype, "markers", {
24526 return this._markers;
24531 Object.defineProperty(MarkerScene.prototype, "needsRender", {
24533 return this._needsRender;
24538 MarkerScene.prototype.add = function (marker, position) {
24539 if (marker.id in this._markers) {
24540 this._dispose(marker.id);
24542 marker.createGeometry(position);
24543 this._scene.add(marker.geometry);
24544 this._markers[marker.id] = marker;
24545 for (var _i = 0, _a = marker.getInteractiveObjects(); _i < _a.length; _i++) {
24546 var interactiveObject = _a[_i];
24547 this._interactiveObjects.push(interactiveObject);
24548 this._objectMarkers[interactiveObject.uuid] = marker.id;
24550 this._needsRender = true;
24552 MarkerScene.prototype.clear = function () {
24553 for (var id in this._markers) {
24554 if (!this._markers.hasOwnProperty) {
24559 this._needsRender = true;
24561 MarkerScene.prototype.get = function (id) {
24562 return this._markers[id];
24564 MarkerScene.prototype.getAll = function () {
24567 .keys(this._markers)
24568 .map(function (id) { return _this._markers[id]; });
24570 MarkerScene.prototype.has = function (id) {
24571 return id in this._markers;
24573 MarkerScene.prototype.intersectObjects = function (_a, camera) {
24574 var viewportX = _a[0], viewportY = _a[1];
24575 this._raycaster.setFromCamera(new THREE.Vector2(viewportX, viewportY), camera);
24576 var intersects = this._raycaster.intersectObjects(this._interactiveObjects);
24577 for (var _i = 0, intersects_1 = intersects; _i < intersects_1.length; _i++) {
24578 var intersect = intersects_1[_i];
24579 if (intersect.object.uuid in this._objectMarkers) {
24580 return this._objectMarkers[intersect.object.uuid];
24585 MarkerScene.prototype.lerpAltitude = function (id, alt, alpha) {
24586 if (!(id in this._markers)) {
24589 this._markers[id].lerpAltitude(alt, alpha);
24590 this._needsRender = true;
24592 MarkerScene.prototype.remove = function (id) {
24593 if (!(id in this._markers)) {
24597 this._needsRender = true;
24599 MarkerScene.prototype.render = function (perspectiveCamera, renderer) {
24600 renderer.render(this._scene, perspectiveCamera);
24601 this._needsRender = false;
24603 MarkerScene.prototype.update = function (id, position, latLon) {
24604 if (!(id in this._markers)) {
24607 var marker = this._markers[id];
24608 marker.updatePosition(position, latLon);
24609 this._needsRender = true;
24611 MarkerScene.prototype._dispose = function (id) {
24612 var marker = this._markers[id];
24613 this._scene.remove(marker.geometry);
24614 for (var _i = 0, _a = marker.getInteractiveObjects(); _i < _a.length; _i++) {
24615 var interactiveObject = _a[_i];
24616 var index = this._interactiveObjects.indexOf(interactiveObject);
24617 if (index !== -1) {
24618 this._interactiveObjects.splice(index, 1);
24621 console.warn("Object does not exist (" + interactiveObject.id + ") for " + id);
24623 delete this._objectMarkers[interactiveObject.uuid];
24625 marker.disposeGeometry();
24626 delete this._markers[id];
24628 return MarkerScene;
24630 exports.MarkerScene = MarkerScene;
24631 exports.default = MarkerScene;
24633 },{"three":176}],265:[function(require,module,exports){
24635 /// <reference path="../../../typings/index.d.ts" />
24636 Object.defineProperty(exports, "__esModule", { value: true });
24637 var rbush = require("rbush");
24638 var Subject_1 = require("rxjs/Subject");
24639 require("rxjs/add/operator/map");
24640 require("rxjs/add/operator/publishReplay");
24641 require("rxjs/add/operator/scan");
24642 var MarkerSet = (function () {
24643 function MarkerSet() {
24645 this._index = rbush(16, [".lon", ".lat", ".lon", ".lat"]);
24646 this._indexChanged$ = new Subject_1.Subject();
24647 this._updated$ = new Subject_1.Subject();
24649 Object.defineProperty(MarkerSet.prototype, "changed$", {
24651 return this._indexChanged$;
24656 Object.defineProperty(MarkerSet.prototype, "updated$", {
24658 return this._updated$;
24663 MarkerSet.prototype.add = function (markers) {
24665 var hash = this._hash;
24666 var index = this._index;
24667 for (var _i = 0, markers_1 = markers; _i < markers_1.length; _i++) {
24668 var marker = markers_1[_i];
24669 var id = marker.id;
24671 index.remove(hash[id]);
24672 updated.push(marker);
24675 lat: marker.latLon.lat,
24676 lon: marker.latLon.lon,
24680 index.insert(item);
24682 if (updated.length > 0) {
24683 this._updated$.next(updated);
24685 if (markers.length > updated.length) {
24686 this._indexChanged$.next(this);
24689 MarkerSet.prototype.has = function (id) {
24690 return id in this._hash;
24692 MarkerSet.prototype.get = function (id) {
24693 return this.has(id) ? this._hash[id].marker : undefined;
24695 MarkerSet.prototype.getAll = function () {
24698 .map(function (indexItem) {
24699 return indexItem.marker;
24702 MarkerSet.prototype.remove = function (ids) {
24703 var hash = this._hash;
24704 var index = this._index;
24705 var changed = false;
24706 for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
24707 var id = ids_1[_i];
24708 if (!(id in hash)) {
24711 var item = hash[id];
24712 index.remove(item);
24717 this._indexChanged$.next(this);
24720 MarkerSet.prototype.removeAll = function () {
24722 this._index.clear();
24723 this._indexChanged$.next(this);
24725 MarkerSet.prototype.search = function (_a) {
24726 var sw = _a[0], ne = _a[1];
24728 .search({ maxX: ne.lon, maxY: ne.lat, minX: sw.lon, minY: sw.lat })
24729 .map(function (indexItem) {
24730 return indexItem.marker;
24733 MarkerSet.prototype.update = function (marker) {
24734 var hash = this._hash;
24735 var index = this._index;
24736 var id = marker.id;
24737 if (!(id in hash)) {
24740 index.remove(hash[id]);
24742 lat: marker.latLon.lat,
24743 lon: marker.latLon.lon,
24747 index.insert(item);
24751 exports.MarkerSet = MarkerSet;
24752 exports.default = MarkerSet;
24754 },{"rbush":25,"rxjs/Subject":34,"rxjs/add/operator/map":65,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":73}],266:[function(require,module,exports){
24756 /// <reference path="../../../../typings/index.d.ts" />
24757 var __extends = (this && this.__extends) || (function () {
24758 var extendStatics = Object.setPrototypeOf ||
24759 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24760 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24761 return function (d, b) {
24762 extendStatics(d, b);
24763 function __() { this.constructor = d; }
24764 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24767 Object.defineProperty(exports, "__esModule", { value: true });
24768 var THREE = require("three");
24769 var Component_1 = require("../../../Component");
24771 * @class CircleMarker
24773 * @classdesc Non-interactive marker with a flat circle shape. The circle
24774 * marker can not be configured to be interactive.
24776 * Circle marker properties can not be updated after creation.
24778 * To create and add one `CircleMarker` with default configuration
24779 * and one with configuration use
24783 * var defaultMarker = new Mapillary.MarkerComponent.CircleMarker(
24785 * { lat: 0, lon: 0, });
24787 * var configuredMarker = new Mapillary.MarkerComponent.CircleMarker(
24789 * { lat: 0, lon: 0, },
24796 * markerComponent.add([defaultMarker, configuredMarker]);
24799 var CircleMarker = (function (_super) {
24800 __extends(CircleMarker, _super);
24801 function CircleMarker(id, latLon, options) {
24802 var _this = _super.call(this, id, latLon) || this;
24803 options = !!options ? options : {};
24804 _this._color = options.color != null ? options.color : 0xffffff;
24805 _this._opacity = options.opacity != null ? options.opacity : 0.4;
24806 _this._radius = options.radius != null ? options.radius : 1;
24809 CircleMarker.prototype._createGeometry = function (position) {
24810 var circle = new THREE.Mesh(new THREE.CircleGeometry(this._radius, 16), new THREE.MeshBasicMaterial({
24811 color: this._color,
24812 opacity: this._opacity,
24815 circle.up.fromArray([0, 0, 1]);
24816 circle.renderOrder = -1;
24817 var group = new THREE.Object3D();
24819 group.position.fromArray(position);
24820 this._geometry = group;
24822 CircleMarker.prototype._disposeGeometry = function () {
24823 for (var _i = 0, _a = this._geometry.children; _i < _a.length; _i++) {
24825 mesh.geometry.dispose();
24826 mesh.material.dispose();
24829 CircleMarker.prototype._getInteractiveObjects = function () {
24832 return CircleMarker;
24833 }(Component_1.Marker));
24834 exports.CircleMarker = CircleMarker;
24835 exports.default = CircleMarker;
24837 },{"../../../Component":226,"three":176}],267:[function(require,module,exports){
24839 /// <reference path="../../../../typings/index.d.ts" />
24840 Object.defineProperty(exports, "__esModule", { value: true });
24844 * @classdesc Represents an abstract marker class that should be extended
24845 * by marker implementations used in the marker component.
24847 var Marker = (function () {
24848 function Marker(id, latLon) {
24850 this._latLon = latLon;
24852 Object.defineProperty(Marker.prototype, "id", {
24855 * @returns {string} The id of the marker.
24863 Object.defineProperty(Marker.prototype, "geometry", {
24865 return this._geometry;
24870 Object.defineProperty(Marker.prototype, "latLon", {
24873 * @returns {ILatLon} The geographic coordinates of the marker.
24876 return this._latLon;
24881 Marker.prototype.createGeometry = function (position) {
24882 if (!!this._geometry) {
24885 this._createGeometry(position);
24886 // update matrix world if raycasting occurs before first render
24887 this._geometry.updateMatrixWorld(true);
24889 Marker.prototype.disposeGeometry = function () {
24890 if (!this._geometry) {
24893 this._disposeGeometry();
24894 this._geometry = undefined;
24896 Marker.prototype.getInteractiveObjects = function () {
24897 if (!this._geometry) {
24900 return this._getInteractiveObjects();
24902 Marker.prototype.lerpAltitude = function (alt, alpha) {
24903 if (!this._geometry) {
24906 this._geometry.position.z = (1 - alpha) * this._geometry.position.z + alpha * alt;
24908 Marker.prototype.updatePosition = function (position, latLon) {
24910 this._latLon.lat = latLon.lat;
24911 this._latLon.lon = latLon.lon;
24913 if (!this._geometry) {
24916 this._geometry.position.fromArray(position);
24917 this._geometry.updateMatrixWorld(true);
24921 exports.Marker = Marker;
24922 exports.default = Marker;
24924 },{}],268:[function(require,module,exports){
24926 /// <reference path="../../../../typings/index.d.ts" />
24927 var __extends = (this && this.__extends) || (function () {
24928 var extendStatics = Object.setPrototypeOf ||
24929 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24930 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24931 return function (d, b) {
24932 extendStatics(d, b);
24933 function __() { this.constructor = d; }
24934 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24937 Object.defineProperty(exports, "__esModule", { value: true });
24938 var THREE = require("three");
24939 var Component_1 = require("../../../Component");
24941 * @class SimpleMarker
24943 * @classdesc Interactive marker with ice cream shape. The sphere
24944 * inside the ice cream can be configured to be interactive.
24946 * Simple marker properties can not be updated after creation.
24948 * To create and add one `SimpleMarker` with default configuration
24949 * (non-interactive) and one interactive with configuration use
24953 * var defaultMarker = new Mapillary.MarkerComponent.SimpleMarker(
24955 * { lat: 0, lon: 0, });
24957 * var interactiveMarker = new Mapillary.MarkerComponent.SimpleMarker(
24959 * { lat: 0, lon: 0, },
24961 * ballColor: "#00f",
24962 * ballOpacity: 0.5,
24964 * interactive: true,
24969 * markerComponent.add([defaultMarker, interactiveMarker]);
24972 var SimpleMarker = (function (_super) {
24973 __extends(SimpleMarker, _super);
24974 function SimpleMarker(id, latLon, options) {
24975 var _this = _super.call(this, id, latLon) || this;
24976 options = !!options ? options : {};
24977 _this._ballColor = options.ballColor != null ? options.ballColor : 0xff0000;
24978 _this._ballOpacity = options.ballOpacity != null ? options.ballOpacity : 0.8;
24979 _this._circleToRayAngle = 2;
24980 _this._color = options.color != null ? options.color : 0xff0000;
24981 _this._interactive = !!options.interactive;
24982 _this._opacity = options.opacity != null ? options.opacity : 0.4;
24983 _this._radius = options.radius != null ? options.radius : 1;
24986 SimpleMarker.prototype._createGeometry = function (position) {
24987 var radius = this._radius;
24988 var cone = new THREE.Mesh(this._markerGeometry(radius, 8, 8), new THREE.MeshBasicMaterial({
24989 color: this._color,
24990 opacity: this._opacity,
24991 shading: THREE.SmoothShading,
24994 cone.renderOrder = 1;
24995 var ball = new THREE.Mesh(new THREE.SphereGeometry(radius / 2, 8, 8), new THREE.MeshBasicMaterial({
24996 color: this._ballColor,
24997 opacity: this._ballOpacity,
24998 shading: THREE.SmoothShading,
25001 ball.position.z = this._markerHeight(radius);
25002 var group = new THREE.Object3D();
25005 group.position.fromArray(position);
25006 this._geometry = group;
25008 SimpleMarker.prototype._disposeGeometry = function () {
25009 for (var _i = 0, _a = this._geometry.children; _i < _a.length; _i++) {
25011 mesh.geometry.dispose();
25012 mesh.material.dispose();
25015 SimpleMarker.prototype._getInteractiveObjects = function () {
25016 return this._interactive ? [this._geometry.children[0]] : [];
25018 SimpleMarker.prototype._markerHeight = function (radius) {
25019 var t = Math.tan(Math.PI - this._circleToRayAngle);
25020 return radius * Math.sqrt(1 + t * t);
25022 SimpleMarker.prototype._markerGeometry = function (radius, widthSegments, heightSegments) {
25023 var geometry = new THREE.Geometry();
25024 widthSegments = Math.max(3, Math.floor(widthSegments) || 8);
25025 heightSegments = Math.max(2, Math.floor(heightSegments) || 6);
25026 var height = this._markerHeight(radius);
25028 for (var y = 0; y <= heightSegments; ++y) {
25029 var verticesRow = [];
25030 for (var x = 0; x <= widthSegments; ++x) {
25031 var u = x / widthSegments * Math.PI * 2;
25032 var v = y / heightSegments * Math.PI;
25034 if (v < this._circleToRayAngle) {
25038 var t = Math.tan(v - this._circleToRayAngle);
25039 r = radius * Math.sqrt(1 + t * t);
25041 var vertex = new THREE.Vector3();
25042 vertex.x = r * Math.cos(u) * Math.sin(v);
25043 vertex.y = r * Math.sin(u) * Math.sin(v);
25044 vertex.z = r * Math.cos(v) + height;
25045 geometry.vertices.push(vertex);
25046 verticesRow.push(geometry.vertices.length - 1);
25048 vertices.push(verticesRow);
25050 for (var y = 0; y < heightSegments; ++y) {
25051 for (var x = 0; x < widthSegments; ++x) {
25052 var v1 = vertices[y][x + 1];
25053 var v2 = vertices[y][x];
25054 var v3 = vertices[y + 1][x];
25055 var v4 = vertices[y + 1][x + 1];
25056 var n1 = geometry.vertices[v1].clone().normalize();
25057 var n2 = geometry.vertices[v2].clone().normalize();
25058 var n3 = geometry.vertices[v3].clone().normalize();
25059 var n4 = geometry.vertices[v4].clone().normalize();
25060 geometry.faces.push(new THREE.Face3(v1, v2, v4, [n1, n2, n4]));
25061 geometry.faces.push(new THREE.Face3(v2, v3, v4, [n2.clone(), n3, n4.clone()]));
25064 geometry.computeFaceNormals();
25065 geometry.boundingSphere = new THREE.Sphere(new THREE.Vector3(), radius + height);
25068 return SimpleMarker;
25069 }(Component_1.Marker));
25070 exports.SimpleMarker = SimpleMarker;
25071 exports.default = SimpleMarker;
25073 },{"../../../Component":226,"three":176}],269:[function(require,module,exports){
25075 /// <reference path="../../../typings/index.d.ts" />
25076 var __extends = (this && this.__extends) || (function () {
25077 var extendStatics = Object.setPrototypeOf ||
25078 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25079 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25080 return function (d, b) {
25081 extendStatics(d, b);
25082 function __() { this.constructor = d; }
25083 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25086 Object.defineProperty(exports, "__esModule", { value: true });
25087 var Observable_1 = require("rxjs/Observable");
25088 var Component_1 = require("../../Component");
25090 * The `BounceHandler` ensures that the viewer bounces back to the image
25091 * when drag panning outside of the image edge.
25093 var BounceHandler = (function (_super) {
25094 __extends(BounceHandler, _super);
25095 function BounceHandler(component, container, navigator, viewportCoords, spatial) {
25096 var _this = _super.call(this, component, container, navigator, viewportCoords) || this;
25097 _this._spatial = spatial;
25098 _this._basicDistanceThreshold = 1e-3;
25099 _this._basicRotationThreshold = 5e-2;
25100 _this._bounceCoeff = 1e-1;
25103 BounceHandler.prototype._enable = function () {
25105 var inTransition$ = this._navigator.stateService.currentState$
25106 .map(function (frame) {
25107 return frame.state.alpha < 1;
25109 this._bounceSubscription = Observable_1.Observable
25110 .combineLatest(inTransition$, this._navigator.stateService.inTranslation$, this._container.mouseService.active$, this._container.touchService.active$)
25111 .map(function (noForce) {
25112 return noForce[0] || noForce[1] || noForce[2] || noForce[3];
25114 .distinctUntilChanged()
25115 .switchMap(function (noForce) {
25117 Observable_1.Observable.empty() :
25118 Observable_1.Observable.combineLatest(_this._container.renderService.renderCamera$, _this._navigator.stateService.currentTransform$.first());
25120 .subscribe(function (args) {
25121 var renderCamera = args[0];
25122 var perspectiveCamera = renderCamera.perspective;
25123 var transform = args[1];
25124 if (!transform.hasValidScale && renderCamera.camera.focal < 0.1) {
25127 if (renderCamera.perspective.aspect === 0 || renderCamera.perspective.aspect === Number.POSITIVE_INFINITY) {
25130 var distanceThreshold = _this._basicDistanceThreshold / Math.pow(2, renderCamera.zoom);
25131 var basicCenter = _this._viewportCoords.viewportToBasic(0, 0, transform, perspectiveCamera);
25132 if (Math.abs(basicCenter[0] - 0.5) < distanceThreshold && Math.abs(basicCenter[1] - 0.5) < distanceThreshold) {
25135 var basicDistances = _this._viewportCoords.getBasicDistances(transform, perspectiveCamera);
25138 if (basicDistances[0] < distanceThreshold && basicDistances[1] < distanceThreshold &&
25139 basicDistances[2] < distanceThreshold && basicDistances[3] < distanceThreshold) {
25142 if (Math.abs(basicDistances[0] - basicDistances[2]) < distanceThreshold &&
25143 Math.abs(basicDistances[1] - basicDistances[3]) < distanceThreshold) {
25146 var coeff = _this._bounceCoeff;
25147 if (basicDistances[1] > 0 && basicDistances[3] === 0) {
25148 basicX = -coeff * basicDistances[1];
25150 else if (basicDistances[1] === 0 && basicDistances[3] > 0) {
25151 basicX = coeff * basicDistances[3];
25153 else if (basicDistances[1] > 0 && basicDistances[3] > 0) {
25154 basicX = coeff * (basicDistances[3] - basicDistances[1]) / 2;
25156 if (basicDistances[0] > 0 && basicDistances[2] === 0) {
25157 basicY = coeff * basicDistances[0];
25159 else if (basicDistances[0] === 0 && basicDistances[2] > 0) {
25160 basicY = -coeff * basicDistances[2];
25162 else if (basicDistances[0] > 0 && basicDistances[2] > 0) {
25163 basicY = coeff * (basicDistances[0] - basicDistances[2]) / 2;
25165 var rotationThreshold = _this._basicRotationThreshold;
25166 basicX = _this._spatial.clamp(basicX, -rotationThreshold, rotationThreshold);
25167 basicY = _this._spatial.clamp(basicY, -rotationThreshold, rotationThreshold);
25168 _this._navigator.stateService.rotateBasicUnbounded([basicX, basicY]);
25171 BounceHandler.prototype._disable = function () {
25172 this._bounceSubscription.unsubscribe();
25174 BounceHandler.prototype._getConfiguration = function (enable) {
25177 return BounceHandler;
25178 }(Component_1.MouseHandlerBase));
25179 exports.BounceHandler = BounceHandler;
25180 exports.default = BounceHandler;
25182 },{"../../Component":226,"rxjs/Observable":29}],270:[function(require,module,exports){
25184 var __extends = (this && this.__extends) || (function () {
25185 var extendStatics = Object.setPrototypeOf ||
25186 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25187 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25188 return function (d, b) {
25189 extendStatics(d, b);
25190 function __() { this.constructor = d; }
25191 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25194 Object.defineProperty(exports, "__esModule", { value: true });
25195 var Observable_1 = require("rxjs/Observable");
25196 var Component_1 = require("../../Component");
25198 * The `DoubleClickZoomHandler` allows the user to zoom the viewer photo at a point by double clicking.
25202 * var mouseComponent = viewer.getComponent("mouse");
25204 * mouseComponent.doubleClickZoom.disable();
25205 * mouseComponent.doubleClickZoom.enable();
25207 * var isEnabled = mouseComponent.doubleClickZoom.isEnabled;
25210 var DoubleClickZoomHandler = (function (_super) {
25211 __extends(DoubleClickZoomHandler, _super);
25212 function DoubleClickZoomHandler() {
25213 return _super !== null && _super.apply(this, arguments) || this;
25215 DoubleClickZoomHandler.prototype._enable = function () {
25217 this._zoomSubscription = Observable_1.Observable
25218 .merge(this._container.mouseService
25219 .filtered$(this._component.name, this._container.mouseService.dblClick$), this._container.touchService.doubleTap$
25220 .map(function (e) {
25221 var touch = e.touches[0];
25222 return { clientX: touch.clientX, clientY: touch.clientY, shiftKey: e.shiftKey };
25224 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
25225 .subscribe(function (_a) {
25226 var event = _a[0], render = _a[1], transform = _a[2];
25227 var element = _this._container.element;
25228 var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
25229 var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
25230 var reference = transform.projectBasic(unprojected.toArray());
25231 var delta = !!event.shiftKey ? -1 : 1;
25232 _this._navigator.stateService.zoomIn(delta, reference);
25235 DoubleClickZoomHandler.prototype._disable = function () {
25236 this._zoomSubscription.unsubscribe();
25238 DoubleClickZoomHandler.prototype._getConfiguration = function (enable) {
25239 return { doubleClickZoom: enable };
25241 return DoubleClickZoomHandler;
25242 }(Component_1.MouseHandlerBase));
25243 exports.DoubleClickZoomHandler = DoubleClickZoomHandler;
25244 exports.default = DoubleClickZoomHandler;
25246 },{"../../Component":226,"rxjs/Observable":29}],271:[function(require,module,exports){
25248 /// <reference path="../../../typings/index.d.ts" />
25249 var __extends = (this && this.__extends) || (function () {
25250 var extendStatics = Object.setPrototypeOf ||
25251 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25252 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25253 return function (d, b) {
25254 extendStatics(d, b);
25255 function __() { this.constructor = d; }
25256 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25259 Object.defineProperty(exports, "__esModule", { value: true });
25260 var THREE = require("three");
25261 var Observable_1 = require("rxjs/Observable");
25262 var Component_1 = require("../../Component");
25264 * The `DragPanHandler` allows the user to pan the viewer photo by clicking and dragging the cursor.
25268 * var mouseComponent = viewer.getComponent("mouse");
25270 * mouseComponent.dragPan.disable();
25271 * mouseComponent.dragPan.enable();
25273 * var isEnabled = mouseComponent.dragPan.isEnabled;
25276 var DragPanHandler = (function (_super) {
25277 __extends(DragPanHandler, _super);
25278 function DragPanHandler(component, container, navigator, viewportCoords, spatial) {
25279 var _this = _super.call(this, component, container, navigator, viewportCoords) || this;
25280 _this._spatial = spatial;
25281 _this._basicRotationThreshold = 5e-2;
25282 _this._forceCoeff = 2e-1;
25285 DragPanHandler.prototype._enable = function () {
25287 var draggingStarted$ = this._container.mouseService
25288 .filtered$(this._component.name, this._container.mouseService.mouseDragStart$)
25289 .map(function (event) {
25292 var draggingStopped$ = this._container.mouseService
25293 .filtered$(this._component.name, this._container.mouseService.mouseDragEnd$)
25294 .map(function (event) {
25297 this._activeMouseSubscription = Observable_1.Observable
25298 .merge(draggingStarted$, draggingStopped$)
25299 .subscribe(this._container.mouseService.activate$);
25300 this._preventDefaultSubscription = Observable_1.Observable
25301 .merge(draggingStarted$, draggingStopped$)
25302 .switchMap(function (dragging) {
25304 _this._container.mouseService.documentMouseMove$ :
25305 Observable_1.Observable.empty();
25307 .merge(this._container.touchService.touchMove$)
25308 .subscribe(function (event) {
25309 event.preventDefault(); // prevent selection of content outside the viewer
25311 var touchMovingStarted$ = this._container.touchService.singleTouchDragStart$
25312 .map(function (event) {
25315 var touchMovingStopped$ = this._container.touchService.singleTouchDragEnd$
25316 .map(function (event) {
25319 this._activeTouchSubscription = Observable_1.Observable
25320 .merge(touchMovingStarted$, touchMovingStopped$)
25321 .subscribe(this._container.touchService.activate$);
25322 this._rotateBasicSubscription = this._navigator.stateService.currentState$
25323 .map(function (frame) {
25324 return frame.state.currentNode.fullPano || frame.state.nodesAhead < 1;
25326 .distinctUntilChanged()
25327 .switchMap(function (enable) {
25329 return Observable_1.Observable.empty();
25331 var mouseDrag$ = Observable_1.Observable
25332 .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$)
25333 .map(function (e) { return null; }))
25335 .filter(function (pair) {
25336 return pair[0] != null && pair[1] != null;
25338 var singleTouchDrag$ = Observable_1.Observable
25339 .merge(_this._container.touchService.singleTouchDragStart$, _this._container.touchService.singleTouchDrag$, _this._container.touchService.singleTouchDragEnd$.map(function (t) { return null; }))
25340 .map(function (event) {
25341 return event != null && event.touches.length > 0 ?
25342 event.touches[0] : null;
25345 .filter(function (pair) {
25346 return pair[0] != null && pair[1] != null;
25348 return Observable_1.Observable
25349 .merge(mouseDrag$, singleTouchDrag$);
25351 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, this._navigator.stateService.currentCamera$)
25352 .map(function (_a) {
25353 var events = _a[0], render = _a[1], transform = _a[2], c = _a[3];
25354 var camera = c.clone();
25355 var previousEvent = events[0];
25356 var event = events[1];
25357 var movementX = event.clientX - previousEvent.clientX;
25358 var movementY = event.clientY - previousEvent.clientY;
25359 var element = _this._container.element;
25360 var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
25361 var currentDirection = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective)
25362 .sub(render.perspective.position);
25363 var directionX = _this._viewportCoords.unprojectFromCanvas(canvasX - movementX, canvasY, element, render.perspective)
25364 .sub(render.perspective.position);
25365 var directionY = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY - movementY, element, render.perspective)
25366 .sub(render.perspective.position);
25367 var deltaPhi = (movementX > 0 ? 1 : -1) * directionX.angleTo(currentDirection);
25368 var deltaTheta = (movementY > 0 ? -1 : 1) * directionY.angleTo(currentDirection);
25369 var upQuaternion = new THREE.Quaternion().setFromUnitVectors(camera.up, new THREE.Vector3(0, 0, 1));
25370 var upQuaternionInverse = upQuaternion.clone().inverse();
25371 var offset = new THREE.Vector3();
25372 offset.copy(camera.lookat).sub(camera.position);
25373 offset.applyQuaternion(upQuaternion);
25374 var length = offset.length();
25375 var phi = Math.atan2(offset.y, offset.x);
25377 var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z);
25378 theta += deltaTheta;
25379 theta = Math.max(0.01, Math.min(Math.PI - 0.01, theta));
25380 offset.x = Math.sin(theta) * Math.cos(phi);
25381 offset.y = Math.sin(theta) * Math.sin(phi);
25382 offset.z = Math.cos(theta);
25383 offset.applyQuaternion(upQuaternionInverse);
25384 var lookat = new THREE.Vector3().copy(camera.position).add(offset.multiplyScalar(length));
25385 var basic = transform.projectBasic(lookat.toArray());
25386 var original = transform.projectBasic(camera.lookat.toArray());
25387 var x = basic[0] - original[0];
25388 var y = basic[1] - original[1];
25389 if (Math.abs(x) > 1) {
25392 else if (x > 0.5) {
25395 else if (x < -0.5) {
25398 var rotationThreshold = _this._basicRotationThreshold;
25399 x = _this._spatial.clamp(x, -rotationThreshold, rotationThreshold);
25400 y = _this._spatial.clamp(y, -rotationThreshold, rotationThreshold);
25401 if (transform.fullPano) {
25404 var pixelDistances = _this._viewportCoords.getPixelDistances(_this._container.element, transform, render.perspective);
25405 var coeff = _this._forceCoeff;
25406 if (pixelDistances[0] > 0 && y < 0 && basic[1] < 0.5) {
25407 y /= Math.max(1, coeff * pixelDistances[0]);
25409 if (pixelDistances[1] > 0 && x > 0 && basic[0] > 0.5) {
25410 x /= Math.max(1, coeff * pixelDistances[1]);
25412 if (pixelDistances[2] > 0 && y > 0 && basic[1] > 0.5) {
25413 y /= Math.max(1, coeff * pixelDistances[2]);
25415 if (pixelDistances[3] > 0 && x < 0 && basic[0] < 0.5) {
25416 x /= Math.max(1, coeff * pixelDistances[3]);
25420 .subscribe(function (basicRotation) {
25421 _this._navigator.stateService.rotateBasic(basicRotation);
25424 DragPanHandler.prototype._disable = function () {
25425 this._activeMouseSubscription.unsubscribe();
25426 this._activeTouchSubscription.unsubscribe();
25427 this._preventDefaultSubscription.unsubscribe();
25428 this._rotateBasicSubscription.unsubscribe();
25429 this._activeMouseSubscription = null;
25430 this._activeTouchSubscription = null;
25431 this._preventDefaultSubscription = null;
25432 this._rotateBasicSubscription = null;
25434 DragPanHandler.prototype._getConfiguration = function (enable) {
25435 return { dragPan: enable };
25437 return DragPanHandler;
25438 }(Component_1.MouseHandlerBase));
25439 exports.DragPanHandler = DragPanHandler;
25440 exports.default = DragPanHandler;
25442 },{"../../Component":226,"rxjs/Observable":29,"three":176}],272:[function(require,module,exports){
25444 var __extends = (this && this.__extends) || (function () {
25445 var extendStatics = Object.setPrototypeOf ||
25446 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25447 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25448 return function (d, b) {
25449 extendStatics(d, b);
25450 function __() { this.constructor = d; }
25451 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25454 Object.defineProperty(exports, "__esModule", { value: true });
25455 require("rxjs/add/observable/merge");
25456 require("rxjs/add/operator/filter");
25457 require("rxjs/add/operator/map");
25458 require("rxjs/add/operator/withLatestFrom");
25459 var Component_1 = require("../../Component");
25460 var Geo_1 = require("../../Geo");
25462 * @class MouseComponent
25464 * @classdesc Component handling mouse and touch events for camera movement.
25466 var MouseComponent = (function (_super) {
25467 __extends(MouseComponent, _super);
25468 function MouseComponent(name, container, navigator) {
25469 var _this = _super.call(this, name, container, navigator) || this;
25470 var spatial = new Geo_1.Spatial();
25471 var viewportCoords = new Geo_1.ViewportCoords();
25472 _this._spatial = spatial;
25473 _this._viewportCoords = viewportCoords;
25474 _this._bounceHandler = new Component_1.BounceHandler(_this, container, navigator, viewportCoords, spatial);
25475 _this._doubleClickZoomHandler = new Component_1.DoubleClickZoomHandler(_this, container, navigator, viewportCoords);
25476 _this._dragPanHandler = new Component_1.DragPanHandler(_this, container, navigator, viewportCoords, spatial);
25477 _this._scrollZoomHandler = new Component_1.ScrollZoomHandler(_this, container, navigator, viewportCoords);
25478 _this._touchZoomHandler = new Component_1.TouchZoomHandler(_this, container, navigator, viewportCoords);
25481 Object.defineProperty(MouseComponent.prototype, "doubleClickZoom", {
25483 * Get double click zoom.
25485 * @returns {DoubleClickZoomHandler} The double click zoom handler.
25488 return this._doubleClickZoomHandler;
25493 Object.defineProperty(MouseComponent.prototype, "dragPan", {
25497 * @returns {DragPanHandler} The drag pan handler.
25500 return this._dragPanHandler;
25505 Object.defineProperty(MouseComponent.prototype, "scrollZoom", {
25509 * @returns {ScrollZoomHandler} The scroll zoom handler.
25512 return this._scrollZoomHandler;
25517 Object.defineProperty(MouseComponent.prototype, "touchZoom", {
25521 * @returns {TouchZoomHandler} The touch zoom handler.
25524 return this._touchZoomHandler;
25529 MouseComponent.prototype._activate = function () {
25531 this._bounceHandler.enable();
25532 this._configurationSubscription = this._configuration$
25533 .subscribe(function (configuration) {
25534 if (configuration.doubleClickZoom) {
25535 _this._doubleClickZoomHandler.enable();
25538 _this._doubleClickZoomHandler.disable();
25540 if (configuration.dragPan) {
25541 _this._dragPanHandler.enable();
25544 _this._dragPanHandler.disable();
25546 if (configuration.scrollZoom) {
25547 _this._scrollZoomHandler.enable();
25550 _this._scrollZoomHandler.disable();
25552 if (configuration.touchZoom) {
25553 _this._touchZoomHandler.enable();
25556 _this._touchZoomHandler.disable();
25559 this._container.mouseService.claimMouse(this._name, 0);
25561 MouseComponent.prototype._deactivate = function () {
25562 this._container.mouseService.unclaimMouse(this._name);
25563 this._configurationSubscription.unsubscribe();
25564 this._bounceHandler.disable();
25565 this._doubleClickZoomHandler.disable();
25566 this._dragPanHandler.disable();
25567 this._scrollZoomHandler.disable();
25568 this._touchZoomHandler.disable();
25570 MouseComponent.prototype._getDefaultConfiguration = function () {
25571 return { doubleClickZoom: true, dragPan: true, scrollZoom: true, touchZoom: true };
25574 MouseComponent.componentName = "mouse";
25575 return MouseComponent;
25576 }(Component_1.Component));
25577 exports.MouseComponent = MouseComponent;
25578 Component_1.ComponentService.register(MouseComponent);
25579 exports.default = MouseComponent;
25581 },{"../../Component":226,"../../Geo":229,"rxjs/add/observable/merge":44,"rxjs/add/operator/filter":61,"rxjs/add/operator/map":65,"rxjs/add/operator/withLatestFrom":83}],273:[function(require,module,exports){
25583 Object.defineProperty(exports, "__esModule", { value: true });
25584 var MouseHandlerBase = (function () {
25585 function MouseHandlerBase(component, container, navigator, viewportCoords) {
25586 this._component = component;
25587 this._container = container;
25588 this._navigator = navigator;
25589 this._viewportCoords = viewportCoords;
25590 this._enabled = false;
25592 Object.defineProperty(MouseHandlerBase.prototype, "isEnabled", {
25594 * Returns a Boolean indicating whether the interaction is enabled.
25596 * @returns {boolean} `true` if the interaction is enabled.
25599 return this._enabled;
25605 * Enables the interaction.
25607 * @example ```mouseComponent.<handler-name>.enable();```
25609 MouseHandlerBase.prototype.enable = function () {
25610 if (this._enabled || !this._component.activated) {
25614 this._enabled = true;
25615 this._component.configure(this._getConfiguration(true));
25618 * Disables the interaction.
25620 * @example ```mouseComponent.<handler-name>.disable();```
25622 MouseHandlerBase.prototype.disable = function () {
25623 if (!this._enabled) {
25627 this._enabled = false;
25628 if (this._component.activated) {
25629 this._component.configure(this._getConfiguration(false));
25632 return MouseHandlerBase;
25634 exports.MouseHandlerBase = MouseHandlerBase;
25635 exports.default = MouseHandlerBase;
25637 },{}],274:[function(require,module,exports){
25639 var __extends = (this && this.__extends) || (function () {
25640 var extendStatics = Object.setPrototypeOf ||
25641 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25642 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25643 return function (d, b) {
25644 extendStatics(d, b);
25645 function __() { this.constructor = d; }
25646 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25649 Object.defineProperty(exports, "__esModule", { value: true });
25650 var Component_1 = require("../../Component");
25652 * The `ScrollZoomHandler` allows the user to zoom the viewer photo by scrolling.
25656 * var mouseComponent = viewer.getComponent("mouse");
25658 * mouseComponent.scrollZoom.disable();
25659 * mouseComponent.scrollZoom.enable();
25661 * var isEnabled = mouseComponent.scrollZoom.isEnabled;
25664 var ScrollZoomHandler = (function (_super) {
25665 __extends(ScrollZoomHandler, _super);
25666 function ScrollZoomHandler() {
25667 return _super !== null && _super.apply(this, arguments) || this;
25669 ScrollZoomHandler.prototype._enable = function () {
25671 this._preventDefaultSubscription = this._container.mouseService.mouseWheel$
25672 .subscribe(function (event) {
25673 event.preventDefault();
25675 this._zoomSubscription = this._container.mouseService
25676 .filtered$(this._component.name, this._container.mouseService.mouseWheel$)
25677 .withLatestFrom(this._navigator.stateService.currentState$, function (w, f) {
25680 .filter(function (args) {
25681 var state = args[1].state;
25682 return state.currentNode.fullPano || state.nodesAhead < 1;
25684 .map(function (args) {
25687 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, function (w, r, t) {
25690 .subscribe(function (args) {
25691 var event = args[0];
25692 var render = args[1];
25693 var transform = args[2];
25694 var element = _this._container.element;
25695 var _a = _this._viewportCoords.canvasPosition(event, element), canvasX = _a[0], canvasY = _a[1];
25696 var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
25697 var reference = transform.projectBasic(unprojected.toArray());
25698 var deltaY = event.deltaY;
25699 if (event.deltaMode === 1) {
25700 deltaY = 40 * deltaY;
25702 else if (event.deltaMode === 2) {
25703 deltaY = 800 * deltaY;
25705 var canvasSize = _this._viewportCoords.containerToCanvas(element);
25706 var zoom = -3 * deltaY / canvasSize[1];
25707 _this._navigator.stateService.zoomIn(zoom, reference);
25710 ScrollZoomHandler.prototype._disable = function () {
25711 this._preventDefaultSubscription.unsubscribe();
25712 this._zoomSubscription.unsubscribe();
25713 this._preventDefaultSubscription = null;
25714 this._zoomSubscription = null;
25716 ScrollZoomHandler.prototype._getConfiguration = function (enable) {
25717 return { scrollZoom: enable };
25719 return ScrollZoomHandler;
25720 }(Component_1.MouseHandlerBase));
25721 exports.ScrollZoomHandler = ScrollZoomHandler;
25722 exports.default = ScrollZoomHandler;
25724 },{"../../Component":226}],275:[function(require,module,exports){
25726 /// <reference path="../../../typings/index.d.ts" />
25727 var __extends = (this && this.__extends) || (function () {
25728 var extendStatics = Object.setPrototypeOf ||
25729 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25730 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25731 return function (d, b) {
25732 extendStatics(d, b);
25733 function __() { this.constructor = d; }
25734 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25737 Object.defineProperty(exports, "__esModule", { value: true });
25738 var Observable_1 = require("rxjs/Observable");
25739 var Component_1 = require("../../Component");
25741 * The `TouchZoomHandler` allows the user to zoom the viewer photo by pinching on a touchscreen.
25745 * var mouseComponent = viewer.getComponent("mouse");
25747 * mouseComponent.touchZoom.disable();
25748 * mouseComponent.touchZoom.enable();
25750 * var isEnabled = mouseComponent.touchZoom.isEnabled;
25753 var TouchZoomHandler = (function (_super) {
25754 __extends(TouchZoomHandler, _super);
25755 function TouchZoomHandler() {
25756 return _super !== null && _super.apply(this, arguments) || this;
25758 TouchZoomHandler.prototype._enable = function () {
25760 this._preventDefaultSubscription = this._container.touchService.pinch$
25761 .subscribe(function (pinch) {
25762 pinch.originalEvent.preventDefault();
25764 var pinchStarted$ = this._container.touchService.pinchStart$
25765 .map(function (event) {
25768 var pinchStopped$ = this._container.touchService.pinchEnd$
25769 .map(function (event) {
25772 this._activeSubscription = Observable_1.Observable
25773 .merge(pinchStarted$, pinchStopped$)
25774 .subscribe(this._container.touchService.activate$);
25775 this._zoomSubscription = this._container.touchService.pinch$
25776 .withLatestFrom(this._navigator.stateService.currentState$)
25777 .filter(function (args) {
25778 var state = args[1].state;
25779 return state.currentNode.fullPano || state.nodesAhead < 1;
25781 .map(function (args) {
25784 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
25785 .subscribe(function (_a) {
25786 var pinch = _a[0], render = _a[1], transform = _a[2];
25787 var element = _this._container.element;
25788 var _b = _this._viewportCoords.canvasPosition(pinch, element), canvasX = _b[0], canvasY = _b[1];
25789 var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
25790 var reference = transform.projectBasic(unprojected.toArray());
25791 var _c = _this._viewportCoords.containerToCanvas(element), canvasWidth = _c[0], canvasHeight = _c[1];
25792 var zoom = 3 * pinch.distanceChange / Math.min(canvasWidth, canvasHeight);
25793 _this._navigator.stateService.zoomIn(zoom, reference);
25796 TouchZoomHandler.prototype._disable = function () {
25797 this._activeSubscription.unsubscribe();
25798 this._preventDefaultSubscription.unsubscribe();
25799 this._zoomSubscription.unsubscribe();
25800 this._preventDefaultSubscription = null;
25801 this._zoomSubscription = null;
25803 TouchZoomHandler.prototype._getConfiguration = function (enable) {
25804 return { touchZoom: enable };
25806 return TouchZoomHandler;
25807 }(Component_1.MouseHandlerBase));
25808 exports.TouchZoomHandler = TouchZoomHandler;
25809 exports.default = TouchZoomHandler;
25811 },{"../../Component":226,"rxjs/Observable":29}],276:[function(require,module,exports){
25813 Object.defineProperty(exports, "__esModule", { value: true });
25814 var Popup_1 = require("./popup/Popup");
25815 exports.Popup = Popup_1.Popup;
25816 var PopupComponent_1 = require("./PopupComponent");
25817 exports.PopupComponent = PopupComponent_1.PopupComponent;
25819 },{"./PopupComponent":277,"./popup/Popup":278}],277:[function(require,module,exports){
25821 var __extends = (this && this.__extends) || (function () {
25822 var extendStatics = Object.setPrototypeOf ||
25823 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25824 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25825 return function (d, b) {
25826 extendStatics(d, b);
25827 function __() { this.constructor = d; }
25828 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25831 Object.defineProperty(exports, "__esModule", { value: true });
25832 var Observable_1 = require("rxjs/Observable");
25833 var Subject_1 = require("rxjs/Subject");
25834 var Component_1 = require("../../Component");
25836 * @class PopupComponent
25838 * @classdesc Component for showing HTML popup objects.
25840 * The `add` method is used for adding new popups. Popups are removed by reference.
25842 * It is not possible to update popups in the set by updating any properties
25843 * directly on the popup object. Popups need to be replaced by
25844 * removing them and creating new ones with relevant changed properties and
25845 * adding those instead.
25847 * Popups are only relevant to a single image because they are based on
25848 * 2D basic image coordinates. Popups related to a certain image should
25849 * be removed when the viewer is moved to another node.
25851 * To retrive and use the popup component
25855 * var viewer = new Mapillary.Viewer(
25859 * { component: { popup: true } });
25861 * var popupComponent = viewer.getComponent("popup");
25864 var PopupComponent = (function (_super) {
25865 __extends(PopupComponent, _super);
25866 function PopupComponent(name, container, navigator) {
25867 var _this = _super.call(this, name, container, navigator) || this;
25868 _this._popups = [];
25869 _this._added$ = new Subject_1.Subject();
25870 _this._popups$ = new Subject_1.Subject();
25874 * Add popups to the popups set.
25876 * @description Adding a new popup never replaces an old one
25877 * because they are stored by reference. Adding an already
25878 * existing popup has no effect.
25880 * @param {Array<Popup>} popups - Popups to add.
25882 * @example ```popupComponent.add([popup1, popup2]);```
25884 PopupComponent.prototype.add = function (popups) {
25885 for (var _i = 0, popups_1 = popups; _i < popups_1.length; _i++) {
25886 var popup = popups_1[_i];
25887 if (this._popups.indexOf(popup) !== -1) {
25890 this._popups.push(popup);
25891 if (this._activated) {
25892 popup.setParentContainer(this._popupContainer);
25895 this._added$.next(popups);
25896 this._popups$.next(this._popups);
25899 * Returns an array of all popups.
25901 * @example ```var popups = popupComponent.getAll();```
25903 PopupComponent.prototype.getAll = function () {
25904 return this._popups.slice();
25907 * Remove popups based on reference from the popup set.
25909 * @param {Array<Popup>} popups - Popups to remove.
25911 * @example ```popupComponent.remove([popup1, popup2]);```
25913 PopupComponent.prototype.remove = function (popups) {
25914 for (var _i = 0, popups_2 = popups; _i < popups_2.length; _i++) {
25915 var popup = popups_2[_i];
25916 this._remove(popup);
25918 this._popups$.next(this._popups);
25921 * Remove all popups from the popup set.
25923 * @example ```popupComponent.removeAll();```
25925 PopupComponent.prototype.removeAll = function () {
25926 for (var _i = 0, _a = this._popups.slice(); _i < _a.length; _i++) {
25927 var popup = _a[_i];
25928 this._remove(popup);
25930 this._popups$.next(this._popups);
25932 PopupComponent.prototype._activate = function () {
25934 this._popupContainer = document.createElement("div");
25935 this._popupContainer.className = "mapillary-js-popup-container";
25936 this._container.element.appendChild(this._popupContainer);
25937 for (var _i = 0, _a = this._popups; _i < _a.length; _i++) {
25938 var popup = _a[_i];
25939 popup.setParentContainer(this._popupContainer);
25941 this._updateAllSubscription = Observable_1.Observable
25942 .combineLatest(this._container.renderService.renderCamera$, this._container.renderService.size$, this._navigator.stateService.currentTransform$)
25943 .subscribe(function (_a) {
25944 var renderCamera = _a[0], size = _a[1], transform = _a[2];
25945 for (var _i = 0, _b = _this._popups; _i < _b.length; _i++) {
25946 var popup = _b[_i];
25947 popup.update(renderCamera, size, transform);
25950 var changed$ = this._popups$
25951 .startWith(this._popups)
25952 .switchMap(function (popups) {
25953 return Observable_1.Observable
25955 .mergeMap(function (popup) {
25956 return popup.changed$;
25959 .map(function (popup) {
25962 this._updateAddedChangedSubscription = this._added$
25964 .withLatestFrom(this._container.renderService.renderCamera$, this._container.renderService.size$, this._navigator.stateService.currentTransform$)
25965 .subscribe(function (_a) {
25966 var popups = _a[0], renderCamera = _a[1], size = _a[2], transform = _a[3];
25967 for (var _i = 0, popups_3 = popups; _i < popups_3.length; _i++) {
25968 var popup = popups_3[_i];
25969 popup.update(renderCamera, size, transform);
25973 PopupComponent.prototype._deactivate = function () {
25974 this._updateAllSubscription.unsubscribe();
25975 this._updateAddedChangedSubscription.unsubscribe();
25976 for (var _i = 0, _a = this._popups; _i < _a.length; _i++) {
25977 var popup = _a[_i];
25980 this._container.element.removeChild(this._popupContainer);
25981 delete this._popupContainer;
25983 PopupComponent.prototype._getDefaultConfiguration = function () {
25986 PopupComponent.prototype._remove = function (popup) {
25987 var index = this._popups.indexOf(popup);
25988 if (index === -1) {
25991 var removed = this._popups.splice(index, 1)[0];
25992 if (this._activated) {
25996 PopupComponent.componentName = "popup";
25997 return PopupComponent;
25998 }(Component_1.Component));
25999 exports.PopupComponent = PopupComponent;
26000 Component_1.ComponentService.register(PopupComponent);
26001 exports.default = PopupComponent;
26003 },{"../../Component":226,"rxjs/Observable":29,"rxjs/Subject":34}],278:[function(require,module,exports){
26005 /// <reference path="../../../../typings/index.d.ts" />
26006 Object.defineProperty(exports, "__esModule", { value: true });
26007 var Subject_1 = require("rxjs/Subject");
26008 var Geo_1 = require("../../../Geo");
26009 var Viewer_1 = require("../../../Viewer");
26013 * @classdesc Popup instance for rendering custom HTML content
26014 * on top of images. Popups are based on 2D basic image coordinates
26015 * (see the {@link Viewer} class documentation for more information about coordinate
26016 * systems) and a certain popup is therefore only relevant to a single image.
26017 * Popups related to a certain image should be removed when moving
26018 * to another image.
26020 * A popup must have both its content and its point or rect set to be
26021 * rendered. Popup options can not be updated after creation but the
26022 * basic point or rect as well as its content can be changed by calling
26023 * the appropriate methods.
26025 * To create and add one `Popup` with default configuration
26026 * (tooltip visuals and automatic float) and one with specific options
26031 * var defaultSpan = document.createElement('span');
26032 * defaultSpan.innerHTML = 'hello default';
26034 * var defaultPopup = new Mapillary.PopupComponent.Popup();
26035 * defaultPopup.setDOMContent(defaultSpan);
26036 * defaultPopup.setBasicPoint([0.3, 0.3]);
26038 * var cleanSpan = document.createElement('span');
26039 * cleanSpan.innerHTML = 'hello clean';
26041 * var cleanPopup = new Mapillary.PopupComponent.Popup({
26043 * float: Mapillary.Alignment.Top,
26048 * cleanPopup.setDOMContent(cleanSpan);
26049 * cleanPopup.setBasicPoint([0.6, 0.6]);
26051 * popupComponent.add([defaultPopup, cleanPopup]);
26054 * @description Implementation of API methods and API documentation inspired
26055 * by/used from https://github.com/mapbox/mapbox-gl-js/blob/v0.38.0/src/ui/popup.js
26057 var Popup = (function () {
26058 function Popup(options, viewportCoords) {
26059 this._options = {};
26061 this._options.clean = options.clean;
26062 this._options.float = options.float;
26063 this._options.offset = options.offset;
26064 this._options.opacity = options.opacity;
26065 this._options.position = options.position;
26067 this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
26068 this._notifyChanged$ = new Subject_1.Subject();
26070 Object.defineProperty(Popup.prototype, "changed$", {
26074 * @description Internal observable used by the component to
26075 * render the popup when its position or content has changed.
26078 return this._notifyChanged$;
26086 * @description Internal method used by the component to
26087 * remove all references to the popup.
26089 Popup.prototype.remove = function () {
26090 if (this._content && this._content.parentNode) {
26091 this._content.parentNode.removeChild(this._content);
26093 if (this._container) {
26094 this._container.parentNode.removeChild(this._container);
26095 delete this._container;
26097 if (this._parentContainer) {
26098 delete this._parentContainer;
26102 * Sets a 2D basic image coordinates point to the popup's anchor, and
26103 * moves the popup to it.
26105 * @description Overwrites any previously set point or rect.
26107 * @param {Array<number>} basicPoint - Point in 2D basic image coordinates.
26111 * var popup = new Mapillary.PopupComponent.Popup();
26112 * popup.setText('hello image');
26113 * popup.setBasicPoint([0.3, 0.3]);
26115 * popupComponent.add([popup]);
26118 Popup.prototype.setBasicPoint = function (basicPoint) {
26119 this._point = basicPoint.slice();
26121 this._notifyChanged$.next(this);
26124 * Sets a 2D basic image coordinates rect to the popup's anchor, and
26125 * moves the popup to it.
26127 * @description Overwrites any previously set point or rect.
26129 * @param {Array<number>} basicRect - Rect in 2D basic image
26130 * coordinates ([topLeftX, topLeftY, bottomRightX, bottomRightY]) .
26134 * var popup = new Mapillary.PopupComponent.Popup();
26135 * popup.setText('hello image');
26136 * popup.setBasicRect([0.3, 0.3, 0.5, 0.6]);
26138 * popupComponent.add([popup]);
26141 Popup.prototype.setBasicRect = function (basicRect) {
26142 this._rect = basicRect.slice();
26143 this._point = null;
26144 this._notifyChanged$.next(this);
26147 * Sets the popup's content to the element provided as a DOM node.
26149 * @param {Node} htmlNode - A DOM node to be used as content for the popup.
26153 * var div = document.createElement('div');
26154 * div.innerHTML = 'hello image';
26156 * var popup = new Mapillary.PopupComponent.Popup();
26157 * popup.setDOMContent(div);
26158 * popup.setBasicPoint([0.3, 0.3]);
26160 * popupComponent.add([popup]);
26163 Popup.prototype.setDOMContent = function (htmlNode) {
26164 if (this._content && this._content.parentNode) {
26165 this._content.parentNode.removeChild(this._content);
26167 var className = "mapillaryjs-popup-content" + (this._options.clean === true ? "-clean" : "");
26168 this._content = this._createElement("div", className, this._container);
26169 this._content.appendChild(htmlNode);
26170 this._notifyChanged$.next(this);
26173 * Sets the popup's content to the HTML provided as a string.
26175 * @description This method does not perform HTML filtering or sanitization,
26176 * and must be used only with trusted content. Consider Popup#setText if the
26177 * content is an untrusted text string.
26179 * @param {string} html - A string representing HTML content for the popup.
26183 * var popup = new Mapillary.PopupComponent.Popup();
26184 * popup.setHTML('<div>hello image</div>');
26185 * popup.setBasicPoint([0.3, 0.3]);
26187 * popupComponent.add([popup]);
26190 Popup.prototype.setHTML = function (html) {
26191 var frag = document.createDocumentFragment();
26192 var temp = document.createElement("body");
26194 temp.innerHTML = html;
26196 child = temp.firstChild;
26200 frag.appendChild(child);
26202 this.setDOMContent(frag);
26205 * Sets the popup's content to a string of text.
26207 * @description This function creates a Text node in the DOM, so it cannot insert raw HTML.
26208 * Use this method for security against XSS if the popup content is user-provided.
26210 * @param {string} text - Textual content for the popup.
26214 * var popup = new Mapillary.PopupComponent.Popup();
26215 * popup.setText('hello image');
26216 * popup.setBasicPoint([0.3, 0.3]);
26218 * popupComponent.add([popup]);
26221 Popup.prototype.setText = function (text) {
26222 this.setDOMContent(document.createTextNode(text));
26227 * @description Internal method for attaching the popup to
26228 * its parent container so that it is rendered in the DOM tree.
26230 Popup.prototype.setParentContainer = function (parentContainer) {
26231 this._parentContainer = parentContainer;
26236 * @description Internal method for updating the rendered
26237 * position of the popup called by the popup component.
26239 Popup.prototype.update = function (renderCamera, size, transform) {
26240 if (!this._parentContainer || !this._content) {
26243 if (!this._point && !this._rect) {
26246 if (!this._container) {
26247 this._container = this._createElement("div", "mapillaryjs-popup", this._parentContainer);
26248 var showTip = this._options.clean !== true &&
26249 this._options.float !== Viewer_1.Alignment.Center;
26251 this._tip = this._createElement("div", "mapillaryjs-popup-tip", this._container);
26252 this._createElement("div", "mapillaryjs-popup-tip-inner", this._tip);
26254 this._container.appendChild(this._content);
26255 this._parentContainer.appendChild(this._container);
26256 if (this._options.opacity != null) {
26257 this._container.style.opacity = this._options.opacity.toString();
26260 var pointPixel = null;
26261 var position = this._alignmentToPopupAligment(this._options.position);
26262 var float = this._alignmentToPopupAligment(this._options.float);
26263 if (this._point != null) {
26265 this._viewportCoords.basicToCanvasSafe(this._point[0], this._point[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective);
26268 _a = this._rectToPixel(this._rect, position, renderCamera, size, transform), pointPixel = _a[0], position = _a[1];
26273 if (pointPixel == null) {
26274 this._container.style.visibility = "hidden";
26277 this._container.style.visibility = "visible";
26279 var width = this._container.offsetWidth;
26280 var height = this._container.offsetHeight;
26281 var floats = this._pixelToFloats(pointPixel, size, width, height);
26282 float = floats.length === 0 ? "bottom" : floats.join("-");
26284 if (!!this._options.offset) {
26285 var offset = this._options.offset;
26286 var sign = offset >= 0 ? 1 : -1;
26287 var cornerOffset = sign * Math.round(Math.sqrt(0.5 * Math.pow(offset, 2)));
26288 var floatOffset = {
26289 "bottom": [0, offset],
26290 "bottom-left": [-cornerOffset, cornerOffset],
26291 "bottom-right": [cornerOffset, cornerOffset],
26293 "left": [-offset, 0],
26294 "right": [offset, 0],
26295 "top": [0, -offset],
26296 "top-left": [-cornerOffset, -cornerOffset],
26297 "top-right": [cornerOffset, -cornerOffset],
26299 pointPixel = [pointPixel[0] + floatOffset[float][0], pointPixel[1] + floatOffset[float][1]];
26301 pointPixel = [Math.round(pointPixel[0]), Math.round(pointPixel[1])];
26302 var floatTranslate = {
26303 "bottom": "translate(-50%,0)",
26304 "bottom-left": "translate(-100%,0)",
26305 "bottom-right": "translate(0,0)",
26306 "center": "translate(-50%,-50%)",
26307 "left": "translate(-100%,-50%)",
26308 "right": "translate(0,-50%)",
26309 "top": "translate(-50%,-100%)",
26310 "top-left": "translate(-100%,-100%)",
26311 "top-right": "translate(0,-100%)",
26313 var classList = this._container.classList;
26314 for (var key in floatTranslate) {
26315 if (!floatTranslate.hasOwnProperty(key)) {
26318 classList.remove("mapillaryjs-popup-float-" + key);
26320 classList.add("mapillaryjs-popup-float-" + float);
26321 this._container.style.transform = floatTranslate[float] + " translate(" + pointPixel[0] + "px," + pointPixel[1] + "px)";
26324 Popup.prototype._createElement = function (tagName, className, container) {
26325 var element = document.createElement(tagName);
26327 element.className = className;
26330 container.appendChild(element);
26334 Popup.prototype._rectToPixel = function (rect, position, renderCamera, size, transform) {
26336 var width = this._container.offsetWidth;
26337 var height = this._container.offsetHeight;
26338 var floatOffsets = {
26339 "bottom": [0, height / 2],
26340 "bottom-left": [-width / 2, height / 2],
26341 "bottom-right": [width / 2, height / 2],
26342 "left": [-width / 2, 0],
26343 "right": [width / 2, 0],
26344 "top": [0, -height / 2],
26345 "top-left": [-width / 2, -height / 2],
26346 "top-right": [width / 2, -height / 2],
26348 var automaticPositions = ["bottom", "top", "left", "right"];
26349 var largestVisibleArea = [0, null, null];
26350 for (var _i = 0, automaticPositions_1 = automaticPositions; _i < automaticPositions_1.length; _i++) {
26351 var automaticPosition = automaticPositions_1[_i];
26352 var pointBasic_1 = this._pointFromRectPosition(rect, automaticPosition);
26353 var pointPixel = this._viewportCoords.basicToCanvasSafe(pointBasic_1[0], pointBasic_1[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective);
26354 if (pointPixel == null) {
26357 var floatOffset = floatOffsets[automaticPosition];
26358 var offsetedPosition = [pointPixel[0] + floatOffset[0], pointPixel[1] + floatOffset[1]];
26359 var floats = this._pixelToFloats(offsetedPosition, size, width, height / 2);
26360 if (floats.length === 0 &&
26361 pointPixel[0] > 0 &&
26362 pointPixel[0] < size.width &&
26363 pointPixel[1] > 0 &&
26364 pointPixel[1] < size.height) {
26365 return [pointPixel, automaticPosition];
26367 var minX = Math.max(offsetedPosition[0] - width / 2, 0);
26368 var maxX = Math.min(offsetedPosition[0] + width / 2, size.width);
26369 var minY = Math.max(offsetedPosition[1] - height / 2, 0);
26370 var maxY = Math.min(offsetedPosition[1] + height / 2, size.height);
26371 var visibleX = Math.max(0, maxX - minX);
26372 var visibleY = Math.max(0, maxY - minY);
26373 var visibleArea = visibleX * visibleY;
26374 if (visibleArea > largestVisibleArea[0]) {
26375 largestVisibleArea[0] = visibleArea;
26376 largestVisibleArea[1] = pointPixel;
26377 largestVisibleArea[2] = automaticPosition;
26380 if (largestVisibleArea[0] > 0) {
26381 return [largestVisibleArea[1], largestVisibleArea[2]];
26384 var pointBasic = this._pointFromRectPosition(rect, position);
26385 var pointCanvas = this._viewportCoords.basicToCanvasSafe(pointBasic[0], pointBasic[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective);
26386 return [pointCanvas, position != null ? position : "bottom"];
26388 Popup.prototype._alignmentToPopupAligment = function (float) {
26390 case Viewer_1.Alignment.Bottom:
26392 case Viewer_1.Alignment.BottomLeft:
26393 return "bottom-left";
26394 case Viewer_1.Alignment.BottomRight:
26395 return "bottom-right";
26396 case Viewer_1.Alignment.Center:
26398 case Viewer_1.Alignment.Left:
26400 case Viewer_1.Alignment.Right:
26402 case Viewer_1.Alignment.Top:
26404 case Viewer_1.Alignment.TopLeft:
26406 case Viewer_1.Alignment.TopRight:
26407 return "top-right";
26412 Popup.prototype._pixelToFloats = function (pointPixel, size, width, height) {
26414 if (pointPixel[1] < height) {
26415 floats.push("bottom");
26417 else if (pointPixel[1] > size.height - height) {
26418 floats.push("top");
26420 if (pointPixel[0] < width / 2) {
26421 floats.push("right");
26423 else if (pointPixel[0] > size.width - width / 2) {
26424 floats.push("left");
26428 Popup.prototype._pointFromRectPosition = function (rect, position) {
26429 switch (position) {
26431 return [(rect[0] + rect[2]) / 2, rect[3]];
26432 case "bottom-left":
26433 return [rect[0], rect[3]];
26434 case "bottom-right":
26435 return [rect[2], rect[3]];
26437 return [(rect[0] + rect[2]) / 2, (rect[1] + rect[3]) / 2];
26439 return [rect[0], (rect[1] + rect[3]) / 2];
26441 return [rect[2], (rect[1] + rect[3]) / 2];
26443 return [(rect[0] + rect[2]) / 2, rect[1]];
26445 return [rect[0], rect[1]];
26447 return [rect[2], rect[1]];
26449 return [(rect[0] + rect[2]) / 2, rect[3]];
26454 exports.Popup = Popup;
26455 exports.default = Popup;
26457 },{"../../../Geo":229,"../../../Viewer":236,"rxjs/Subject":34}],279:[function(require,module,exports){
26459 /// <reference path="../../../typings/index.d.ts" />
26460 var __extends = (this && this.__extends) || (function () {
26461 var extendStatics = Object.setPrototypeOf ||
26462 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26463 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
26464 return function (d, b) {
26465 extendStatics(d, b);
26466 function __() { this.constructor = d; }
26467 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26470 Object.defineProperty(exports, "__esModule", { value: true });
26471 var Observable_1 = require("rxjs/Observable");
26472 var Subject_1 = require("rxjs/Subject");
26473 require("rxjs/add/observable/combineLatest");
26474 require("rxjs/add/observable/of");
26475 require("rxjs/add/operator/bufferCount");
26476 require("rxjs/add/operator/concat");
26477 require("rxjs/add/operator/distinctUntilChanged");
26478 require("rxjs/add/operator/filter");
26479 require("rxjs/add/operator/finally");
26480 require("rxjs/add/operator/first");
26481 require("rxjs/add/operator/map");
26482 require("rxjs/add/operator/publishReplay");
26483 require("rxjs/add/operator/scan");
26484 require("rxjs/add/operator/share");
26485 require("rxjs/add/operator/switchMap");
26486 require("rxjs/add/operator/takeUntil");
26487 require("rxjs/add/operator/withLatestFrom");
26488 var Component_1 = require("../../Component");
26489 var Edge_1 = require("../../Edge");
26491 * @class SequenceComponent
26492 * @classdesc Component showing navigation arrows for sequence directions
26493 * as well as playing button. Exposes an API to start and stop play.
26495 var SequenceComponent = (function (_super) {
26496 __extends(SequenceComponent, _super);
26497 function SequenceComponent(name, container, navigator) {
26498 var _this = _super.call(this, name, container, navigator) || this;
26499 _this._nodesAhead = 5;
26500 _this._configurationOperation$ = new Subject_1.Subject();
26501 _this._sequenceDOMRenderer = new Component_1.SequenceDOMRenderer(container.element);
26502 _this._sequenceDOMInteraction = new Component_1.SequenceDOMInteraction();
26503 _this._containerWidth$ = new Subject_1.Subject();
26504 _this._hoveredKeySubject$ = new Subject_1.Subject();
26505 _this._hoveredKey$ = _this._hoveredKeySubject$.share();
26506 _this._edgeStatus$ = _this._navigator.stateService.currentNode$
26507 .switchMap(function (node) {
26508 return node.sequenceEdges$;
26514 Object.defineProperty(SequenceComponent.prototype, "hoveredKey$", {
26516 * Get hovered key observable.
26518 * @description An observable emitting the key of the node for the direction
26519 * arrow that is being hovered. When the mouse leaves a direction arrow null
26522 * @returns {Observable<string>}
26525 return this._hoveredKey$;
26533 * @fires PlayerComponent#playingchanged
26535 SequenceComponent.prototype.play = function () {
26536 this.configure({ playing: true });
26541 * @fires PlayerComponent#playingchanged
26543 SequenceComponent.prototype.stop = function () {
26544 this.configure({ playing: false });
26547 * Set the direction to follow when playing.
26549 * @param {EdgeDirection} direction - The direction that will be followed when playing.
26551 SequenceComponent.prototype.setDirection = function (direction) {
26552 this.configure({ direction: direction });
26555 * Set highlight key.
26557 * @description The arrow pointing towards the node corresponding to the
26558 * highlight key will be highlighted.
26560 * @param {string} highlightKey Key of node to be highlighted if existing.
26562 SequenceComponent.prototype.setHighlightKey = function (highlightKey) {
26563 this.configure({ highlightKey: highlightKey });
26566 * Set max width of container element.
26568 * @description Set max width of the container element holding
26569 * the sequence navigation elements. If the min width is larger than the
26570 * max width the min width value will be used.
26572 * The container element is automatically resized when the resize
26573 * method on the Viewer class is called.
26575 * @param {number} minWidth
26577 SequenceComponent.prototype.setMaxWidth = function (maxWidth) {
26578 this.configure({ maxWidth: maxWidth });
26581 * Set min width of container element.
26583 * @description Set min width of the container element holding
26584 * the sequence navigation elements. If the min width is larger than the
26585 * max width the min width value will be used.
26587 * The container element is automatically resized when the resize
26588 * method on the Viewer class is called.
26590 * @param {number} minWidth
26592 SequenceComponent.prototype.setMinWidth = function (minWidth) {
26593 this.configure({ minWidth: minWidth });
26596 * Set the value indicating whether the sequence UI elements should be visible.
26598 * @param {boolean} visible
26600 SequenceComponent.prototype.setVisible = function (visible) {
26601 this.configure({ visible: visible });
26604 SequenceComponent.prototype.resize = function () {
26606 this._configuration$
26608 .map(function (configuration) {
26609 return _this._sequenceDOMRenderer.getContainerWidth(_this._container.element, configuration);
26611 .subscribe(function (containerWidth) {
26612 _this._containerWidth$.next(containerWidth);
26615 SequenceComponent.prototype._activate = function () {
26617 this._renderSubscription = Observable_1.Observable
26618 .combineLatest(this._edgeStatus$, this._configuration$, this._containerWidth$)
26619 .map(function (ec) {
26620 var edgeStatus = ec[0];
26621 var configuration = ec[1];
26622 var containerWidth = ec[2];
26623 var vNode = _this._sequenceDOMRenderer
26624 .render(edgeStatus, configuration, containerWidth, _this, _this._sequenceDOMInteraction, _this._navigator);
26625 return { name: _this._name, vnode: vNode };
26627 .subscribe(this._container.domRenderer.render$);
26628 this._containerWidthSubscription = this._configuration$
26629 .distinctUntilChanged(function (value1, value2) {
26630 return value1[0] === value2[0] && value1[1] === value2[1];
26631 }, function (configuration) {
26632 return [configuration.minWidth, configuration.maxWidth];
26634 .map(function (configuration) {
26635 return _this._sequenceDOMRenderer.getContainerWidth(_this._container.element, configuration);
26637 .subscribe(this._containerWidth$);
26638 this._configurationSubscription = this._configurationOperation$
26639 .scan(function (configuration, operation) {
26640 return operation(configuration);
26641 }, { playing: false })
26642 .finally(function () {
26643 if (_this._playingSubscription != null) {
26644 _this._navigator.stateService.cutNodes();
26648 .subscribe(function () { });
26649 this._configuration$
26650 .map(function (newConfiguration) {
26651 return function (configuration) {
26652 if (newConfiguration.playing !== configuration.playing) {
26653 _this._navigator.stateService.cutNodes();
26654 if (newConfiguration.playing) {
26661 configuration.playing = newConfiguration.playing;
26662 return configuration;
26665 .subscribe(this._configurationOperation$);
26666 this._stopSubscription = this._configuration$
26667 .switchMap(function (configuration) {
26668 var edgeStatus$ = configuration.playing ?
26669 _this._edgeStatus$ :
26670 Observable_1.Observable.empty();
26671 var edgeDirection$ = Observable_1.Observable
26672 .of(configuration.direction);
26673 return Observable_1.Observable
26674 .combineLatest(edgeStatus$, edgeDirection$);
26676 .map(function (ne) {
26677 var edgeStatus = ne[0];
26678 var direction = ne[1];
26679 if (!edgeStatus.cached) {
26682 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
26684 if (edge.data.direction === direction) {
26690 .filter(function (hasEdge) {
26693 .map(function (hasEdge) {
26694 return { playing: false };
26696 .subscribe(this._configurationSubject$);
26697 this._hoveredKeySubscription = this._sequenceDOMInteraction.mouseEnterDirection$
26698 .switchMap(function (direction) {
26699 return _this._edgeStatus$
26700 .map(function (edgeStatus) {
26701 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
26703 if (edge.data.direction === direction) {
26709 .takeUntil(_this._sequenceDOMInteraction.mouseLeaveDirection$)
26710 .concat(Observable_1.Observable.of(null));
26712 .distinctUntilChanged()
26713 .subscribe(this._hoveredKeySubject$);
26715 SequenceComponent.prototype._deactivate = function () {
26716 this._stopSubscription.unsubscribe();
26717 this._renderSubscription.unsubscribe();
26718 this._configurationSubscription.unsubscribe();
26719 this._containerWidthSubscription.unsubscribe();
26720 this._hoveredKeySubscription.unsubscribe();
26723 SequenceComponent.prototype._getDefaultConfiguration = function () {
26725 direction: Edge_1.EdgeDirection.Next,
26732 SequenceComponent.prototype._play = function () {
26734 this._playingSubscription = this._navigator.stateService.currentState$
26735 .filter(function (frame) {
26736 return frame.state.nodesAhead < _this._nodesAhead;
26738 .map(function (frame) {
26739 return frame.state.lastNode;
26741 .distinctUntilChanged(undefined, function (lastNode) {
26742 return lastNode.key;
26744 .withLatestFrom(this._configuration$, function (lastNode, configuration) {
26745 return [lastNode, configuration.direction];
26747 .switchMap(function (nd) {
26748 return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(nd[1]) > -1 ?
26749 nd[0].sequenceEdges$ :
26750 nd[0].spatialEdges$)
26751 .filter(function (status) {
26752 return status.cached;
26754 .zip(Observable_1.Observable.of(nd[1]), function (status, direction) {
26755 return [status, direction];
26758 .map(function (ed) {
26759 var direction = ed[1];
26760 for (var _i = 0, _a = ed[0].edges; _i < _a.length; _i++) {
26762 if (edge.data.direction === direction) {
26768 .filter(function (key) {
26769 return key != null;
26771 .switchMap(function (key) {
26772 return _this._navigator.graphService.cacheNode$(key);
26774 .subscribe(function (node) {
26775 _this._navigator.stateService.appendNodes([node]);
26776 }, function (error) {
26777 console.error(error);
26780 this._clearSubscription = this._navigator.stateService.currentNode$
26782 .subscribe(function (nodes) {
26783 _this._navigator.stateService.clearPriorNodes();
26785 this.fire(SequenceComponent.playingchanged, true);
26787 SequenceComponent.prototype._stop = function () {
26788 this._playingSubscription.unsubscribe();
26789 this._playingSubscription = null;
26790 this._clearSubscription.unsubscribe();
26791 this._clearSubscription = null;
26792 this.fire(SequenceComponent.playingchanged, false);
26795 SequenceComponent.componentName = "sequence";
26797 * Event fired when playing starts or stops.
26799 * @event PlayerComponent#playingchanged
26800 * @type {boolean} Indicates whether the player is playing.
26802 SequenceComponent.playingchanged = "playingchanged";
26803 return SequenceComponent;
26804 }(Component_1.Component));
26805 exports.SequenceComponent = SequenceComponent;
26806 Component_1.ComponentService.register(SequenceComponent);
26807 exports.default = SequenceComponent;
26809 },{"../../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}],280:[function(require,module,exports){
26811 Object.defineProperty(exports, "__esModule", { value: true });
26812 var Subject_1 = require("rxjs/Subject");
26813 var SequenceDOMInteraction = (function () {
26814 function SequenceDOMInteraction() {
26815 this._mouseEnterDirection$ = new Subject_1.Subject();
26816 this._mouseLeaveDirection$ = new Subject_1.Subject();
26818 Object.defineProperty(SequenceDOMInteraction.prototype, "mouseEnterDirection$", {
26820 return this._mouseEnterDirection$;
26825 Object.defineProperty(SequenceDOMInteraction.prototype, "mouseLeaveDirection$", {
26827 return this._mouseLeaveDirection$;
26832 return SequenceDOMInteraction;
26834 exports.SequenceDOMInteraction = SequenceDOMInteraction;
26835 exports.default = SequenceDOMInteraction;
26837 },{"rxjs/Subject":34}],281:[function(require,module,exports){
26839 /// <reference path="../../../typings/index.d.ts" />
26840 Object.defineProperty(exports, "__esModule", { value: true });
26841 var vd = require("virtual-dom");
26842 var Edge_1 = require("../../Edge");
26843 var SequenceDOMRenderer = (function () {
26844 function SequenceDOMRenderer(element) {
26845 this._minThresholdWidth = 320;
26846 this._maxThresholdWidth = 1480;
26847 this._minThresholdHeight = 240;
26848 this._maxThresholdHeight = 820;
26850 SequenceDOMRenderer.prototype.render = function (edgeStatus, configuration, containerWidth, component, interaction, navigator) {
26851 if (configuration.visible === false) {
26852 return vd.h("div.SequenceContainer", {}, []);
26854 var nextKey = null;
26855 var prevKey = null;
26856 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
26858 if (edge.data.direction === Edge_1.EdgeDirection.Next) {
26861 if (edge.data.direction === Edge_1.EdgeDirection.Prev) {
26865 var playingButton = this._createPlayingButton(nextKey, prevKey, configuration, component);
26866 var arrows = this._createSequenceArrows(nextKey, prevKey, configuration, interaction, navigator);
26867 var containerProperties = {
26868 oncontextmenu: function (event) { event.preventDefault(); },
26869 style: { height: (0.27 * containerWidth) + "px", width: containerWidth + "px" },
26871 return vd.h("div.SequenceContainer", containerProperties, arrows.concat([playingButton]));
26873 SequenceDOMRenderer.prototype.getContainerWidth = function (element, configuration) {
26874 var elementWidth = element.offsetWidth;
26875 var elementHeight = element.offsetHeight;
26876 var minWidth = configuration.minWidth;
26877 var maxWidth = configuration.maxWidth;
26878 if (maxWidth < minWidth) {
26879 maxWidth = minWidth;
26881 var relativeWidth = (elementWidth - this._minThresholdWidth) / (this._maxThresholdWidth - this._minThresholdWidth);
26882 var relativeHeight = (elementHeight - this._minThresholdHeight) / (this._maxThresholdHeight - this._minThresholdHeight);
26883 var coeff = Math.max(0, Math.min(1, Math.min(relativeWidth, relativeHeight)));
26884 return minWidth + coeff * (maxWidth - minWidth);
26886 SequenceDOMRenderer.prototype._createPlayingButton = function (nextKey, prevKey, configuration, component) {
26887 var canPlay = configuration.direction === Edge_1.EdgeDirection.Next && nextKey != null ||
26888 configuration.direction === Edge_1.EdgeDirection.Prev && prevKey != null;
26889 var onclick = configuration.playing ?
26890 function (e) { component.stop(); } :
26891 canPlay ? function (e) { component.play(); } : null;
26892 var buttonProperties = {
26896 var iconClass = configuration.playing ?
26898 canPlay ? "Play" : "PlayDisabled";
26899 var icon = vd.h("div.SequenceComponentIcon", { className: iconClass }, []);
26900 var buttonClass = canPlay ? "SequencePlay" : "SequencePlayDisabled";
26901 return vd.h("div." + buttonClass, buttonProperties, [icon]);
26903 SequenceDOMRenderer.prototype._createSequenceArrows = function (nextKey, prevKey, configuration, interaction, navigator) {
26904 var nextProperties = {
26905 onclick: nextKey != null ?
26907 navigator.moveDir$(Edge_1.EdgeDirection.Next)
26908 .subscribe(function (node) { return; }, function (error) { console.error(error); });
26911 onmouseenter: function (e) { interaction.mouseEnterDirection$.next(Edge_1.EdgeDirection.Next); },
26912 onmouseleave: function (e) { interaction.mouseLeaveDirection$.next(Edge_1.EdgeDirection.Next); },
26915 var prevProperties = {
26916 onclick: prevKey != null ?
26918 navigator.moveDir$(Edge_1.EdgeDirection.Prev)
26919 .subscribe(function (node) { return; }, function (error) { console.error(error); });
26922 onmouseenter: function (e) { interaction.mouseEnterDirection$.next(Edge_1.EdgeDirection.Prev); },
26923 onmouseleave: function (e) { interaction.mouseLeaveDirection$.next(Edge_1.EdgeDirection.Prev); },
26926 var nextClass = this._getStepClassName(Edge_1.EdgeDirection.Next, nextKey, configuration.highlightKey);
26927 var prevClass = this._getStepClassName(Edge_1.EdgeDirection.Prev, prevKey, configuration.highlightKey);
26928 var nextIcon = vd.h("div.SequenceComponentIcon", []);
26929 var prevIcon = vd.h("div.SequenceComponentIcon", []);
26931 vd.h("div." + nextClass, nextProperties, [nextIcon]),
26932 vd.h("div." + prevClass, prevProperties, [prevIcon]),
26935 SequenceDOMRenderer.prototype._getStepClassName = function (direction, key, highlightKey) {
26936 var className = direction === Edge_1.EdgeDirection.Next ?
26937 "SequenceStepNext" :
26938 "SequenceStepPrev";
26940 className += "Disabled";
26943 if (highlightKey === key) {
26944 className += "Highlight";
26949 return SequenceDOMRenderer;
26951 exports.SequenceDOMRenderer = SequenceDOMRenderer;
26952 exports.default = SequenceDOMRenderer;
26954 },{"../../Edge":227,"virtual-dom":182}],282:[function(require,module,exports){
26956 Object.defineProperty(exports, "__esModule", { value: true });
26957 var GeometryTagError_1 = require("./error/GeometryTagError");
26958 exports.GeometryTagError = GeometryTagError_1.GeometryTagError;
26959 var PointGeometry_1 = require("./geometry/PointGeometry");
26960 exports.PointGeometry = PointGeometry_1.PointGeometry;
26961 var RectGeometry_1 = require("./geometry/RectGeometry");
26962 exports.RectGeometry = RectGeometry_1.RectGeometry;
26963 var PolygonGeometry_1 = require("./geometry/PolygonGeometry");
26964 exports.PolygonGeometry = PolygonGeometry_1.PolygonGeometry;
26965 var OutlineTag_1 = require("./tag/OutlineTag");
26966 exports.OutlineTag = OutlineTag_1.OutlineTag;
26967 var SpotTag_1 = require("./tag/SpotTag");
26968 exports.SpotTag = SpotTag_1.SpotTag;
26969 var TagComponent_1 = require("./TagComponent");
26970 exports.TagComponent = TagComponent_1.TagComponent;
26971 var TagMode_1 = require("./TagMode");
26972 exports.TagMode = TagMode_1.TagMode;
26974 },{"./TagComponent":283,"./TagMode":286,"./error/GeometryTagError":290,"./geometry/PointGeometry":292,"./geometry/PolygonGeometry":293,"./geometry/RectGeometry":294,"./tag/OutlineTag":298,"./tag/SpotTag":301}],283:[function(require,module,exports){
26976 /// <reference path="../../../typings/index.d.ts" />
26977 var __extends = (this && this.__extends) || (function () {
26978 var extendStatics = Object.setPrototypeOf ||
26979 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26980 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
26981 return function (d, b) {
26982 extendStatics(d, b);
26983 function __() { this.constructor = d; }
26984 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26987 Object.defineProperty(exports, "__esModule", { value: true });
26988 var when = require("when");
26989 var Observable_1 = require("rxjs/Observable");
26990 var Subject_1 = require("rxjs/Subject");
26991 require("rxjs/add/observable/combineLatest");
26992 require("rxjs/add/observable/empty");
26993 require("rxjs/add/observable/from");
26994 require("rxjs/add/observable/merge");
26995 require("rxjs/add/observable/of");
26996 require("rxjs/add/operator/combineLatest");
26997 require("rxjs/add/operator/concat");
26998 require("rxjs/add/operator/distinctUntilChanged");
26999 require("rxjs/add/operator/do");
27000 require("rxjs/add/operator/filter");
27001 require("rxjs/add/operator/map");
27002 require("rxjs/add/operator/merge");
27003 require("rxjs/add/operator/mergeMap");
27004 require("rxjs/add/operator/publishReplay");
27005 require("rxjs/add/operator/scan");
27006 require("rxjs/add/operator/share");
27007 require("rxjs/add/operator/skip");
27008 require("rxjs/add/operator/skipUntil");
27009 require("rxjs/add/operator/startWith");
27010 require("rxjs/add/operator/switchMap");
27011 require("rxjs/add/operator/take");
27012 require("rxjs/add/operator/takeUntil");
27013 require("rxjs/add/operator/withLatestFrom");
27014 var Component_1 = require("../../Component");
27015 var Geo_1 = require("../../Geo");
27016 var Render_1 = require("../../Render");
27018 * @class TagComponent
27020 * @classdesc Component for showing and editing tags with different
27021 * geometries composed from 2D basic image coordinates (see the
27022 * {@link Viewer} class documentation for more information about coordinate
27025 * The `add` method is used for adding new tags or replacing
27026 * tags already in the set. Tags are removed by id.
27028 * If a tag already in the set has the same
27029 * id as one of the tags added, the old tag will be removed and
27030 * the added tag will take its place.
27032 * The tag component mode can be set to either be non interactive or
27033 * to be in creating mode of a certain geometry type.
27035 * The tag properties can be updated at any time and the change will
27036 * be visibile immediately.
27038 * Tags are only relevant to a single image because they are based on
27039 * 2D basic image coordinates. Tags related to a certain image should
27040 * be removed when the viewer is moved to another node.
27042 * To retrive and use the tag component
27046 * var viewer = new Mapillary.Viewer(
27050 * { component: { tag: true } });
27052 * var tagComponent = viewer.getComponent("tag");
27055 var TagComponent = (function (_super) {
27056 __extends(TagComponent, _super);
27057 function TagComponent(name, container, navigator) {
27058 var _this = _super.call(this, name, container, navigator) || this;
27059 _this._tagDomRenderer = new Component_1.TagDOMRenderer();
27060 _this._tagScene = new Component_1.TagScene();
27061 _this._tagSet = new Component_1.TagSet();
27062 _this._tagCreator = new Component_1.TagCreator(_this, navigator);
27063 _this._viewportCoords = new Geo_1.ViewportCoords();
27064 _this._renderTags$ = _this._tagSet.changed$
27065 .map(function (tagSet) {
27066 var tags = tagSet.getAll();
27067 // ensure that tags are always rendered in the same order
27068 // to avoid hover tracking problems on first resize.
27069 tags.sort(function (t1, t2) {
27070 var id1 = t1.tag.id;
27071 var id2 = t2.tag.id;
27083 _this._tagChanged$ = _this._renderTags$
27084 .switchMap(function (tags) {
27085 return Observable_1.Observable
27087 .mergeMap(function (tag) {
27088 return Observable_1.Observable
27089 .merge(tag.tag.changed$, tag.tag.geometryChanged$);
27093 _this._renderTagGLChanged$ = _this._renderTags$
27094 .switchMap(function (tags) {
27095 return Observable_1.Observable
27097 .mergeMap(function (tag) {
27098 return tag.glObjectsChanged$;
27102 _this._tagInterationInitiated$ = _this._renderTags$
27103 .switchMap(function (tags) {
27104 return Observable_1.Observable
27106 .mergeMap(function (tag) {
27107 return tag.interact$
27108 .map(function (interaction) {
27109 return interaction.tag.id;
27114 _this._tagInteractionAbort$ = Observable_1.Observable
27115 .merge(_this._container.mouseService.documentMouseUp$)
27116 .map(function (e) { })
27118 _this._activeTag$ = _this._renderTags$
27119 .switchMap(function (tags) {
27120 return Observable_1.Observable
27122 .mergeMap(function (tag) {
27123 return tag.interact$;
27126 .merge(_this._tagInteractionAbort$
27128 return { offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: null };
27131 _this._createGeometryChanged$ = _this._tagCreator.tag$
27132 .switchMap(function (tag) {
27133 return tag != null ?
27134 tag.geometryChanged$ :
27135 Observable_1.Observable.empty();
27138 _this._createGLObjectsChanged$ = _this._tagCreator.tag$
27139 .switchMap(function (tag) {
27140 return tag != null ?
27141 tag.glObjectsChanged$ :
27142 Observable_1.Observable.empty();
27145 _this._tagCreated$ = _this._tagCreator.tag$
27146 .switchMap(function (tag) {
27147 return tag != null ?
27149 Observable_1.Observable.empty();
27152 _this._vertexGeometryCreated$ = _this._tagCreated$
27153 .map(function (tag) {
27154 return tag.geometry;
27157 _this._pointGeometryCreated$ = new Subject_1.Subject();
27158 _this._geometryCreated$ = Observable_1.Observable
27159 .merge(_this._vertexGeometryCreated$, _this._pointGeometryCreated$)
27161 _this._basicClick$ = _this._container.mouseService.staticClick$
27162 .withLatestFrom(_this._container.renderService.renderCamera$, _this._navigator.stateService.currentTransform$, function (event, renderCamera, transform) {
27163 return [event, renderCamera, transform];
27165 .map(function (ert) {
27166 var event = ert[0];
27167 var camera = ert[1];
27168 var transform = ert[2];
27169 var basic = _this._mouseEventToBasic(event, _this._container.element, camera, transform);
27173 _this._validBasicClick$ = _this._basicClick$
27174 .filter(function (basic) {
27177 return 0 <= x && x <= 1 && 0 <= y && y <= 1;
27180 _this._creatingConfiguration$ = _this._configuration$
27181 .distinctUntilChanged(function (c1, c2) {
27182 return c1.mode === c2.mode;
27183 }, function (configuration) {
27185 createColor: configuration.createColor,
27186 mode: configuration.mode,
27191 _this._creating$ = _this._creatingConfiguration$
27192 .map(function (configuration) {
27193 return configuration.mode !== Component_1.TagMode.Default;
27197 _this._creatingConfiguration$
27198 .subscribe(function (configuration) {
27199 _this.fire(TagComponent.modechanged, configuration.mode);
27204 * Add tags to the tag set or replace tags in the tag set.
27206 * @description If a tag already in the set has the same
27207 * id as one of the tags added, the old tag will be removed
27208 * the added tag will take its place.
27210 * @param {Array<Tag>} tags - Tags to add.
27212 * @example ```tagComponent.add([tag1, tag2]);```
27214 TagComponent.prototype.add = function (tags) {
27216 if (this._activated) {
27217 this._navigator.stateService.currentTransform$
27219 .subscribe(function (transform) {
27220 _this._tagSet.add(tags, transform);
27221 var renderTags = tags
27222 .map(function (tag) {
27223 return _this._tagSet.get(tag.id);
27225 _this._tagScene.add(renderTags);
27229 this._tagSet.addDeactivated(tags);
27233 * Change the current tag mode.
27235 * @description Change the tag mode to one of the create modes for creating new geometries.
27237 * @param {TagMode} mode - New tag mode.
27239 * @fires TagComponent#modechanged
27241 * @example ```tagComponent.changeMode(Mapillary.TagComponent.TagMode.CreateRect);```
27243 TagComponent.prototype.changeMode = function (mode) {
27244 this.configure({ mode: mode });
27247 * Returns the tag in the tag set with the specified id, or
27248 * undefined if the id matches no tag.
27250 * @param {string} tagId - Id of the tag.
27252 * @example ```var tag = tagComponent.get("tagId");```
27254 TagComponent.prototype.get = function (tagId) {
27255 if (this._activated) {
27256 var renderTag = this._tagSet.get(tagId);
27257 return renderTag !== undefined ? renderTag.tag : undefined;
27260 return this._tagSet.getDeactivated(tagId);
27264 * Returns an array of all tags.
27266 * @example ```var tags = tagComponent.getAll();```
27268 TagComponent.prototype.getAll = function () {
27269 if (this.activated) {
27270 return this._tagSet
27272 .map(function (renderTag) {
27273 return renderTag.tag;
27277 return this._tagSet.getAllDeactivated();
27281 * Returns an array of tag ids for tags that contain the specified point.
27283 * @description The pixel point must lie inside the polygon or rectangle
27284 * of an added tag for the tag id to be returned. Tag ids for
27285 * tags that do not have a fill will also be returned if the point is inside
27286 * the geometry of the tag. Tags with point geometries can not be retrieved.
27288 * No tag ids will be returned for panoramas.
27290 * Notice that the pixelPoint argument requires x, y coordinates from pixel space.
27292 * With this function, you can use the coordinates provided by mouse
27293 * events to get information out of the tag component.
27295 * If no tag at exist the pixel point, an empty array will be returned.
27297 * @param {Array<number>} pixelPoint - Pixel coordinates on the viewer element.
27298 * @returns {Array<string>} Ids of the tags that contain the specified pixel point.
27302 * tagComponent.getTagIdsAt([100, 100])
27303 * .then((tagIds) => { console.log(tagIds); });
27306 TagComponent.prototype.getTagIdsAt = function (pixelPoint) {
27308 return when.promise(function (resolve, reject) {
27309 _this._container.renderService.renderCamera$
27311 .map(function (render) {
27312 var viewport = _this._viewportCoords
27313 .canvasToViewport(pixelPoint[0], pixelPoint[1], _this._container.element);
27314 var ids = _this._tagScene.intersectObjects(viewport, render.perspective);
27317 .subscribe(function (ids) {
27319 }, function (error) {
27325 * Check if a tag exist in the tag set.
27327 * @param {string} tagId - Id of the tag.
27329 * @example ```var tagExists = tagComponent.has("tagId");```
27331 TagComponent.prototype.has = function (tagId) {
27332 return this._activated ? this._tagSet.has(tagId) : this._tagSet.hasDeactivated(tagId);
27335 * Remove tags with the specified ids from the tag set.
27337 * @param {Array<string>} tagIds - Ids for tags to remove.
27339 * @example ```tagComponent.remove(["id-1", "id-2"]);```
27341 TagComponent.prototype.remove = function (tagIds) {
27342 if (this._activated) {
27343 this._tagSet.remove(tagIds);
27344 this._tagScene.remove(tagIds);
27347 this._tagSet.removeDeactivated(tagIds);
27351 * Remove all tags from the tag set.
27353 * @example ```tagComponent.removeAll();```
27355 TagComponent.prototype.removeAll = function () {
27356 if (this._activated) {
27357 this._tagSet.removeAll();
27358 this._tagScene.removeAll();
27361 this._tagSet.removeAllDeactivated();
27364 TagComponent.prototype._activate = function () {
27366 this._preventDefaultSubscription = this._activeTag$
27367 .switchMap(function (interaction) {
27368 return interaction.tag != null ?
27369 _this._container.mouseService.documentMouseMove$ :
27370 Observable_1.Observable.empty();
27372 .subscribe(function (event) {
27373 event.preventDefault(); // prevent selection of content outside the viewer
27375 this._geometryCreatedEventSubscription = this._geometryCreated$
27376 .subscribe(function (geometry) {
27377 _this.fire(TagComponent.geometrycreated, geometry);
27379 this._tagsChangedEventSubscription = this._renderTags$
27380 .subscribe(function (tags) {
27381 _this.fire(TagComponent.tagschanged, _this);
27383 var transformChanged$ = this.configuration$
27384 .switchMap(function (configuration) {
27385 return configuration.mode !== Component_1.TagMode.Default ?
27386 _this._navigator.stateService.currentTransform$
27387 .map(function (n) { return null; }) :
27388 Observable_1.Observable.empty();
27392 this._deleteCreatingSubscription = transformChanged$
27394 .subscribe(function () {
27395 _this._tagCreator.delete$.next(null);
27397 var tagAborted$ = this._tagCreator.tag$
27398 .switchMap(function (tag) {
27399 return tag != null ?
27401 .map(function (t) { return null; }) :
27402 Observable_1.Observable.empty();
27404 var tagCreated$ = this._tagCreated$
27405 .map(function (t) { return null; });
27406 var pointGeometryCreated$ = this._pointGeometryCreated$
27407 .map(function (p) { return null; });
27408 this._stopCreateSubscription = Observable_1.Observable
27409 .merge(tagAborted$, tagCreated$, pointGeometryCreated$)
27410 .subscribe(function () { _this.changeMode(Component_1.TagMode.Default); });
27411 var creatingStarted$ = Observable_1.Observable
27412 .combineLatest(this._creatingConfiguration$, transformChanged$)
27413 .map(function (_a) {
27414 var configuration = _a[0];
27415 return configuration;
27419 this._createSubscription = creatingStarted$
27420 .switchMap(function (configuration) {
27421 return configuration.mode === Component_1.TagMode.CreateRect ||
27422 configuration.mode === Component_1.TagMode.CreatePolygon ?
27423 _this._validBasicClick$.take(1) :
27424 Observable_1.Observable.empty();
27426 .subscribe(this._tagCreator.create$);
27427 this._createPointSubscription = creatingStarted$
27428 .switchMap(function (configuration) {
27429 return configuration.mode === Component_1.TagMode.CreatePoint ?
27430 _this._validBasicClick$.take(1) :
27431 Observable_1.Observable.empty();
27433 .map(function (basic) {
27434 return new Component_1.PointGeometry(basic);
27436 .subscribe(this._pointGeometryCreated$);
27437 var containerMouseMove$ = Observable_1.Observable
27438 .merge(this._container.mouseService.mouseMove$, this._container.mouseService.domMouseMove$)
27440 this._setCreateVertexSubscription = Observable_1.Observable
27441 .combineLatest(containerMouseMove$, this._tagCreator.tag$, this._container.renderService.renderCamera$)
27442 .filter(function (etr) {
27443 return etr[1] != null;
27445 .withLatestFrom(this._navigator.stateService.currentTransform$, function (etr, transform) {
27446 return [etr[0], etr[1], etr[2], transform];
27448 .subscribe(function (etrt) {
27449 var event = etrt[0];
27451 var camera = etrt[2];
27452 var transform = etrt[3];
27453 var basic = _this._mouseEventToBasic(event, _this._container.element, camera, transform);
27454 if (tag.geometry instanceof Component_1.RectGeometry) {
27455 tag.geometry.setVertex2d(3, basic, transform);
27457 else if (tag.geometry instanceof Component_1.PolygonGeometry) {
27458 tag.geometry.setVertex2d(tag.geometry.polygon.length - 2, basic, transform);
27461 this._addPointSubscription = creatingStarted$
27462 .switchMap(function (configuration) {
27463 return configuration.mode === Component_1.TagMode.CreateRect || configuration.mode === Component_1.TagMode.CreatePolygon ?
27464 _this._basicClick$.skipUntil(_this._validBasicClick$).skip(1) :
27465 Observable_1.Observable.empty();
27467 .withLatestFrom(this._tagCreator.tag$, function (basic, tag) {
27468 return [basic, tag];
27470 .subscribe(function (bt) {
27473 tag.addPoint(basic);
27475 this._containerClassListSubscription = this._creating$
27476 .subscribe(function (creating) {
27478 _this._container.element.classList.add("component-tag-create");
27481 _this._container.element.classList.remove("component-tag-create");
27484 this._deleteCreatedSubscription = this._creating$
27485 .subscribe(function (creating) {
27486 _this._tagCreator.delete$.next(null);
27488 this._setGLCreateTagSubscription = this._tagCreator.tag$
27489 .subscribe(function (tag) {
27490 if (_this._tagScene.hasCreateTag()) {
27491 _this._tagScene.removeCreateTag();
27494 _this._tagScene.addCreateTag(tag);
27497 this._createGLObjectsChangedSubscription = this._createGLObjectsChanged$
27498 .subscribe(function (tag) {
27499 _this._tagScene.updateCreateTagObjects(tag);
27501 this._claimMouseSubscription = this._tagInterationInitiated$
27502 .switchMap(function (id) {
27503 return containerMouseMove$
27504 .takeUntil(_this._tagInteractionAbort$)
27507 .subscribe(function (e) {
27508 _this._container.mouseService.claimMouse(_this._name, 1);
27510 this._mouseDragSubscription = this._activeTag$
27511 .withLatestFrom(containerMouseMove$, function (a, e) {
27514 .switchMap(function (args) {
27515 var activeTag = args[0];
27516 var mouseMove = args[1];
27517 if (activeTag.operation === Component_1.TagOperation.None) {
27518 return Observable_1.Observable.empty();
27520 var mouseDrag$ = Observable_1.Observable
27522 .concat(_this._container.mouseService
27523 .filtered$(_this._name, _this._container.mouseService.domMouseDrag$)
27524 .filter(function (event) {
27525 return _this._viewportCoords.insideElement(event, _this._container.element);
27527 return Observable_1.Observable
27528 .combineLatest(mouseDrag$, _this._container.renderService.renderCamera$)
27529 .withLatestFrom(Observable_1.Observable.of(activeTag), _this._navigator.stateService.currentTransform$, function (ec, a, t) {
27530 return [ec[0], ec[1], a, t];
27533 .subscribe(function (args) {
27534 var mouseEvent = args[0];
27535 var renderCamera = args[1];
27536 var activeTag = args[2];
27537 var transform = args[3];
27538 if (activeTag.operation === Component_1.TagOperation.None) {
27541 var basic = _this._mouseEventToBasic(mouseEvent, _this._container.element, renderCamera, transform, activeTag.offsetX, activeTag.offsetY);
27542 if (activeTag.operation === Component_1.TagOperation.Centroid) {
27543 activeTag.tag.geometry.setCentroid2d(basic, transform);
27545 else if (activeTag.operation === Component_1.TagOperation.Vertex) {
27546 var vertexGeometry = activeTag.tag.geometry;
27547 vertexGeometry.setVertex2d(activeTag.vertexIndex, basic, transform);
27550 this._unclaimMouseSubscription = this._container.mouseService
27551 .filtered$(this._name, this._container.mouseService.domMouseDragEnd$)
27552 .subscribe(function (e) {
27553 _this._container.mouseService.unclaimMouse(_this._name);
27555 this._updateGLObjectsSubscription = this._renderTagGLChanged$
27556 .subscribe(function (tag) {
27557 _this._tagScene.updateObjects(tag);
27559 this._updateTagSceneSubscription = this._tagChanged$
27560 .subscribe(function (tag) {
27561 _this._tagScene.update();
27563 this._domSubscription = this._renderTags$
27565 .do(function (tags) {
27566 _this._container.domRenderer.render$.next({
27568 vnode: _this._tagDomRenderer.clear(),
27571 .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) {
27572 return [rc, atlas, size, renderTags, tag, ct];
27574 .map(function (args) {
27577 vnode: _this._tagDomRenderer.render(args[3], args[5], args[1], args[0].perspective, args[2]),
27580 .subscribe(this._container.domRenderer.render$);
27581 this._glSubscription = this._navigator.stateService.currentState$
27582 .map(function (frame) {
27583 var tagScene = _this._tagScene;
27588 needsRender: tagScene.needsRender,
27589 render: tagScene.render.bind(tagScene),
27590 stage: Render_1.GLRenderStage.Foreground,
27594 .subscribe(this._container.glRenderer.render$);
27595 this._navigator.stateService.currentTransform$
27597 .subscribe(function (transform) {
27598 _this._tagSet.activate(transform);
27599 _this._tagScene.add(_this._tagSet.getAll());
27602 TagComponent.prototype._deactivate = function () {
27603 this._tagScene.clear();
27604 this._tagSet.deactivate();
27605 this._tagCreator.delete$.next(null);
27606 this._claimMouseSubscription.unsubscribe();
27607 this._mouseDragSubscription.unsubscribe();
27608 this._unclaimMouseSubscription.unsubscribe();
27609 this._updateGLObjectsSubscription.unsubscribe();
27610 this._updateTagSceneSubscription.unsubscribe();
27611 this._stopCreateSubscription.unsubscribe();
27612 this._deleteCreatingSubscription.unsubscribe();
27613 this._createSubscription.unsubscribe();
27614 this._createPointSubscription.unsubscribe();
27615 this._setCreateVertexSubscription.unsubscribe();
27616 this._addPointSubscription.unsubscribe();
27617 this._deleteCreatedSubscription.unsubscribe();
27618 this._setGLCreateTagSubscription.unsubscribe();
27619 this._createGLObjectsChangedSubscription.unsubscribe();
27620 this._preventDefaultSubscription.unsubscribe();
27621 this._containerClassListSubscription.unsubscribe();
27622 this._domSubscription.unsubscribe();
27623 this._glSubscription.unsubscribe();
27624 this._geometryCreatedEventSubscription.unsubscribe();
27625 this._tagsChangedEventSubscription.unsubscribe();
27626 this._container.element.classList.remove("component-tag-create");
27628 TagComponent.prototype._getDefaultConfiguration = function () {
27630 createColor: 0xFFFFFF,
27631 mode: Component_1.TagMode.Default,
27634 TagComponent.prototype._mouseEventToBasic = function (event, element, camera, transform, offsetX, offsetY) {
27635 offsetX = offsetX != null ? offsetX : 0;
27636 offsetY = offsetY != null ? offsetY : 0;
27637 var _a = this._viewportCoords.canvasPosition(event, element), canvasX = _a[0], canvasY = _a[1];
27638 var basic = this._viewportCoords.canvasToBasic(canvasX - offsetX, canvasY - offsetY, element, transform, camera.perspective);
27642 TagComponent.componentName = "tag";
27644 * Event fired when the create mode is changed.
27646 * @event TagComponent#modechanged
27647 * @type {TagMode} Tag mode
27650 * tagComponent.on("modechanged", function(mode) {
27651 * console.log(mode);
27655 TagComponent.modechanged = "modechanged";
27657 * Event fired when a geometry has been created.
27659 * @event TagComponent#geometrycreated
27660 * @type {Geometry} Created geometry.
27663 * tagComponent.on("geometrycreated", function(geometry) {
27664 * console.log(geometry);
27668 TagComponent.geometrycreated = "geometrycreated";
27670 * Event fired when the tags collection has changed.
27672 * @event TagComponent#tagschanged
27673 * @type {TagComponent} Tag component.
27676 * tagComponent.on("tagschanged", function(component) {
27677 * console.log(component.getAll());
27681 TagComponent.tagschanged = "tagschanged";
27682 return TagComponent;
27683 }(Component_1.Component));
27684 exports.TagComponent = TagComponent;
27685 Component_1.ComponentService.register(TagComponent);
27686 exports.default = TagComponent;
27688 },{"../../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}],284:[function(require,module,exports){
27690 Object.defineProperty(exports, "__esModule", { value: true });
27691 var Subject_1 = require("rxjs/Subject");
27692 require("rxjs/add/operator/map");
27693 require("rxjs/add/operator/scan");
27694 require("rxjs/add/operator/share");
27695 require("rxjs/add/operator/withLatestFrom");
27696 var Component_1 = require("../../Component");
27697 var TagCreator = (function () {
27698 function TagCreator(component, navigator) {
27699 this._component = component;
27700 this._navigator = navigator;
27701 this._tagOperation$ = new Subject_1.Subject();
27702 this._create$ = new Subject_1.Subject();
27703 this._delete$ = new Subject_1.Subject();
27704 this._tag$ = this._tagOperation$
27705 .scan(function (tag, operation) {
27706 return operation(tag);
27710 .withLatestFrom(this._component.configuration$, this._navigator.stateService.currentTransform$)
27711 .map(function (_a) {
27712 var coord = _a[0], conf = _a[1], transform = _a[2];
27713 return function (tag) {
27714 if (conf.mode === Component_1.TagMode.CreateRect) {
27715 var geometry = new Component_1.RectGeometry([
27721 return new Component_1.OutlineCreateTag(geometry, { color: conf.createColor }, transform);
27723 else if (conf.mode === Component_1.TagMode.CreatePolygon) {
27724 var geometry = new Component_1.PolygonGeometry([
27725 [coord[0], coord[1]],
27726 [coord[0], coord[1]],
27727 [coord[0], coord[1]],
27729 return new Component_1.OutlineCreateTag(geometry, { color: conf.createColor }, transform);
27734 .subscribe(this._tagOperation$);
27737 return function (tag) {
27741 .subscribe(this._tagOperation$);
27743 Object.defineProperty(TagCreator.prototype, "create$", {
27745 return this._create$;
27750 Object.defineProperty(TagCreator.prototype, "delete$", {
27752 return this._delete$;
27757 Object.defineProperty(TagCreator.prototype, "tag$", {
27766 exports.TagCreator = TagCreator;
27767 exports.default = TagCreator;
27769 },{"../../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}],285:[function(require,module,exports){
27771 /// <reference path="../../../typings/index.d.ts" />
27772 Object.defineProperty(exports, "__esModule", { value: true });
27773 var vd = require("virtual-dom");
27774 var TagDOMRenderer = (function () {
27775 function TagDOMRenderer() {
27777 TagDOMRenderer.prototype.render = function (tags, createTag, atlas, camera, size) {
27779 for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
27780 var tag = tags_1[_i];
27781 vNodes = vNodes.concat(tag.getDOMObjects(atlas, camera, size));
27783 if (createTag != null) {
27784 vNodes = vNodes.concat(createTag.getDOMObjects(camera, size));
27786 return vd.h("div.TagContainer", {}, vNodes);
27788 TagDOMRenderer.prototype.clear = function () {
27789 return vd.h("div", {}, []);
27791 return TagDOMRenderer;
27793 exports.TagDOMRenderer = TagDOMRenderer;
27795 },{"virtual-dom":182}],286:[function(require,module,exports){
27797 Object.defineProperty(exports, "__esModule", { value: true });
27799 * Enumeration for tag modes
27802 * @description Modes for the interaction in the tag component.
27805 (function (TagMode) {
27807 * Disables creating tags.
27809 TagMode[TagMode["Default"] = 0] = "Default";
27811 * Create a point geometry through a click.
27813 TagMode[TagMode["CreatePoint"] = 1] = "CreatePoint";
27815 * Create a polygon geometry through clicks.
27817 TagMode[TagMode["CreatePolygon"] = 2] = "CreatePolygon";
27819 * Create a rect geometry through clicks.
27821 TagMode[TagMode["CreateRect"] = 3] = "CreateRect";
27822 })(TagMode = exports.TagMode || (exports.TagMode = {}));
27823 exports.default = TagMode;
27825 },{}],287:[function(require,module,exports){
27827 Object.defineProperty(exports, "__esModule", { value: true });
27829 (function (TagOperation) {
27830 TagOperation[TagOperation["None"] = 0] = "None";
27831 TagOperation[TagOperation["Centroid"] = 1] = "Centroid";
27832 TagOperation[TagOperation["Vertex"] = 2] = "Vertex";
27833 })(TagOperation = exports.TagOperation || (exports.TagOperation = {}));
27834 exports.default = TagOperation;
27836 },{}],288:[function(require,module,exports){
27838 /// <reference path="../../../typings/index.d.ts" />
27839 Object.defineProperty(exports, "__esModule", { value: true });
27840 var THREE = require("three");
27841 var TagScene = (function () {
27842 function TagScene(scene, raycaster) {
27843 this._createTag = null;
27844 this._needsRender = false;
27845 this._raycaster = !!raycaster ? raycaster : new THREE.Raycaster();
27846 this._scene = !!scene ? scene : new THREE.Scene();
27847 this._objectTags = {};
27848 this._retrievableObjects = [];
27851 Object.defineProperty(TagScene.prototype, "needsRender", {
27853 return this._needsRender;
27858 TagScene.prototype.add = function (tags) {
27859 for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
27860 var tag = tags_1[_i];
27861 if (tag.tag.id in this._tags) {
27862 this._remove(tag.tag.id);
27866 this._needsRender = true;
27868 TagScene.prototype.addCreateTag = function (tag) {
27869 for (var _i = 0, _a = tag.glObjects; _i < _a.length; _i++) {
27870 var object = _a[_i];
27871 this._scene.add(object);
27873 this._createTag = { tag: tag, objects: tag.glObjects };
27874 this._needsRender = true;
27876 TagScene.prototype.clear = function () {
27877 for (var _i = 0, _a = Object.keys(this._tags); _i < _a.length; _i++) {
27881 this._needsRender = false;
27883 TagScene.prototype.get = function (id) {
27884 return this.has(id) ? this._tags[id].tag : undefined;
27886 TagScene.prototype.has = function (id) {
27887 return id in this._tags;
27889 TagScene.prototype.hasCreateTag = function () {
27890 return this._createTag != null;
27892 TagScene.prototype.intersectObjects = function (_a, camera) {
27893 var viewportX = _a[0], viewportY = _a[1];
27894 this._raycaster.setFromCamera(new THREE.Vector2(viewportX, viewportY), camera);
27895 var intersects = this._raycaster.intersectObjects(this._retrievableObjects);
27896 var intersectedIds = [];
27897 for (var _i = 0, intersects_1 = intersects; _i < intersects_1.length; _i++) {
27898 var intersect = intersects_1[_i];
27899 if (intersect.object.uuid in this._objectTags) {
27900 intersectedIds.push(this._objectTags[intersect.object.uuid]);
27903 return intersectedIds;
27905 TagScene.prototype.remove = function (ids) {
27906 for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
27907 var id = ids_1[_i];
27910 this._needsRender = true;
27912 TagScene.prototype.removeAll = function () {
27913 for (var _i = 0, _a = Object.keys(this._tags); _i < _a.length; _i++) {
27917 this._needsRender = true;
27919 TagScene.prototype.removeCreateTag = function () {
27920 if (this._createTag == null) {
27923 for (var _i = 0, _a = this._createTag.objects; _i < _a.length; _i++) {
27924 var object = _a[_i];
27925 this._scene.remove(object);
27927 this._createTag.tag.dispose();
27928 this._createTag = null;
27929 this._needsRender = true;
27931 TagScene.prototype.render = function (perspectiveCamera, renderer) {
27932 renderer.render(this._scene, perspectiveCamera);
27933 this._needsRender = false;
27935 TagScene.prototype.update = function () {
27936 this._needsRender = true;
27938 TagScene.prototype.updateCreateTagObjects = function (tag) {
27939 if (this._createTag.tag !== tag) {
27940 throw new Error("Create tags do not have the same reference.");
27942 for (var _i = 0, _a = this._createTag.objects; _i < _a.length; _i++) {
27943 var object = _a[_i];
27944 this._scene.remove(object);
27946 for (var _b = 0, _c = tag.glObjects; _b < _c.length; _b++) {
27947 var object = _c[_b];
27948 this._scene.add(object);
27950 this._createTag.objects = tag.glObjects;
27951 this._needsRender = true;
27953 TagScene.prototype.updateObjects = function (tag) {
27954 var id = tag.tag.id;
27955 if (this._tags[id].tag !== tag) {
27956 throw new Error("Tags do not have the same reference.");
27958 var tagObjects = this._tags[id];
27959 this._removeObjects(tagObjects);
27960 delete this._tags[id];
27962 this._needsRender = true;
27964 TagScene.prototype._add = function (tag) {
27965 var id = tag.tag.id;
27966 var tagObjects = { tag: tag, objects: [], retrievableObjects: [] };
27967 this._tags[id] = tagObjects;
27968 for (var _i = 0, _a = tag.getGLObjects(); _i < _a.length; _i++) {
27969 var object = _a[_i];
27970 tagObjects.objects.push(object);
27971 this._scene.add(object);
27973 for (var _b = 0, _c = tag.getRetrievableObjects(); _b < _c.length; _b++) {
27974 var retrievableObject = _c[_b];
27975 tagObjects.retrievableObjects.push(retrievableObject);
27976 this._retrievableObjects.push(retrievableObject);
27977 this._objectTags[retrievableObject.uuid] = tag.tag.id;
27980 TagScene.prototype._remove = function (id) {
27981 var tagObjects = this._tags[id];
27982 this._removeObjects(tagObjects);
27983 tagObjects.tag.dispose();
27984 delete this._tags[id];
27986 TagScene.prototype._removeObjects = function (tagObjects) {
27987 for (var _i = 0, _a = tagObjects.objects; _i < _a.length; _i++) {
27988 var object = _a[_i];
27989 this._scene.remove(object);
27991 for (var _b = 0, _c = tagObjects.retrievableObjects; _b < _c.length; _b++) {
27992 var retrievableObject = _c[_b];
27993 var index = this._retrievableObjects.indexOf(retrievableObject);
27994 if (index !== -1) {
27995 this._retrievableObjects.splice(index, 1);
28001 exports.TagScene = TagScene;
28002 exports.default = TagScene;
28004 },{"three":176}],289:[function(require,module,exports){
28006 Object.defineProperty(exports, "__esModule", { value: true });
28007 var Subject_1 = require("rxjs/Subject");
28008 require("rxjs/add/operator/map");
28009 require("rxjs/add/operator/scan");
28010 require("rxjs/add/operator/share");
28011 var Component_1 = require("../../Component");
28012 var TagSet = (function () {
28013 function TagSet() {
28014 this._active = false;
28016 this._hashDeactivated = {};
28017 this._notifyChanged$ = new Subject_1.Subject();
28019 Object.defineProperty(TagSet.prototype, "active", {
28021 return this._active;
28026 Object.defineProperty(TagSet.prototype, "changed$", {
28028 return this._notifyChanged$;
28033 TagSet.prototype.activate = function (transform) {
28034 if (this._active) {
28037 for (var id in this._hashDeactivated) {
28038 if (!this._hashDeactivated.hasOwnProperty(id)) {
28041 var tag = this._hashDeactivated[id];
28042 this._add(tag, transform);
28044 this._hashDeactivated = {};
28045 this._active = true;
28046 this._notifyChanged$.next(this);
28048 TagSet.prototype.deactivate = function () {
28049 if (!this._active) {
28052 for (var id in this._hash) {
28053 if (!this._hash.hasOwnProperty(id)) {
28056 this._hashDeactivated[id] = this._hash[id].tag;
28059 this._active = false;
28061 TagSet.prototype.add = function (tags, transform) {
28062 this._assertActivationState(true);
28063 for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
28064 var tag = tags_1[_i];
28065 this._add(tag, transform);
28067 this._notifyChanged$.next(this);
28069 TagSet.prototype.addDeactivated = function (tags) {
28070 this._assertActivationState(false);
28071 for (var _i = 0, tags_2 = tags; _i < tags_2.length; _i++) {
28072 var tag = tags_2[_i];
28073 if (!(tag instanceof Component_1.OutlineTag || tag instanceof Component_1.SpotTag)) {
28074 throw new Error("Tag type not supported");
28076 this._hashDeactivated[tag.id] = tag;
28079 TagSet.prototype.get = function (id) {
28080 return this.has(id) ? this._hash[id] : undefined;
28082 TagSet.prototype.getAll = function () {
28083 var hash = this._hash;
28084 return Object.keys(hash)
28085 .map(function (id) {
28089 TagSet.prototype.getAllDeactivated = function () {
28090 var hashDeactivated = this._hashDeactivated;
28091 return Object.keys(hashDeactivated)
28092 .map(function (id) {
28093 return hashDeactivated[id];
28096 TagSet.prototype.getDeactivated = function (id) {
28097 return this.hasDeactivated(id) ? this._hashDeactivated[id] : undefined;
28099 TagSet.prototype.has = function (id) {
28100 return id in this._hash;
28102 TagSet.prototype.hasDeactivated = function (id) {
28103 return id in this._hashDeactivated;
28105 TagSet.prototype.remove = function (ids) {
28106 this._assertActivationState(true);
28107 var hash = this._hash;
28108 for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
28109 var id = ids_1[_i];
28110 if (!(id in hash)) {
28115 this._notifyChanged$.next(this);
28117 TagSet.prototype.removeAll = function () {
28118 this._assertActivationState(true);
28120 this._notifyChanged$.next(this);
28122 TagSet.prototype.removeAllDeactivated = function () {
28123 this._assertActivationState(false);
28124 this._hashDeactivated = {};
28126 TagSet.prototype.removeDeactivated = function (ids) {
28127 this._assertActivationState(false);
28128 var hashDeactivated = this._hashDeactivated;
28129 for (var _i = 0, ids_2 = ids; _i < ids_2.length; _i++) {
28130 var id = ids_2[_i];
28131 if (!(id in hashDeactivated)) {
28134 delete hashDeactivated[id];
28137 TagSet.prototype._add = function (tag, transform) {
28138 if (tag instanceof Component_1.OutlineTag) {
28139 this._hash[tag.id] = new Component_1.OutlineRenderTag(tag, transform);
28141 else if (tag instanceof Component_1.SpotTag) {
28142 this._hash[tag.id] = new Component_1.SpotRenderTag(tag, transform);
28145 throw new Error("Tag type not supported");
28148 TagSet.prototype._assertActivationState = function (should) {
28149 if (should !== this._active) {
28150 throw new Error("Tag set not in correct state for operation.");
28155 exports.TagSet = TagSet;
28156 exports.default = TagSet;
28158 },{"../../Component":226,"rxjs/Subject":34,"rxjs/add/operator/map":65,"rxjs/add/operator/scan":73,"rxjs/add/operator/share":74}],290:[function(require,module,exports){
28160 var __extends = (this && this.__extends) || (function () {
28161 var extendStatics = Object.setPrototypeOf ||
28162 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28163 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28164 return function (d, b) {
28165 extendStatics(d, b);
28166 function __() { this.constructor = d; }
28167 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28170 Object.defineProperty(exports, "__esModule", { value: true });
28171 var Error_1 = require("../../../Error");
28172 var GeometryTagError = (function (_super) {
28173 __extends(GeometryTagError, _super);
28174 function GeometryTagError(message) {
28175 var _this = _super.call(this, message != null ? message : "The provided geometry value is incorrect") || this;
28176 _this.name = "GeometryTagError";
28179 return GeometryTagError;
28180 }(Error_1.MapillaryError));
28181 exports.GeometryTagError = GeometryTagError;
28182 exports.default = Error_1.MapillaryError;
28184 },{"../../../Error":228}],291:[function(require,module,exports){
28186 Object.defineProperty(exports, "__esModule", { value: true });
28187 var Subject_1 = require("rxjs/Subject");
28191 * @classdesc Represents a geometry.
28193 var Geometry = (function () {
28195 * Create a geometry.
28199 function Geometry() {
28200 this._notifyChanged$ = new Subject_1.Subject();
28202 Object.defineProperty(Geometry.prototype, "changed$", {
28204 * Get changed observable.
28206 * @description Emits the geometry itself every time the geometry
28209 * @returns {Observable<Geometry>} Observable emitting the geometry instance.
28213 return this._notifyChanged$;
28220 exports.Geometry = Geometry;
28221 exports.default = Geometry;
28223 },{"rxjs/Subject":34}],292:[function(require,module,exports){
28225 var __extends = (this && this.__extends) || (function () {
28226 var extendStatics = Object.setPrototypeOf ||
28227 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28228 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28229 return function (d, b) {
28230 extendStatics(d, b);
28231 function __() { this.constructor = d; }
28232 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28235 Object.defineProperty(exports, "__esModule", { value: true });
28236 var Component_1 = require("../../../Component");
28238 * @class PointGeometry
28240 * @classdesc Represents a point geometry in the 2D basic image coordinate system.
28244 * var basicPoint = [0.5, 0.7];
28245 * var pointGeometry = new Mapillary.TagComponent.PointGeometry(basicPoint);
28248 var PointGeometry = (function (_super) {
28249 __extends(PointGeometry, _super);
28251 * Create a point geometry.
28254 * @param {Array<number>} point - An array representing the basic coordinates of
28257 * @throws {GeometryTagError} Point coordinates must be valid basic coordinates.
28259 function PointGeometry(point) {
28260 var _this = _super.call(this) || this;
28263 if (x < 0 || x > 1 || y < 0 || y > 1) {
28264 throw new Component_1.GeometryTagError("Basic coordinates must be on the interval [0, 1].");
28266 _this._point = point.slice();
28269 Object.defineProperty(PointGeometry.prototype, "point", {
28271 * Get point property.
28272 * @returns {Array<number>} Array representing the basic coordinates of the point.
28275 return this._point;
28281 * Get the 2D basic coordinates for the centroid of the point, i.e. the 2D
28282 * basic coordinates of the point itself.
28284 * @returns {Array<number>} 2D basic coordinates representing the centroid.
28286 PointGeometry.prototype.getCentroid2d = function () {
28287 return this._point.slice();
28290 * Get the 3D world coordinates for the centroid of the point, i.e. the 3D
28291 * world coordinates of the point itself.
28293 * @param {Transform} transform - The transform of the node related to the point.
28294 * @returns {Array<number>} 3D world coordinates representing the centroid.
28296 PointGeometry.prototype.getCentroid3d = function (transform) {
28297 return transform.unprojectBasic(this._point, 200);
28300 * Set the centroid of the point, i.e. the point coordinates.
28302 * @param {Array<number>} value - The new value of the centroid.
28303 * @param {Transform} transform - The transform of the node related to the point.
28305 PointGeometry.prototype.setCentroid2d = function (value, transform) {
28307 Math.max(0, Math.min(1, value[0])),
28308 Math.max(0, Math.min(1, value[1])),
28310 this._point[0] = changed[0];
28311 this._point[1] = changed[1];
28312 this._notifyChanged$.next(this);
28314 return PointGeometry;
28315 }(Component_1.Geometry));
28316 exports.PointGeometry = PointGeometry;
28318 },{"../../../Component":226}],293:[function(require,module,exports){
28320 var __extends = (this && this.__extends) || (function () {
28321 var extendStatics = Object.setPrototypeOf ||
28322 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28323 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28324 return function (d, b) {
28325 extendStatics(d, b);
28326 function __() { this.constructor = d; }
28327 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28330 Object.defineProperty(exports, "__esModule", { value: true });
28331 var Component_1 = require("../../../Component");
28333 * @class PolygonGeometry
28335 * @classdesc Represents a polygon geometry in the 2D basic image coordinate system.
28336 * All polygons and holes provided to the constructor needs to be closed.
28340 * var basicPolygon = [[0.5, 0.3], [0.7, 0.3], [0.6, 0.5], [0.5, 0.3]];
28341 * var polygonGeometry = new Mapillary.TagComponent.PointGeometry(basicPolygon);
28344 var PolygonGeometry = (function (_super) {
28345 __extends(PolygonGeometry, _super);
28347 * Create a polygon geometry.
28350 * @param {Array<Array<number>>} polygon - Array of polygon vertices. Must be closed.
28351 * @param {Array<Array<Array<number>>>} [holes] - Array of arrays of hole vertices.
28352 * Each array of holes vertices must be closed.
28354 * @throws {GeometryTagError} Polygon coordinates must be valid basic coordinates.
28356 function PolygonGeometry(polygon, holes) {
28357 var _this = _super.call(this) || this;
28358 var polygonLength = polygon.length;
28359 if (polygonLength < 3) {
28360 throw new Component_1.GeometryTagError("A polygon must have three or more positions.");
28362 if (polygon[0][0] !== polygon[polygonLength - 1][0] ||
28363 polygon[0][1] !== polygon[polygonLength - 1][1]) {
28364 throw new Component_1.GeometryTagError("First and last positions must be equivalent.");
28366 _this._polygon = [];
28367 for (var _i = 0, polygon_1 = polygon; _i < polygon_1.length; _i++) {
28368 var vertex = polygon_1[_i];
28369 if (vertex[0] < 0 || vertex[0] > 1 ||
28370 vertex[1] < 0 || vertex[1] > 1) {
28371 throw new Component_1.GeometryTagError("Basic coordinates of polygon must be on the interval [0, 1].");
28373 _this._polygon.push(vertex.slice());
28376 if (holes == null) {
28379 for (var i = 0; i < holes.length; i++) {
28380 var hole = holes[i];
28381 var holeLength = hole.length;
28382 if (holeLength < 3) {
28383 throw new Component_1.GeometryTagError("A polygon hole must have three or more positions.");
28385 if (hole[0][0] !== hole[holeLength - 1][0] ||
28386 hole[0][1] !== hole[holeLength - 1][1]) {
28387 throw new Component_1.GeometryTagError("First and last positions of hole must be equivalent.");
28389 _this._holes.push([]);
28390 for (var _a = 0, hole_1 = hole; _a < hole_1.length; _a++) {
28391 var vertex = hole_1[_a];
28392 if (vertex[0] < 0 || vertex[0] > 1 ||
28393 vertex[1] < 0 || vertex[1] > 1) {
28394 throw new Component_1.GeometryTagError("Basic coordinates of hole must be on the interval [0, 1].");
28396 _this._holes[i].push(vertex.slice());
28401 Object.defineProperty(PolygonGeometry.prototype, "polygon", {
28403 * Get polygon property.
28404 * @returns {Array<Array<number>>} Closed 2d polygon.
28407 return this._polygon;
28412 Object.defineProperty(PolygonGeometry.prototype, "holes", {
28414 * Get holes property.
28415 * @returns {Array<Array<Array<number>>>} Holes of 2d polygon.
28418 return this._holes;
28424 * Add a vertex to the polygon by appending it after the last vertex.
28426 * @param {Array<number>} vertex - Vertex to add.
28428 PolygonGeometry.prototype.addVertex2d = function (vertex) {
28430 Math.max(0, Math.min(1, vertex[0])),
28431 Math.max(0, Math.min(1, vertex[1])),
28433 this._polygon.splice(this._polygon.length - 1, 0, clamped);
28434 this._notifyChanged$.next(this);
28437 * Get the coordinates of a vertex from the polygon representation of the geometry.
28439 * @description The first vertex represents the bottom-left corner with the rest of
28440 * the vertices following in clockwise order.
28442 * @param {number} index - Vertex index.
28443 * @returns {Array<number>} Array representing the 2D basic coordinates of the vertex.
28445 PolygonGeometry.prototype.getVertex2d = function (index) {
28446 return this._polygon[index].slice();
28449 * Remove a vertex from the polygon.
28451 * @param {number} index - The index of the vertex to remove.
28453 PolygonGeometry.prototype.removeVertex2d = function (index) {
28455 index >= this._polygon.length ||
28456 this._polygon.length < 4) {
28457 throw new Component_1.GeometryTagError("Index for removed vertex must be valid.");
28459 if (index > 0 && index < this._polygon.length - 1) {
28460 this._polygon.splice(index, 1);
28463 this._polygon.splice(0, 1);
28464 this._polygon.pop();
28465 var closing = this._polygon[0].slice();
28466 this._polygon.push(closing);
28468 this._notifyChanged$.next(this);
28471 PolygonGeometry.prototype.setVertex2d = function (index, value, transform) {
28473 Math.max(0, Math.min(1, value[0])),
28474 Math.max(0, Math.min(1, value[1])),
28476 if (index === 0 || index === this._polygon.length - 1) {
28477 this._polygon[0] = changed.slice();
28478 this._polygon[this._polygon.length - 1] = changed.slice();
28481 this._polygon[index] = changed.slice();
28483 this._notifyChanged$.next(this);
28486 PolygonGeometry.prototype.setCentroid2d = function (value, transform) {
28487 var xs = this._polygon.map(function (point) { return point[0]; });
28488 var ys = this._polygon.map(function (point) { return point[1]; });
28489 var minX = Math.min.apply(Math, xs);
28490 var maxX = Math.max.apply(Math, xs);
28491 var minY = Math.min.apply(Math, ys);
28492 var maxY = Math.max.apply(Math, ys);
28493 var centroid = this.getCentroid2d();
28494 var minTranslationX = -minX;
28495 var maxTranslationX = 1 - maxX;
28496 var minTranslationY = -minY;
28497 var maxTranslationY = 1 - maxY;
28498 var translationX = Math.max(minTranslationX, Math.min(maxTranslationX, value[0] - centroid[0]));
28499 var translationY = Math.max(minTranslationY, Math.min(maxTranslationY, value[1] - centroid[1]));
28500 for (var _i = 0, _a = this._polygon; _i < _a.length; _i++) {
28501 var point = _a[_i];
28502 point[0] += translationX;
28503 point[1] += translationY;
28505 this._notifyChanged$.next(this);
28508 PolygonGeometry.prototype.getPoints3d = function (transform) {
28509 return this.getVertices3d(transform);
28512 PolygonGeometry.prototype.getVertex3d = function (index, transform) {
28513 return transform.unprojectBasic(this._polygon[index], 200);
28516 PolygonGeometry.prototype.getVertices2d = function () {
28517 return this._polygon.slice();
28520 PolygonGeometry.prototype.getVertices3d = function (transform) {
28521 return this._polygon
28522 .map(function (point) {
28523 return transform.unprojectBasic(point, 200);
28527 * Get a polygon representation of the 3D coordinates for the vertices of each hole
28530 * @param {Transform} transform - The transform of the node related to the geometry.
28531 * @returns {Array<Array<Array<number>>>} Array of hole polygons in 3D world coordinates
28532 * representing the vertices of each hole of the geometry.
28534 PolygonGeometry.prototype.getHoleVertices3d = function (transform) {
28536 for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
28539 .map(function (point) {
28540 return transform.unprojectBasic(point, 200);
28542 holes3d.push(hole3d);
28547 PolygonGeometry.prototype.getCentroid2d = function () {
28548 var polygon = this._polygon;
28552 for (var i = 0; i < polygon.length - 1; i++) {
28553 var xi = polygon[i][0];
28554 var yi = polygon[i][1];
28555 var xi1 = polygon[i + 1][0];
28556 var yi1 = polygon[i + 1][1];
28557 var a = xi * yi1 - xi1 * yi;
28559 centroidX += (xi + xi1) * a;
28560 centroidY += (yi + yi1) * a;
28563 centroidX /= 6 * area;
28564 centroidY /= 6 * area;
28565 return [centroidX, centroidY];
28568 PolygonGeometry.prototype.getCentroid3d = function (transform) {
28569 var centroid2d = this.getCentroid2d();
28570 return transform.unprojectBasic(centroid2d, 200);
28573 PolygonGeometry.prototype.getTriangles3d = function (transform) {
28574 return this._triangulate(this._polygon, this.getPoints3d(transform), this._holes, this.getHoleVertices3d(transform));
28577 PolygonGeometry.prototype.getPoleOfAccessibility2d = function () {
28578 return this._getPoleOfInaccessibility2d(this._polygon.slice());
28581 PolygonGeometry.prototype.getPoleOfAccessibility3d = function (transform) {
28582 var pole2d = this._getPoleOfInaccessibility2d(this._polygon.slice());
28583 return transform.unprojectBasic(pole2d, 200);
28585 return PolygonGeometry;
28586 }(Component_1.VertexGeometry));
28587 exports.PolygonGeometry = PolygonGeometry;
28588 exports.default = PolygonGeometry;
28590 },{"../../../Component":226}],294:[function(require,module,exports){
28592 var __extends = (this && this.__extends) || (function () {
28593 var extendStatics = Object.setPrototypeOf ||
28594 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28595 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28596 return function (d, b) {
28597 extendStatics(d, b);
28598 function __() { this.constructor = d; }
28599 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28602 Object.defineProperty(exports, "__esModule", { value: true });
28603 var Component_1 = require("../../../Component");
28605 * @class RectGeometry
28607 * @classdesc Represents a rectangle geometry in the 2D basic image coordinate system.
28611 * var basicRect = [0.5, 0.3, 0.7, 0.4];
28612 * var rectGeometry = new Mapillary.TagComponent.RectGeometry(basicRect);
28615 var RectGeometry = (function (_super) {
28616 __extends(RectGeometry, _super);
28618 * Create a rectangle geometry.
28621 * @param {Array<number>} rect - An array representing the top-left and bottom-right
28622 * corners of the rectangle in basic coordinates. Ordered according to [x0, y0, x1, y1].
28624 * @throws {GeometryTagError} Rectangle coordinates must be valid basic coordinates.
28626 function RectGeometry(rect) {
28627 var _this = _super.call(this) || this;
28628 if (rect[1] > rect[3]) {
28629 throw new Component_1.GeometryTagError("Basic Y coordinates values can not be inverted.");
28631 for (var _i = 0, rect_1 = rect; _i < rect_1.length; _i++) {
28632 var coord = rect_1[_i];
28633 if (coord < 0 || coord > 1) {
28634 throw new Component_1.GeometryTagError("Basic coordinates must be on the interval [0, 1].");
28637 _this._rect = rect.slice(0, 4);
28638 if (_this._rect[0] > _this._rect[2]) {
28639 _this._inverted = true;
28643 Object.defineProperty(RectGeometry.prototype, "rect", {
28645 * Get rect property.
28646 * @returns {Array<number>} Array representing the top-left and bottom-right
28647 * corners of the rectangle in basic coordinates.
28656 * Set the value of a vertex in the polygon representation of the rectangle.
28658 * @description The polygon is defined to have the first vertex at the
28659 * bottom-left corner with the rest of the vertices following in clockwise order.
28661 * @param {number} index - The index of the vertex to be set.
28662 * @param {Array<number>} value - The new value of the vertex.
28663 * @param {Transform} transform - The transform of the node related to the rectangle.
28665 RectGeometry.prototype.setVertex2d = function (index, value, transform) {
28666 var original = this._rect.slice();
28668 Math.max(0, Math.min(1, value[0])),
28669 Math.max(0, Math.min(1, value[1])),
28673 rect[0] = changed[0];
28674 rect[1] = original[1];
28675 rect[2] = original[2];
28676 rect[3] = changed[1];
28678 else if (index === 1) {
28679 rect[0] = changed[0];
28680 rect[1] = changed[1];
28681 rect[2] = original[2];
28682 rect[3] = original[3];
28684 else if (index === 2) {
28685 rect[0] = original[0];
28686 rect[1] = changed[1];
28687 rect[2] = changed[0];
28688 rect[3] = original[3];
28690 else if (index === 3) {
28691 rect[0] = original[0];
28692 rect[1] = original[1];
28693 rect[2] = changed[0];
28694 rect[3] = changed[1];
28696 if (transform.gpano) {
28697 var passingBoundaryLeft = index < 2 && changed[0] > 0.75 && original[0] < 0.25 ||
28698 index >= 2 && this._inverted && changed[0] > 0.75 && original[2] < 0.25;
28699 var passingBoundaryRight = index < 2 && this._inverted && changed[0] < 0.25 && original[0] > 0.75 ||
28700 index >= 2 && changed[0] < 0.25 && original[2] > 0.75;
28701 if (passingBoundaryLeft || passingBoundaryRight) {
28702 this._inverted = !this._inverted;
28705 if (rect[0] - original[0] < -0.25) {
28706 rect[0] = original[0];
28708 if (rect[2] - original[2] > 0.25) {
28709 rect[2] = original[2];
28712 if (!this._inverted && rect[0] > rect[2] ||
28713 this._inverted && rect[0] < rect[2]) {
28714 rect[0] = original[0];
28715 rect[2] = original[2];
28719 if (rect[0] > rect[2]) {
28720 rect[0] = original[0];
28721 rect[2] = original[2];
28724 if (rect[1] > rect[3]) {
28725 rect[1] = original[1];
28726 rect[3] = original[3];
28728 this._rect[0] = rect[0];
28729 this._rect[1] = rect[1];
28730 this._rect[2] = rect[2];
28731 this._rect[3] = rect[3];
28732 this._notifyChanged$.next(this);
28735 RectGeometry.prototype.setCentroid2d = function (value, transform) {
28736 var original = this._rect.slice();
28737 var x0 = original[0];
28738 var x1 = this._inverted ? original[2] + 1 : original[2];
28739 var y0 = original[1];
28740 var y1 = original[3];
28741 var centerX = x0 + (x1 - x0) / 2;
28742 var centerY = y0 + (y1 - y0) / 2;
28743 var translationX = 0;
28744 if (transform.gpano != null &&
28745 transform.gpano.CroppedAreaImageWidthPixels === transform.gpano.FullPanoWidthPixels) {
28746 translationX = this._inverted ? value[0] + 1 - centerX : value[0] - centerX;
28749 var minTranslationX = -x0;
28750 var maxTranslationX = 1 - x1;
28751 translationX = Math.max(minTranslationX, Math.min(maxTranslationX, value[0] - centerX));
28753 var minTranslationY = -y0;
28754 var maxTranslationY = 1 - y1;
28755 var translationY = Math.max(minTranslationY, Math.min(maxTranslationY, value[1] - centerY));
28756 this._rect[0] = original[0] + translationX;
28757 this._rect[1] = original[1] + translationY;
28758 this._rect[2] = original[2] + translationX;
28759 this._rect[3] = original[3] + translationY;
28760 if (this._rect[0] < 0) {
28761 this._rect[0] += 1;
28762 this._inverted = !this._inverted;
28764 else if (this._rect[0] > 1) {
28765 this._rect[0] -= 1;
28766 this._inverted = !this._inverted;
28768 if (this._rect[2] < 0) {
28769 this._rect[2] += 1;
28770 this._inverted = !this._inverted;
28772 else if (this._rect[2] > 1) {
28773 this._rect[2] -= 1;
28774 this._inverted = !this._inverted;
28776 this._notifyChanged$.next(this);
28779 * Get the 3D coordinates for the vertices of the rectangle with
28780 * interpolated points along the lines.
28782 * @param {Transform} transform - The transform of the node related to
28784 * @returns {Array<Array<number>>} Polygon array of 3D world coordinates
28785 * representing the rectangle.
28787 RectGeometry.prototype.getPoints3d = function (transform) {
28788 return this._getPoints2d(transform)
28789 .map(function (point) {
28790 return transform.unprojectBasic(point, 200);
28794 * Get the coordinates of a vertex from the polygon representation of the geometry.
28796 * @description The first vertex represents the bottom-left corner with the rest of
28797 * the vertices following in clockwise order.
28799 * @param {number} index - Vertex index.
28800 * @returns {Array<number>} Array representing the 2D basic coordinates of the vertex.
28802 RectGeometry.prototype.getVertex2d = function (index) {
28803 return this._rectToVertices2d(this._rect)[index];
28806 * Get a vertex from the polygon representation of the 3D coordinates for the
28807 * vertices of the geometry.
28809 * @description The first vertex represents the bottom-left corner with the rest of
28810 * the vertices following in clockwise order.
28812 * @param {number} index - Vertex index.
28813 * @param {Transform} transform - The transform of the node related to the geometry.
28814 * @returns {Array<Array<number>>} Polygon array of 3D world coordinates representing
28815 * the vertices of the geometry.
28817 RectGeometry.prototype.getVertex3d = function (index, transform) {
28818 return transform.unprojectBasic(this._rectToVertices2d(this._rect)[index], 200);
28821 * Get a polygon representation of the 2D basic coordinates for the vertices of the rectangle.
28823 * @description The first vertex represents the bottom-left corner with the rest of
28824 * the vertices following in clockwise order.
28826 * @returns {Array<Array<number>>} Polygon array of 2D basic coordinates representing
28827 * the rectangle vertices.
28829 RectGeometry.prototype.getVertices2d = function () {
28830 return this._rectToVertices2d(this._rect);
28833 * Get a polygon representation of the 3D coordinates for the vertices of the rectangle.
28835 * @description The first vertex represents the bottom-left corner with the rest of
28836 * the vertices following in clockwise order.
28838 * @param {Transform} transform - The transform of the node related to the rectangle.
28839 * @returns {Array<Array<number>>} Polygon array of 3D world coordinates representing
28840 * the rectangle vertices.
28842 RectGeometry.prototype.getVertices3d = function (transform) {
28843 return this._rectToVertices2d(this._rect)
28844 .map(function (vertex) {
28845 return transform.unprojectBasic(vertex, 200);
28849 RectGeometry.prototype.getCentroid2d = function () {
28850 var rect = this._rect;
28852 var x1 = this._inverted ? rect[2] + 1 : rect[2];
28855 var centroidX = x0 + (x1 - x0) / 2;
28856 var centroidY = y0 + (y1 - y0) / 2;
28857 return [centroidX, centroidY];
28860 RectGeometry.prototype.getCentroid3d = function (transform) {
28861 var centroid2d = this.getCentroid2d();
28862 return transform.unprojectBasic(centroid2d, 200);
28865 RectGeometry.prototype.getPoleOfAccessibility2d = function () {
28866 return this._getPoleOfInaccessibility2d(this._rectToVertices2d(this._rect));
28869 RectGeometry.prototype.getPoleOfAccessibility3d = function (transform) {
28870 var pole2d = this._getPoleOfInaccessibility2d(this._rectToVertices2d(this._rect));
28871 return transform.unprojectBasic(pole2d, 200);
28874 RectGeometry.prototype.getTriangles3d = function (transform) {
28875 return this._triangulate(this._rectToVertices2d(this._rect), this.getVertices3d(transform));
28878 * Check if a particular bottom-right value is valid according to the current
28879 * rectangle coordinates.
28881 * @param {Array<number>} bottomRight - The bottom-right coordinates to validate
28882 * @returns {boolean} Value indicating whether the provided bottom-right coordinates
28885 RectGeometry.prototype.validate = function (bottomRight) {
28886 var rect = this._rect;
28887 if (!this._inverted && bottomRight[0] < rect[0] ||
28888 bottomRight[0] - rect[2] > 0.25 ||
28889 bottomRight[1] < rect[1]) {
28895 * Get the 2D coordinates for the vertices of the rectangle with
28896 * interpolated points along the lines.
28898 * @param {Transform} transform - The transform of the node related to
28900 * @returns {Array<Array<number>>} Polygon array of 2D basic coordinates
28901 * representing the rectangle.
28903 RectGeometry.prototype._getPoints2d = function (transform) {
28904 var vertices2d = this._rectToVertices2d(this._rect);
28905 var sides = vertices2d.length - 1;
28908 for (var i = 0; i < sides; ++i) {
28909 var startX = vertices2d[i][0];
28910 var startY = vertices2d[i][1];
28911 var endX = vertices2d[i + 1][0];
28912 var endY = vertices2d[i + 1][1];
28913 var intervalX = (endX - startX) / (sections - 1);
28914 var intervalY = (endY - startY) / (sections - 1);
28915 for (var j = 0; j < sections; ++j) {
28917 startX + j * intervalX,
28918 startY + j * intervalY,
28920 points2d.push(point);
28926 * Convert the top-left, bottom-right representation of a rectangle to a polygon
28927 * representation of the vertices starting at the bottom-right corner going
28930 * @param {Array<number>} rect - Top-left, bottom-right representation of a
28932 * @returns {Array<Array<number>>} Polygon representation of the vertices of the
28935 RectGeometry.prototype._rectToVertices2d = function (rect) {
28937 [rect[0], rect[3]],
28938 [rect[0], rect[1]],
28939 [this._inverted ? rect[2] + 1 : rect[2], rect[1]],
28940 [this._inverted ? rect[2] + 1 : rect[2], rect[3]],
28941 [rect[0], rect[3]],
28944 return RectGeometry;
28945 }(Component_1.VertexGeometry));
28946 exports.RectGeometry = RectGeometry;
28947 exports.default = RectGeometry;
28949 },{"../../../Component":226}],295:[function(require,module,exports){
28951 /// <reference path="../../../../typings/index.d.ts" />
28952 var __extends = (this && this.__extends) || (function () {
28953 var extendStatics = Object.setPrototypeOf ||
28954 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28955 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28956 return function (d, b) {
28957 extendStatics(d, b);
28958 function __() { this.constructor = d; }
28959 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28962 Object.defineProperty(exports, "__esModule", { value: true });
28963 var earcut = require("earcut");
28964 var polylabel = require("@mapbox/polylabel");
28965 var Component_1 = require("../../../Component");
28967 * @class VertexGeometry
28969 * @classdesc Represents a vertex geometry.
28971 var VertexGeometry = (function (_super) {
28972 __extends(VertexGeometry, _super);
28974 * Create a vertex geometry.
28978 function VertexGeometry() {
28979 return _super.call(this) || this;
28982 * Finds the polygon pole of inaccessibility, the most distant internal
28983 * point from the polygon outline.
28985 * @param {Array<Array<number>>} points2d - 2d points of outline to triangulate.
28986 * @returns {Array<number>} Point of inaccessibility.
28989 VertexGeometry.prototype._getPoleOfInaccessibility2d = function (points2d) {
28990 var pole2d = polylabel([points2d], 3e-2);
28994 * Triangulates a 2d polygon and returns the triangle
28995 * representation as a flattened array of 3d points.
28997 * @param {Array<Array<number>>} points2d - 2d points of outline to triangulate.
28998 * @param {Array<Array<number>>} points3d - 3d points of outline corresponding to the 2d points.
28999 * @param {Array<Array<Array<number>>>} [holes2d] - 2d points of holes to triangulate.
29000 * @param {Array<Array<Array<number>>>} [holes3d] - 3d points of holes corresponding to the 2d points.
29001 * @returns {Array<number>} Flattened array of 3d points ordered based on the triangles.
29004 VertexGeometry.prototype._triangulate = function (points2d, points3d, holes2d, holes3d) {
29005 var data = [points2d.slice(0, -1)];
29006 for (var _i = 0, _a = holes2d != null ? holes2d : []; _i < _a.length; _i++) {
29007 var hole2d = _a[_i];
29008 data.push(hole2d.slice(0, -1));
29010 var points = points3d.slice(0, -1);
29011 for (var _b = 0, _c = holes3d != null ? holes3d : []; _b < _c.length; _b++) {
29012 var hole3d = _c[_b];
29013 points = points.concat(hole3d.slice(0, -1));
29015 var flattened = earcut.flatten(data);
29016 var indices = earcut(flattened.vertices, flattened.holes, flattened.dimensions);
29017 var triangles = [];
29018 for (var i = 0; i < indices.length; ++i) {
29019 var point = points[indices[i]];
29020 triangles.push(point[0]);
29021 triangles.push(point[1]);
29022 triangles.push(point[2]);
29026 return VertexGeometry;
29027 }(Component_1.Geometry));
29028 exports.VertexGeometry = VertexGeometry;
29029 exports.default = VertexGeometry;
29031 },{"../../../Component":226,"@mapbox/polylabel":1,"earcut":8}],296:[function(require,module,exports){
29033 /// <reference path="../../../../typings/index.d.ts" />
29034 Object.defineProperty(exports, "__esModule", { value: true });
29035 var THREE = require("three");
29036 var vd = require("virtual-dom");
29037 var Subject_1 = require("rxjs/Subject");
29038 var Component_1 = require("../../../Component");
29039 var Geo_1 = require("../../../Geo");
29040 var OutlineCreateTag = (function () {
29041 function OutlineCreateTag(geometry, options, transform, viewportCoords) {
29043 this._geometry = geometry;
29044 this._options = { color: options.color == null ? 0xFFFFFF : options.color };
29045 this._transform = transform;
29046 this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
29047 this._outline = this._createOutine();
29048 this._glObjects = [this._outline];
29049 this._aborted$ = new Subject_1.Subject();
29050 this._created$ = new Subject_1.Subject();
29051 this._glObjectsChanged$ = new Subject_1.Subject();
29052 this._geometryChangedSubscription = this._geometry.changed$
29053 .subscribe(function (vertexGeometry) {
29054 _this._disposeOutline();
29055 _this._outline = _this._createOutine();
29056 _this._glObjects = [_this._outline];
29057 _this._glObjectsChanged$.next(_this);
29060 Object.defineProperty(OutlineCreateTag.prototype, "geometry", {
29062 return this._geometry;
29067 Object.defineProperty(OutlineCreateTag.prototype, "glObjects", {
29069 return this._glObjects;
29074 Object.defineProperty(OutlineCreateTag.prototype, "aborted$", {
29076 return this._aborted$;
29081 Object.defineProperty(OutlineCreateTag.prototype, "created$", {
29083 return this._created$;
29088 Object.defineProperty(OutlineCreateTag.prototype, "glObjectsChanged$", {
29090 return this._glObjectsChanged$;
29095 Object.defineProperty(OutlineCreateTag.prototype, "geometryChanged$", {
29098 return this._geometry.changed$
29099 .map(function (geometry) {
29106 OutlineCreateTag.prototype.dispose = function () {
29107 this._disposeOutline();
29108 this._geometryChangedSubscription.unsubscribe();
29110 OutlineCreateTag.prototype.getDOMObjects = function (camera, size) {
29114 offsetHeight: size.height, offsetWidth: size.width,
29116 var abort = function (e) {
29117 e.stopPropagation();
29118 _this._aborted$.next(_this);
29120 if (this._geometry instanceof Component_1.RectGeometry) {
29121 var _a = this._geometry.getVertex2d(1), basicX = _a[0], basicY = _a[1];
29122 var canvasPoint = this._viewportCoords.basicToCanvasSafe(basicX, basicY, container, this._transform, camera);
29123 if (canvasPoint != null) {
29124 var background = this._colorToBackground(this._options.color);
29125 var transform = this._canvasToTransform(canvasPoint);
29126 var pointProperties = {
29127 style: { background: background, transform: transform },
29129 var completerProperties = {
29131 style: { transform: transform },
29133 vNodes.push(vd.h("div.TagInteractor", completerProperties, []));
29134 vNodes.push(vd.h("div.TagVertex", pointProperties, []));
29137 else if (this._geometry instanceof Component_1.PolygonGeometry) {
29138 var polygonGeometry_1 = this._geometry;
29139 var _b = polygonGeometry_1.getVertex2d(0), firstVertexBasicX = _b[0], firstVertexBasicY = _b[1];
29140 var firstVertexCanvas = this._viewportCoords.basicToCanvasSafe(firstVertexBasicX, firstVertexBasicY, container, this._transform, camera);
29141 if (firstVertexCanvas != null) {
29142 var firstOnclick = polygonGeometry_1.polygon.length > 4 ?
29144 e.stopPropagation();
29145 polygonGeometry_1.removeVertex2d(polygonGeometry_1.polygon.length - 2);
29146 _this._created$.next(_this);
29149 var transform = this._canvasToTransform(firstVertexCanvas);
29150 var completerProperties = {
29151 onclick: firstOnclick,
29152 style: { transform: transform },
29154 var firstClass = polygonGeometry_1.polygon.length > 4 ?
29157 vNodes.push(vd.h("div." + firstClass, completerProperties, []));
29159 if (polygonGeometry_1.polygon.length > 3) {
29160 var _c = polygonGeometry_1.getVertex2d(polygonGeometry_1.polygon.length - 3), lastVertexBasicX = _c[0], lastVertexBasicY = _c[1];
29161 var lastVertexCanvas = this._viewportCoords.basicToCanvasSafe(lastVertexBasicX, lastVertexBasicY, container, this._transform, camera);
29162 if (lastVertexCanvas != null) {
29163 var remove = function (e) {
29164 e.stopPropagation();
29165 polygonGeometry_1.removeVertex2d(polygonGeometry_1.polygon.length - 3);
29167 var transform = this._canvasToTransform(lastVertexCanvas);
29168 var completerProperties = {
29170 style: { transform: transform },
29172 vNodes.push(vd.h("div.TagInteractor", completerProperties, []));
29175 var verticesBasic = polygonGeometry_1.polygon.slice();
29176 verticesBasic.splice(-2, 2);
29177 for (var _i = 0, verticesBasic_1 = verticesBasic; _i < verticesBasic_1.length; _i++) {
29178 var vertexBasic = verticesBasic_1[_i];
29179 var vertexCanvas = this._viewportCoords.basicToCanvasSafe(vertexBasic[0], vertexBasic[1], container, this._transform, camera);
29180 if (vertexCanvas != null) {
29181 var background = this._colorToBackground(this._options.color);
29182 var transform = this._canvasToTransform(vertexCanvas);
29183 var pointProperties = {
29185 background: background,
29186 transform: transform,
29189 vNodes.push(vd.h("div.TagVertex", pointProperties, []));
29195 OutlineCreateTag.prototype.addPoint = function (point) {
29196 if (this._geometry instanceof Component_1.RectGeometry) {
29197 var rectGeometry = this._geometry;
29198 if (!rectGeometry.validate(point)) {
29201 this._created$.next(this);
29203 else if (this._geometry instanceof Component_1.PolygonGeometry) {
29204 var polygonGeometry = this._geometry;
29205 polygonGeometry.addVertex2d(point);
29208 OutlineCreateTag.prototype._canvasToTransform = function (canvas) {
29209 var canvasX = Math.round(canvas[0]);
29210 var canvasY = Math.round(canvas[1]);
29211 var transform = "translate(-50%,-50%) translate(" + canvasX + "px," + canvasY + "px)";
29214 OutlineCreateTag.prototype._colorToBackground = function (color) {
29215 return "#" + ("000000" + color.toString(16)).substr(-6);
29217 OutlineCreateTag.prototype._createOutine = function () {
29218 var polygon3d = this._geometry.getPoints3d(this._transform);
29219 var positions = this._getLinePositions(polygon3d);
29220 var geometry = new THREE.BufferGeometry();
29221 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
29222 var material = new THREE.LineBasicMaterial({
29223 color: this._options.color,
29226 return new THREE.Line(geometry, material);
29228 OutlineCreateTag.prototype._disposeOutline = function () {
29229 if (this._outline == null) {
29232 var line = this._outline;
29233 line.geometry.dispose();
29234 line.material.dispose();
29235 this._outline = null;
29236 this._glObjects = [];
29238 OutlineCreateTag.prototype._getLinePositions = function (polygon3d) {
29239 var length = polygon3d.length;
29240 var positions = new Float32Array(length * 3);
29241 for (var i = 0; i < length; ++i) {
29243 var position = polygon3d[i];
29244 positions[index] = position[0];
29245 positions[index + 1] = position[1];
29246 positions[index + 2] = position[2];
29250 return OutlineCreateTag;
29252 exports.OutlineCreateTag = OutlineCreateTag;
29253 exports.default = OutlineCreateTag;
29255 },{"../../../Component":226,"../../../Geo":229,"rxjs/Subject":34,"three":176,"virtual-dom":182}],297:[function(require,module,exports){
29257 /// <reference path="../../../../typings/index.d.ts" />
29258 var __extends = (this && this.__extends) || (function () {
29259 var extendStatics = Object.setPrototypeOf ||
29260 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
29261 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
29262 return function (d, b) {
29263 extendStatics(d, b);
29264 function __() { this.constructor = d; }
29265 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
29268 Object.defineProperty(exports, "__esModule", { value: true });
29269 var THREE = require("three");
29270 var vd = require("virtual-dom");
29271 var Component_1 = require("../../../Component");
29273 * @class OutlineRenderTag
29274 * @classdesc Tag visualizing the properties of an OutlineTag.
29276 var OutlineRenderTag = (function (_super) {
29277 __extends(OutlineRenderTag, _super);
29278 function OutlineRenderTag(tag, transform) {
29279 var _this = _super.call(this, tag, transform) || this;
29280 _this._fill = !transform.gpano ?
29281 _this._createFill() :
29283 _this._holes = _this._tag.lineWidth >= 1 ?
29284 _this._createHoles() :
29286 _this._outline = _this._tag.lineWidth >= 1 ?
29287 _this._createOutline() :
29289 _this._geometryChangedSubscription = _this._tag.geometry.changed$
29290 .subscribe(function (geometry) {
29291 if (_this._fill != null) {
29292 _this._updateFillGeometry();
29294 if (_this._holes.length > 0) {
29295 _this._updateHoleGeometries();
29297 if (_this._outline != null) {
29298 _this._updateOulineGeometry();
29301 _this._changedSubscription = _this._tag.changed$
29302 .subscribe(function (changedTag) {
29303 var glObjectsChanged = false;
29304 if (_this._fill != null) {
29305 _this._updateFillMaterial(_this._fill.material);
29307 if (_this._outline == null) {
29308 if (_this._tag.lineWidth >= 1) {
29309 _this._holes = _this._createHoles();
29310 _this._outline = _this._createOutline();
29311 glObjectsChanged = true;
29315 _this._updateHoleMaterials();
29316 _this._updateOutlineMaterial();
29318 if (glObjectsChanged) {
29319 _this._glObjectsChanged$.next(_this);
29324 OutlineRenderTag.prototype.dispose = function () {
29325 this._disposeFill();
29326 this._disposeHoles();
29327 this._disposeOutline();
29328 this._changedSubscription.unsubscribe();
29329 this._geometryChangedSubscription.unsubscribe();
29331 OutlineRenderTag.prototype.getDOMObjects = function (atlas, camera, size) {
29334 var isRect = this._tag.geometry instanceof Component_1.RectGeometry;
29335 var isPerspective = !this._transform.gpano;
29337 offsetHeight: size.height, offsetWidth: size.width,
29339 if (this._tag.icon != null && (isRect || isPerspective)) {
29340 var _a = this._tag.geometry instanceof Component_1.RectGeometry ?
29341 this._tag.geometry.getVertex2d(this._tag.iconIndex) :
29342 this._tag.geometry.getPoleOfAccessibility2d(), iconBasicX = _a[0], iconBasicY = _a[1];
29343 var iconCanvas = this._viewportCoords.basicToCanvasSafe(iconBasicX, iconBasicY, container, this._transform, camera);
29344 if (iconCanvas != null) {
29345 var interact = function (e) {
29346 _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
29348 if (atlas.loaded) {
29349 var sprite = atlas.getDOMSprite(this._tag.icon, this._tag.iconFloat);
29350 var iconCanvasX = Math.round(iconCanvas[0]);
29351 var iconCanvasY = Math.round(iconCanvas[1]);
29352 var transform = "translate(" + iconCanvasX + "px," + iconCanvasY + "px)";
29353 var click = function (e) {
29354 e.stopPropagation();
29355 _this._tag.click$.next(_this._tag);
29359 onmousedown: interact,
29360 style: { transform: transform },
29362 vNodes.push(vd.h("div.TagSymbol", properties, [sprite]));
29366 else if (this._tag.text != null && (isRect || isPerspective)) {
29367 var _b = this._tag.geometry instanceof Component_1.RectGeometry ?
29368 this._tag.geometry.getVertex2d(3) :
29369 this._tag.geometry.getPoleOfAccessibility2d(), textBasicX = _b[0], textBasicY = _b[1];
29370 var textCanvas = this._viewportCoords.basicToCanvasSafe(textBasicX, textBasicY, container, this._transform, camera);
29371 if (textCanvas != null) {
29372 var textCanvasX = Math.round(textCanvas[0]);
29373 var textCanvasY = Math.round(textCanvas[1]);
29374 var transform = this._tag.geometry instanceof Component_1.RectGeometry ?
29375 "translate(" + textCanvasX + "px," + textCanvasY + "px)" :
29376 "translate(-50%, -50%) translate(" + textCanvasX + "px," + textCanvasY + "px)";
29377 var interact = function (e) {
29378 _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
29381 onmousedown: interact,
29383 color: this._colorToCss(this._tag.textColor),
29384 transform: transform,
29386 textContent: this._tag.text,
29388 vNodes.push(vd.h("span.TagSymbol", properties, []));
29391 if (!this._tag.editable) {
29394 var lineColor = this._colorToCss(this._tag.lineColor);
29395 if (this._tag.geometry instanceof Component_1.RectGeometry) {
29396 var _c = this._tag.geometry.getCentroid2d(), centroidBasicX = _c[0], centroidBasicY = _c[1];
29397 var centroidCanvas = this._viewportCoords.basicToCanvasSafe(centroidBasicX, centroidBasicY, container, this._transform, camera);
29398 if (centroidCanvas != null) {
29399 var interact = this._interact(Component_1.TagOperation.Centroid);
29400 var centroidCanvasX = Math.round(centroidCanvas[0]);
29401 var centroidCanvasY = Math.round(centroidCanvas[1]);
29402 var transform = "translate(-50%, -50%) translate(" + centroidCanvasX + "px," + centroidCanvasY + "px)";
29404 onmousedown: interact,
29405 style: { background: lineColor, transform: transform },
29407 vNodes.push(vd.h("div.TagMover", properties, []));
29410 var vertices2d = this._tag.geometry.getVertices2d();
29411 for (var i = 0; i < vertices2d.length - 1; i++) {
29413 ((this._tag.icon != null && i === this._tag.iconIndex) ||
29414 (this._tag.icon == null && this._tag.text != null && i === 3))) {
29417 var _d = vertices2d[i], vertexBasicX = _d[0], vertexBasicY = _d[1];
29418 var vertexCanvas = this._viewportCoords.basicToCanvasSafe(vertexBasicX, vertexBasicY, container, this._transform, camera);
29419 if (vertexCanvas == null) {
29422 var interact = this._interact(Component_1.TagOperation.Vertex, i);
29423 var vertexCanvasX = Math.round(vertexCanvas[0]);
29424 var vertexCanvasY = Math.round(vertexCanvas[1]);
29425 var transform = "translate(-50%, -50%) translate(" + vertexCanvasX + "px," + vertexCanvasY + "px)";
29427 onmousedown: interact,
29428 style: { background: lineColor, transform: transform },
29431 properties.style.cursor = i % 2 === 0 ? "nesw-resize" : "nwse-resize";
29433 vNodes.push(vd.h("div.TagResizer", properties, []));
29434 if (!this._tag.indicateVertices) {
29437 var pointProperties = {
29438 style: { background: lineColor, transform: transform },
29440 vNodes.push(vd.h("div.TagVertex", pointProperties, []));
29444 OutlineRenderTag.prototype.getGLObjects = function () {
29445 var glObjects = [];
29446 if (this._fill != null) {
29447 glObjects.push(this._fill);
29449 for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
29451 glObjects.push(hole);
29453 if (this._outline != null) {
29454 glObjects.push(this._outline);
29458 OutlineRenderTag.prototype.getRetrievableObjects = function () {
29459 return this._fill != null ? [this._fill] : [];
29461 OutlineRenderTag.prototype._colorToCss = function (color) {
29462 return "#" + ("000000" + color.toString(16)).substr(-6);
29464 OutlineRenderTag.prototype._createFill = function () {
29465 var triangles = this._tag.geometry.getTriangles3d(this._transform);
29466 var positions = new Float32Array(triangles);
29467 var geometry = new THREE.BufferGeometry();
29468 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
29469 geometry.computeBoundingSphere();
29470 var material = new THREE.MeshBasicMaterial({ side: THREE.DoubleSide, transparent: true });
29471 this._updateFillMaterial(material);
29472 return new THREE.Mesh(geometry, material);
29474 OutlineRenderTag.prototype._createHoles = function () {
29476 if (this._tag.geometry instanceof Component_1.PolygonGeometry) {
29477 var polygonGeometry = this._tag.geometry;
29478 var holes3d = polygonGeometry.getHoleVertices3d(this._transform);
29479 for (var _i = 0, holes3d_1 = holes3d; _i < holes3d_1.length; _i++) {
29480 var holePoints3d = holes3d_1[_i];
29481 var hole = this._createLine(holePoints3d);
29487 OutlineRenderTag.prototype._createLine = function (points3d) {
29488 var positions = this._getLinePositions(points3d);
29489 var geometry = new THREE.BufferGeometry();
29490 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
29491 geometry.computeBoundingSphere();
29492 var material = new THREE.LineBasicMaterial();
29493 this._updateLineBasicMaterial(material);
29494 var line = new THREE.Line(geometry, material);
29495 line.renderOrder = 1;
29498 OutlineRenderTag.prototype._createOutline = function () {
29499 var points3d = this._tag.geometry.getPoints3d(this._transform);
29500 return this._createLine(points3d);
29502 OutlineRenderTag.prototype._disposeFill = function () {
29503 if (this._fill == null) {
29506 this._fill.geometry.dispose();
29507 this._fill.material.dispose();
29510 OutlineRenderTag.prototype._disposeHoles = function () {
29511 for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
29513 hole.geometry.dispose();
29514 hole.material.dispose();
29518 OutlineRenderTag.prototype._disposeOutline = function () {
29519 if (this._outline == null) {
29522 this._outline.geometry.dispose();
29523 this._outline.material.dispose();
29524 this._outline = null;
29526 OutlineRenderTag.prototype._getLinePositions = function (points3d) {
29527 var length = points3d.length;
29528 var positions = new Float32Array(length * 3);
29529 for (var i = 0; i < length; ++i) {
29531 var position = points3d[i];
29532 positions[index + 0] = position[0];
29533 positions[index + 1] = position[1];
29534 positions[index + 2] = position[2];
29538 OutlineRenderTag.prototype._interact = function (operation, vertexIndex) {
29540 return function (e) {
29541 var offsetX = e.offsetX - e.target.offsetWidth / 2;
29542 var offsetY = e.offsetY - e.target.offsetHeight / 2;
29543 _this._interact$.next({
29546 operation: operation,
29548 vertexIndex: vertexIndex,
29552 OutlineRenderTag.prototype._updateFillGeometry = function () {
29553 var triangles = this._tag.geometry.getTriangles3d(this._transform);
29554 var positions = new Float32Array(triangles);
29555 var geometry = this._fill.geometry;
29556 var attribute = geometry.getAttribute("position");
29557 if (attribute.array.length === positions.length) {
29558 attribute.set(positions);
29559 attribute.needsUpdate = true;
29562 geometry.removeAttribute("position");
29563 geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
29565 geometry.computeBoundingSphere();
29567 OutlineRenderTag.prototype._updateFillMaterial = function (material) {
29568 material.color = new THREE.Color(this._tag.fillColor);
29569 material.opacity = this._tag.fillOpacity;
29570 material.needsUpdate = true;
29572 OutlineRenderTag.prototype._updateHoleGeometries = function () {
29573 var polygonGeometry = this._tag.geometry;
29574 var holes3d = polygonGeometry.getHoleVertices3d(this._transform);
29575 if (holes3d.length !== this._holes.length) {
29576 throw new Error("Changing the number of holes is not supported.");
29578 for (var i = 0; i < this._holes.length; i++) {
29579 var holePoints3d = holes3d[i];
29580 var hole = this._holes[i];
29581 this._updateLine(hole, holePoints3d);
29584 OutlineRenderTag.prototype._updateHoleMaterials = function () {
29585 for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
29587 var material = hole.material;
29588 this._updateLineBasicMaterial(material);
29591 OutlineRenderTag.prototype._updateLine = function (line, points3d) {
29592 var positions = this._getLinePositions(points3d);
29593 var geometry = line.geometry;
29594 var attribute = geometry.getAttribute("position");
29595 attribute.set(positions);
29596 attribute.needsUpdate = true;
29597 geometry.computeBoundingSphere();
29599 OutlineRenderTag.prototype._updateOulineGeometry = function () {
29600 var points3d = this._tag.geometry.getPoints3d(this._transform);
29601 this._updateLine(this._outline, points3d);
29603 OutlineRenderTag.prototype._updateOutlineMaterial = function () {
29604 var material = this._outline.material;
29605 this._updateLineBasicMaterial(material);
29607 OutlineRenderTag.prototype._updateLineBasicMaterial = function (material) {
29608 material.color = new THREE.Color(this._tag.lineColor);
29609 material.linewidth = Math.max(this._tag.lineWidth, 1);
29610 material.visible = this._tag.lineWidth >= 1 && this._tag.lineOpacity > 0;
29611 material.opacity = this._tag.lineOpacity;
29612 material.transparent = this._tag.lineOpacity < 1;
29613 material.needsUpdate = true;
29615 return OutlineRenderTag;
29616 }(Component_1.RenderTag));
29617 exports.OutlineRenderTag = OutlineRenderTag;
29619 },{"../../../Component":226,"three":176,"virtual-dom":182}],298:[function(require,module,exports){
29621 var __extends = (this && this.__extends) || (function () {
29622 var extendStatics = Object.setPrototypeOf ||
29623 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
29624 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
29625 return function (d, b) {
29626 extendStatics(d, b);
29627 function __() { this.constructor = d; }
29628 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
29631 Object.defineProperty(exports, "__esModule", { value: true });
29632 var Subject_1 = require("rxjs/Subject");
29633 var Component_1 = require("../../../Component");
29634 var Viewer_1 = require("../../../Viewer");
29636 * @class OutlineTag
29638 * @classdesc Tag holding properties for visualizing a geometry outline.
29642 * var geometry = new Mapillary.TagComponent.RectGeometry([0.3, 0.3, 0.5, 0.4]);
29643 * var tag = new Mapillary.TagComponent.OutlineTag(
29646 * { editable: true, lineColor: 0xff0000 });
29648 * tagComponent.add([tag]);
29651 var OutlineTag = (function (_super) {
29652 __extends(OutlineTag, _super);
29654 * Create an outline tag.
29658 * @param {string} id - Unique identifier of the tag.
29659 * @param {VertexGeometry} geometry - Geometry defining vertices of tag.
29660 * @param {IOutlineTagOptions} options - Options defining the visual appearance and
29661 * behavior of the outline tag.
29663 function OutlineTag(id, geometry, options) {
29664 var _this = _super.call(this, id, geometry) || this;
29665 options = !!options ? options : {};
29666 _this._editable = options.editable == null ? false : options.editable;
29667 _this._fillColor = options.fillColor == null ? 0xFFFFFF : options.fillColor;
29668 _this._fillOpacity = options.fillOpacity == null ? 0.0 : options.fillOpacity;
29669 _this._icon = options.icon === undefined ? null : options.icon;
29670 _this._iconFloat = options.iconFloat == null ? Viewer_1.Alignment.Center : options.iconFloat;
29671 _this._iconIndex = options.iconIndex == null ? 3 : options.iconIndex;
29672 _this._indicateVertices = options.indicateVertices == null ? true : options.indicateVertices;
29673 _this._lineColor = options.lineColor == null ? 0xFFFFFF : options.lineColor;
29674 _this._lineOpacity = options.lineOpacity == null ? 1 : options.lineOpacity;
29675 _this._lineWidth = options.lineWidth == null ? 1 : options.lineWidth;
29676 _this._text = options.text === undefined ? null : options.text;
29677 _this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor;
29678 _this._click$ = new Subject_1.Subject();
29680 .subscribe(function (t) {
29681 _this.fire(OutlineTag.click, _this);
29685 Object.defineProperty(OutlineTag.prototype, "click$", {
29687 * Click observable.
29689 * @description An observable emitting the tag when the icon of the
29690 * tag has been clicked.
29692 * @returns {Observable<Tag>}
29695 return this._click$;
29700 Object.defineProperty(OutlineTag.prototype, "editable", {
29702 * Get editable property.
29703 * @returns {boolean} Value indicating if tag is editable.
29706 return this._editable;
29709 * Set editable property.
29712 * @fires Tag#changed
29714 set: function (value) {
29715 this._editable = value;
29716 this._notifyChanged$.next(this);
29721 Object.defineProperty(OutlineTag.prototype, "fillColor", {
29723 * Get fill color property.
29724 * @returns {number}
29727 return this._fillColor;
29730 * Set fill color property.
29733 * @fires Tag#changed
29735 set: function (value) {
29736 this._fillColor = value;
29737 this._notifyChanged$.next(this);
29742 Object.defineProperty(OutlineTag.prototype, "fillOpacity", {
29744 * Get fill opacity property.
29745 * @returns {number}
29748 return this._fillOpacity;
29751 * Set fill opacity property.
29754 * @fires Tag#changed
29756 set: function (value) {
29757 this._fillOpacity = value;
29758 this._notifyChanged$.next(this);
29763 Object.defineProperty(OutlineTag.prototype, "geometry", {
29766 return this._geometry;
29771 Object.defineProperty(OutlineTag.prototype, "icon", {
29773 * Get icon property.
29774 * @returns {string}
29780 * Set icon property.
29783 * @fires Tag#changed
29785 set: function (value) {
29786 this._icon = value;
29787 this._notifyChanged$.next(this);
29792 Object.defineProperty(OutlineTag.prototype, "iconFloat", {
29794 * Get icon float property.
29795 * @returns {Alignment}
29798 return this._iconFloat;
29801 * Set icon float property.
29802 * @param {Alignment}
29804 * @fires Tag#changed
29806 set: function (value) {
29807 this._iconFloat = value;
29808 this._notifyChanged$.next(this);
29813 Object.defineProperty(OutlineTag.prototype, "iconIndex", {
29815 * Get icon index property.
29816 * @returns {number}
29819 return this._iconIndex;
29822 * Set icon index property.
29825 * @fires Tag#changed
29827 set: function (value) {
29828 this._iconIndex = value;
29829 this._notifyChanged$.next(this);
29834 Object.defineProperty(OutlineTag.prototype, "indicateVertices", {
29836 * Get indicate vertices property.
29837 * @returns {boolean} Value indicating if vertices should be indicated
29838 * when tag is editable.
29841 return this._indicateVertices;
29844 * Set indicate vertices property.
29847 * @fires Tag#changed
29849 set: function (value) {
29850 this._indicateVertices = value;
29851 this._notifyChanged$.next(this);
29856 Object.defineProperty(OutlineTag.prototype, "lineColor", {
29858 * Get line color property.
29859 * @returns {number}
29862 return this._lineColor;
29865 * Set line color property.
29868 * @fires Tag#changed
29870 set: function (value) {
29871 this._lineColor = value;
29872 this._notifyChanged$.next(this);
29877 Object.defineProperty(OutlineTag.prototype, "lineOpacity", {
29879 * Get line opacity property.
29880 * @returns {number}
29883 return this._lineOpacity;
29886 * Set line opacity property.
29889 * @fires Tag#changed
29891 set: function (value) {
29892 this._lineOpacity = value;
29893 this._notifyChanged$.next(this);
29898 Object.defineProperty(OutlineTag.prototype, "lineWidth", {
29900 * Get line width property.
29901 * @returns {number}
29904 return this._lineWidth;
29907 * Set line width property.
29910 * @fires Tag#changed
29912 set: function (value) {
29913 this._lineWidth = value;
29914 this._notifyChanged$.next(this);
29919 Object.defineProperty(OutlineTag.prototype, "text", {
29921 * Get text property.
29922 * @returns {string}
29928 * Set text property.
29931 * @fires Tag#changed
29933 set: function (value) {
29934 this._text = value;
29935 this._notifyChanged$.next(this);
29940 Object.defineProperty(OutlineTag.prototype, "textColor", {
29942 * Get text color property.
29943 * @returns {number}
29946 return this._textColor;
29949 * Set text color property.
29952 * @fires Tag#changed
29954 set: function (value) {
29955 this._textColor = value;
29956 this._notifyChanged$.next(this);
29962 * Set options for tag.
29964 * @description Sets all the option properties provided and keeps
29965 * the rest of the values as is.
29967 * @param {IOutlineTagOptions} options - Outline tag options
29969 * @fires {Tag#changed}
29971 OutlineTag.prototype.setOptions = function (options) {
29972 this._editable = options.editable == null ? this._editable : options.editable;
29973 this._icon = options.icon === undefined ? this._icon : options.icon;
29974 this._iconFloat = options.iconFloat == null ? this._iconFloat : options.iconFloat;
29975 this._iconIndex = options.iconIndex == null ? this._iconIndex : options.iconIndex;
29976 this._indicateVertices = options.indicateVertices == null ? this._indicateVertices : options.indicateVertices;
29977 this._lineColor = options.lineColor == null ? this._lineColor : options.lineColor;
29978 this._lineWidth = options.lineWidth == null ? this._lineWidth : options.lineWidth;
29979 this._fillColor = options.fillColor == null ? this._fillColor : options.fillColor;
29980 this._fillOpacity = options.fillOpacity == null ? this._fillOpacity : options.fillOpacity;
29981 this._text = options.text === undefined ? this._text : options.text;
29982 this._textColor = options.textColor == null ? this._textColor : options.textColor;
29983 this._notifyChanged$.next(this);
29986 * Event fired when the icon of the outline tag is clicked.
29988 * @event OutlineTag#click
29989 * @type {OutlineTag} The tag instance that was clicked.
29991 OutlineTag.click = "click";
29993 }(Component_1.Tag));
29994 exports.OutlineTag = OutlineTag;
29995 exports.default = OutlineTag;
29997 },{"../../../Component":226,"../../../Viewer":236,"rxjs/Subject":34}],299:[function(require,module,exports){
29999 /// <reference path="../../../../typings/index.d.ts" />
30000 Object.defineProperty(exports, "__esModule", { value: true });
30001 var Subject_1 = require("rxjs/Subject");
30002 var Geo_1 = require("../../../Geo");
30003 var RenderTag = (function () {
30004 function RenderTag(tag, transform, viewportCoords) {
30006 this._transform = transform;
30007 this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
30008 this._glObjectsChanged$ = new Subject_1.Subject();
30009 this._interact$ = new Subject_1.Subject();
30011 Object.defineProperty(RenderTag.prototype, "glObjectsChanged$", {
30013 return this._glObjectsChanged$;
30018 Object.defineProperty(RenderTag.prototype, "interact$", {
30020 return this._interact$;
30025 Object.defineProperty(RenderTag.prototype, "tag", {
30034 exports.RenderTag = RenderTag;
30035 exports.default = RenderTag;
30037 },{"../../../Geo":229,"rxjs/Subject":34}],300:[function(require,module,exports){
30039 /// <reference path="../../../../typings/index.d.ts" />
30040 var __extends = (this && this.__extends) || (function () {
30041 var extendStatics = Object.setPrototypeOf ||
30042 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30043 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30044 return function (d, b) {
30045 extendStatics(d, b);
30046 function __() { this.constructor = d; }
30047 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30050 Object.defineProperty(exports, "__esModule", { value: true });
30051 var vd = require("virtual-dom");
30052 var Component_1 = require("../../../Component");
30053 var Viewer_1 = require("../../../Viewer");
30055 * @class SpotRenderTag
30056 * @classdesc Tag visualizing the properties of a SpotTag.
30058 var SpotRenderTag = (function (_super) {
30059 __extends(SpotRenderTag, _super);
30060 function SpotRenderTag() {
30061 return _super !== null && _super.apply(this, arguments) || this;
30063 SpotRenderTag.prototype.dispose = function () { };
30064 SpotRenderTag.prototype.getDOMObjects = function (atlas, camera, size) {
30066 var tag = this._tag;
30068 offsetHeight: size.height, offsetWidth: size.width,
30071 var _a = tag.geometry.getCentroid2d(), centroidBasicX = _a[0], centroidBasicY = _a[1];
30072 var centroidCanvas = this._viewportCoords.basicToCanvasSafe(centroidBasicX, centroidBasicY, container, this._transform, camera);
30073 if (centroidCanvas != null) {
30074 var interactNone = function (e) {
30075 _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: tag });
30077 var canvasX = Math.round(centroidCanvas[0]);
30078 var canvasY = Math.round(centroidCanvas[1]);
30079 if (tag.icon != null) {
30080 if (atlas.loaded) {
30081 var sprite = atlas.getDOMSprite(tag.icon, Viewer_1.Alignment.Bottom);
30082 var transform_1 = "translate(" + canvasX + "px," + (canvasY + 8) + "px)";
30084 onmousedown: interactNone,
30086 pointerEvents: "all",
30087 transform: transform_1,
30090 vNodes.push(vd.h("div", properties, [sprite]));
30093 else if (tag.text != null) {
30094 var transform_2 = "translate(-50%,0%) translate(" + canvasX + "px," + (canvasY + 8) + "px)";
30096 onmousedown: interactNone,
30098 color: this._colorToCss(tag.textColor),
30099 transform: transform_2,
30101 textContent: tag.text,
30103 vNodes.push(vd.h("span.TagSymbol", properties, []));
30105 var interact = this._interact(Component_1.TagOperation.Centroid, tag);
30106 var background = this._colorToCss(tag.color);
30107 var transform = "translate(-50%,-50%) translate(" + canvasX + "px," + canvasY + "px)";
30108 if (tag.editable) {
30109 var interactorProperties = {
30110 onmousedown: interact,
30112 background: background,
30113 transform: transform,
30116 vNodes.push(vd.h("div.TagSpotInteractor", interactorProperties, []));
30118 var pointProperties = {
30120 background: background,
30121 transform: transform,
30124 vNodes.push(vd.h("div.TagVertex", pointProperties, []));
30128 SpotRenderTag.prototype.getGLObjects = function () { return []; };
30129 SpotRenderTag.prototype.getRetrievableObjects = function () { return []; };
30130 SpotRenderTag.prototype._colorToCss = function (color) {
30131 return "#" + ("000000" + color.toString(16)).substr(-6);
30133 SpotRenderTag.prototype._interact = function (operation, tag, vertexIndex) {
30135 return function (e) {
30136 var offsetX = e.offsetX - e.target.offsetWidth / 2;
30137 var offsetY = e.offsetY - e.target.offsetHeight / 2;
30138 _this._interact$.next({
30141 operation: operation,
30143 vertexIndex: vertexIndex,
30147 return SpotRenderTag;
30148 }(Component_1.RenderTag));
30149 exports.SpotRenderTag = SpotRenderTag;
30151 },{"../../../Component":226,"../../../Viewer":236,"virtual-dom":182}],301:[function(require,module,exports){
30153 var __extends = (this && this.__extends) || (function () {
30154 var extendStatics = Object.setPrototypeOf ||
30155 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30156 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30157 return function (d, b) {
30158 extendStatics(d, b);
30159 function __() { this.constructor = d; }
30160 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30163 Object.defineProperty(exports, "__esModule", { value: true });
30164 var Component_1 = require("../../../Component");
30168 * @classdesc Tag holding properties for visualizing the centroid of a geometry.
30172 * var geometry = new Mapillary.TagComponent.PointGeometry([0.3, 0.3]);
30173 * var tag = new Mapillary.TagComponent.SpotTag(
30176 * { editable: true, color: 0xff0000 });
30178 * tagComponent.add([tag]);
30181 var SpotTag = (function (_super) {
30182 __extends(SpotTag, _super);
30184 * Create a spot tag.
30188 * @param {string} id
30189 * @param {Geometry} geometry
30190 * @param {IOutlineTagOptions} options - Options defining the visual appearance and
30191 * behavior of the spot tag.
30193 function SpotTag(id, geometry, options) {
30194 var _this = _super.call(this, id, geometry) || this;
30195 options = !!options ? options : {};
30196 _this._color = options.color == null ? 0xFFFFFF : options.color;
30197 _this._editable = options.editable == null ? false : options.editable;
30198 _this._icon = options.icon === undefined ? null : options.icon;
30199 _this._text = options.text === undefined ? null : options.text;
30200 _this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor;
30203 Object.defineProperty(SpotTag.prototype, "color", {
30205 * Get color property.
30206 * @returns {number} The color of the spot as a hexagonal number;
30209 return this._color;
30212 * Set color property.
30215 * @fires Tag#changed
30217 set: function (value) {
30218 this._color = value;
30219 this._notifyChanged$.next(this);
30224 Object.defineProperty(SpotTag.prototype, "editable", {
30226 * Get editable property.
30227 * @returns {boolean} Value indicating if tag is editable.
30230 return this._editable;
30233 * Set editable property.
30236 * @fires Tag#changed
30238 set: function (value) {
30239 this._editable = value;
30240 this._notifyChanged$.next(this);
30245 Object.defineProperty(SpotTag.prototype, "icon", {
30247 * Get icon property.
30248 * @returns {string}
30254 * Set icon property.
30257 * @fires Tag#changed
30259 set: function (value) {
30260 this._icon = value;
30261 this._notifyChanged$.next(this);
30266 Object.defineProperty(SpotTag.prototype, "text", {
30268 * Get text property.
30269 * @returns {string}
30275 * Set text property.
30278 * @fires Tag#changed
30280 set: function (value) {
30281 this._text = value;
30282 this._notifyChanged$.next(this);
30287 Object.defineProperty(SpotTag.prototype, "textColor", {
30289 * Get text color property.
30290 * @returns {number}
30293 return this._textColor;
30296 * Set text color property.
30299 * @fires Tag#changed
30301 set: function (value) {
30302 this._textColor = value;
30303 this._notifyChanged$.next(this);
30309 * Set options for tag.
30311 * @description Sets all the option properties provided and keps
30312 * the rest of the values as is.
30314 * @param {ISpotTagOptions} options - Spot tag options
30316 * @fires {Tag#changed}
30318 SpotTag.prototype.setOptions = function (options) {
30319 this._color = options.color == null ? this._color : options.color;
30320 this._editable = options.editable == null ? this._editable : options.editable;
30321 this._icon = options.icon === undefined ? this._icon : options.icon;
30322 this._text = options.text === undefined ? this._text : options.text;
30323 this._textColor = options.textColor == null ? this._textColor : options.textColor;
30324 this._notifyChanged$.next(this);
30327 }(Component_1.Tag));
30328 exports.SpotTag = SpotTag;
30329 exports.default = SpotTag;
30331 },{"../../../Component":226}],302:[function(require,module,exports){
30333 var __extends = (this && this.__extends) || (function () {
30334 var extendStatics = Object.setPrototypeOf ||
30335 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30336 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30337 return function (d, b) {
30338 extendStatics(d, b);
30339 function __() { this.constructor = d; }
30340 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30343 Object.defineProperty(exports, "__esModule", { value: true });
30344 var Subject_1 = require("rxjs/Subject");
30345 require("rxjs/add/operator/map");
30346 require("rxjs/add/operator/share");
30347 var Utils_1 = require("../../../Utils");
30351 * @classdesc Abstract class representing the basic functionality of for a tag.
30353 var Tag = (function (_super) {
30354 __extends(Tag, _super);
30359 * @param {string} id
30360 * @param {Geometry} geometry
30362 function Tag(id, geometry) {
30363 var _this = _super.call(this) || this;
30365 _this._geometry = geometry;
30366 _this._notifyChanged$ = new Subject_1.Subject();
30367 _this._notifyChanged$
30368 .subscribe(function (t) {
30369 _this.fire(Tag.changed, _this);
30371 _this._geometry.changed$
30372 .subscribe(function (g) {
30373 _this.fire(Tag.geometrychanged, _this);
30377 Object.defineProperty(Tag.prototype, "id", {
30380 * @returns {string}
30388 Object.defineProperty(Tag.prototype, "geometry", {
30390 * Get geometry property.
30391 * @returns {Geometry} The geometry of the tag.
30394 return this._geometry;
30399 Object.defineProperty(Tag.prototype, "changed$", {
30401 * Get changed observable.
30402 * @returns {Observable<Tag>}
30406 return this._notifyChanged$;
30411 Object.defineProperty(Tag.prototype, "geometryChanged$", {
30413 * Get geometry changed observable.
30414 * @returns {Observable<Tag>}
30419 return this._geometry.changed$
30420 .map(function (geometry) {
30429 * Event fired when a property related to the visual appearance of the
30432 * @event Tag#changed
30433 * @type {Tag} The tag instance that has changed.
30435 Tag.changed = "changed";
30437 * Event fired when the geometry of the tag has changed.
30439 * @event Tag#geometrychanged
30440 * @type {Tag} The tag instance whose geometry has changed.
30442 Tag.geometrychanged = "geometrychanged";
30444 }(Utils_1.EventEmitter));
30446 exports.default = Tag;
30448 },{"../../../Utils":235,"rxjs/Subject":34,"rxjs/add/operator/map":65,"rxjs/add/operator/share":74}],303:[function(require,module,exports){
30450 var __extends = (this && this.__extends) || (function () {
30451 var extendStatics = Object.setPrototypeOf ||
30452 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30453 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30454 return function (d, b) {
30455 extendStatics(d, b);
30456 function __() { this.constructor = d; }
30457 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30460 Object.defineProperty(exports, "__esModule", { value: true });
30461 var MapillaryError_1 = require("./MapillaryError");
30462 var ArgumentMapillaryError = (function (_super) {
30463 __extends(ArgumentMapillaryError, _super);
30464 function ArgumentMapillaryError(message) {
30465 var _this = _super.call(this, message != null ? message : "The argument is not valid.") || this;
30466 _this.name = "ArgumentMapillaryError";
30469 return ArgumentMapillaryError;
30470 }(MapillaryError_1.MapillaryError));
30471 exports.ArgumentMapillaryError = ArgumentMapillaryError;
30472 exports.default = ArgumentMapillaryError;
30474 },{"./MapillaryError":305}],304:[function(require,module,exports){
30476 var __extends = (this && this.__extends) || (function () {
30477 var extendStatics = Object.setPrototypeOf ||
30478 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30479 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30480 return function (d, b) {
30481 extendStatics(d, b);
30482 function __() { this.constructor = d; }
30483 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30486 Object.defineProperty(exports, "__esModule", { value: true });
30487 var MapillaryError_1 = require("./MapillaryError");
30488 var GraphMapillaryError = (function (_super) {
30489 __extends(GraphMapillaryError, _super);
30490 function GraphMapillaryError(message) {
30491 var _this = _super.call(this, message) || this;
30492 _this.name = "GraphMapillaryError";
30495 return GraphMapillaryError;
30496 }(MapillaryError_1.MapillaryError));
30497 exports.GraphMapillaryError = GraphMapillaryError;
30498 exports.default = GraphMapillaryError;
30500 },{"./MapillaryError":305}],305:[function(require,module,exports){
30502 var __extends = (this && this.__extends) || (function () {
30503 var extendStatics = Object.setPrototypeOf ||
30504 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30505 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30506 return function (d, b) {
30507 extendStatics(d, b);
30508 function __() { this.constructor = d; }
30509 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30512 Object.defineProperty(exports, "__esModule", { value: true });
30513 var MapillaryError = (function (_super) {
30514 __extends(MapillaryError, _super);
30515 function MapillaryError(message) {
30516 var _this = _super.call(this, message) || this;
30517 _this.name = "MapillaryError";
30520 return MapillaryError;
30522 exports.MapillaryError = MapillaryError;
30523 exports.default = MapillaryError;
30525 },{}],306:[function(require,module,exports){
30527 /// <reference path="../../typings/index.d.ts" />
30528 Object.defineProperty(exports, "__esModule", { value: true });
30529 var THREE = require("three");
30533 * @classdesc Holds information about a camera.
30535 var Camera = (function () {
30537 * Create a new camera instance.
30538 * @param {Transform} [transform] - Optional transform instance.
30540 function Camera(transform) {
30541 if (transform != null) {
30542 this._position = new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 0));
30543 this._lookat = new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 10));
30544 this._up = transform.upVector();
30545 this._focal = this._getFocal(transform);
30548 this._position = new THREE.Vector3(0, 0, 0);
30549 this._lookat = new THREE.Vector3(0, 0, 1);
30550 this._up = new THREE.Vector3(0, -1, 0);
30554 Object.defineProperty(Camera.prototype, "position", {
30557 * @returns {THREE.Vector3} The position vector.
30560 return this._position;
30565 Object.defineProperty(Camera.prototype, "lookat", {
30568 * @returns {THREE.Vector3} The lookat vector.
30571 return this._lookat;
30576 Object.defineProperty(Camera.prototype, "up", {
30579 * @returns {THREE.Vector3} The up vector.
30587 Object.defineProperty(Camera.prototype, "focal", {
30590 * @returns {number} The focal length.
30593 return this._focal;
30598 set: function (value) {
30599 this._focal = value;
30605 * Update this camera to the linearly interpolated value of two other cameras.
30607 * @param {Camera} a - First camera.
30608 * @param {Camera} b - Second camera.
30609 * @param {number} alpha - Interpolation value on the interval [0, 1].
30611 Camera.prototype.lerpCameras = function (a, b, alpha) {
30612 this._position.subVectors(b.position, a.position).multiplyScalar(alpha).add(a.position);
30613 this._lookat.subVectors(b.lookat, a.lookat).multiplyScalar(alpha).add(a.lookat);
30614 this._up.subVectors(b.up, a.up).multiplyScalar(alpha).add(a.up);
30615 this._focal = (1 - alpha) * a.focal + alpha * b.focal;
30618 * Copy the properties of another camera to this camera.
30620 * @param {Camera} other - Another camera.
30622 Camera.prototype.copy = function (other) {
30623 this._position.copy(other.position);
30624 this._lookat.copy(other.lookat);
30625 this._up.copy(other.up);
30626 this._focal = other.focal;
30629 * Clone this camera.
30631 * @returns {Camera} A camera with cloned properties equal to this camera.
30633 Camera.prototype.clone = function () {
30634 var camera = new Camera();
30635 camera.position.copy(this._position);
30636 camera.lookat.copy(this._lookat);
30637 camera.up.copy(this._up);
30638 camera.focal = this._focal;
30642 * Determine the distance between this camera and another camera.
30644 * @param {Camera} other - Another camera.
30645 * @returns {number} The distance between the cameras.
30647 Camera.prototype.diff = function (other) {
30648 var pd = this._position.distanceToSquared(other.position);
30649 var ld = this._lookat.distanceToSquared(other.lookat);
30650 var ud = this._up.distanceToSquared(other.up);
30651 var fd = 100 * Math.abs(this._focal - other.focal);
30652 return Math.max(pd, ld, ud, fd);
30655 * Get the focal length based on the transform.
30657 * @description Returns the focal length of the transform if gpano info is not available.
30658 * Returns a focal length corresponding to a vertical fov clamped to [45, 90] degrees based on
30659 * the gpano information if available.
30661 * @returns {number} Focal length.
30663 Camera.prototype._getFocal = function (transform) {
30664 if (transform.gpano == null) {
30665 return transform.focal;
30667 var vFov = Math.PI * transform.gpano.CroppedAreaImageHeightPixels / transform.gpano.FullPanoHeightPixels;
30668 var focal = 0.5 / Math.tan(vFov / 2);
30669 return Math.min(1 / (2 * (Math.sqrt(2) - 1)), Math.max(0.5, focal));
30673 exports.Camera = Camera;
30675 },{"three":176}],307:[function(require,module,exports){
30677 Object.defineProperty(exports, "__esModule", { value: true });
30681 * @classdesc Converts coordinates between the geodetic (WGS84),
30682 * Earth-Centered, Earth-Fixed (ECEF) and local topocentric
30683 * East, North, Up (ENU) reference frames.
30685 * The WGS84 has latitude (degrees), longitude (degrees) and
30686 * altitude (meters) values.
30688 * The ECEF Z-axis pierces the north pole and the
30689 * XY-axis defines the equatorial plane. The X-axis extends
30690 * from the geocenter to the intersection of the Equator and
30691 * the Greenwich Meridian. All values in meters.
30693 * The WGS84 parameters are:
30697 * f = 1 / 298.257223563
30698 * e = Math.sqrt((a^2 - b^2) / a^2)
30699 * e' = Math.sqrt((a^2 - b^2) / b^2)
30701 * The WGS84 to ECEF conversion is performed using the following:
30703 * X = (N - h) * cos(phi) * cos(lambda)
30704 * Y = (N + h) * cos(phi) * sin(lambda)
30705 * Z = (b^2 * N / a^2 + h) * sin(phi)
30710 * lambda = longitude
30711 * h = height above ellipsoid (altitude)
30712 * N = Radius of curvature (meters)
30713 * = a / Math.sqrt(1 - e^2 * sin(phi)^2)
30715 * The ECEF to WGS84 conversion is performed using the following:
30717 * phi = arctan((Z + e'^2 * b * sin(theta)^3) / (p - e^2 * a * cos(theta)^3))
30718 * lambda = arctan(Y / X)
30719 * h = p / cos(phi) - N
30723 * p = Math.sqrt(X^2 + Y^2)
30724 * theta = arctan(Z * a / p * b)
30726 * In the ENU reference frame the x-axis points to the
30727 * East, the y-axis to the North and the z-axis Up. All values
30730 * The ECEF to ENU conversion is performed using the following:
30732 * | x | | -sin(lambda_r) cos(lambda_r) 0 | | X - X_r |
30733 * | y | = | -sin(phi_r) * cos(lambda_r) -sin(phi_r) * sin(lambda_r) cos(phi_r) | | Y - Y_r |
30734 * | z | | cos(phi_r) * cos(lambda_r) cos(phi_r) * sin(lambda_r) sin(phi_r) | | Z - Z_r |
30738 * phi_r = latitude of reference
30739 * lambda_r = longitude of reference
30740 * X_r, Y_r, Z_r = ECEF coordinates of reference
30742 * The ENU to ECEF conversion is performed by solving the above equation for X, Y, Z.
30744 * WGS84 to ENU and ENU to WGS84 are two step conversions with ECEF calculated in
30745 * the first step for both conversions.
30747 var GeoCoords = (function () {
30748 function GeoCoords() {
30749 this._wgs84a = 6378137.0;
30750 this._wgs84b = 6356752.31424518;
30753 * Convert coordinates from geodetic (WGS84) reference to local topocentric
30756 * @param {number} lat Latitude in degrees.
30757 * @param {number} lon Longitude in degrees.
30758 * @param {number} alt Altitude in meters.
30759 * @param {number} refLat Reference latitude in degrees.
30760 * @param {number} refLon Reference longitude in degrees.
30761 * @param {number} refAlt Reference altitude in meters.
30762 * @returns {Array<number>} The x, y, z local topocentric ENU coordinates.
30764 GeoCoords.prototype.geodeticToEnu = function (lat, lon, alt, refLat, refLon, refAlt) {
30765 var ecef = this.geodeticToEcef(lat, lon, alt);
30766 return this.ecefToEnu(ecef[0], ecef[1], ecef[2], refLat, refLon, refAlt);
30769 * Convert coordinates from local topocentric (ENU) reference to
30770 * geodetic (WGS84) reference.
30772 * @param {number} x Topocentric ENU coordinate in East direction.
30773 * @param {number} y Topocentric ENU coordinate in North direction.
30774 * @param {number} z Topocentric ENU coordinate in Up direction.
30775 * @param {number} refLat Reference latitude in degrees.
30776 * @param {number} refLon Reference longitude in degrees.
30777 * @param {number} refAlt Reference altitude in meters.
30778 * @returns {Array<number>} The latitude and longitude in degrees
30779 * as well as altitude in meters.
30781 GeoCoords.prototype.enuToGeodetic = function (x, y, z, refLat, refLon, refAlt) {
30782 var ecef = this.enuToEcef(x, y, z, refLat, refLon, refAlt);
30783 return this.ecefToGeodetic(ecef[0], ecef[1], ecef[2]);
30786 * Convert coordinates from Earth-Centered, Earth-Fixed (ECEF) reference
30787 * to local topocentric (ENU) reference.
30789 * @param {number} X ECEF X-value.
30790 * @param {number} Y ECEF Y-value.
30791 * @param {number} Z ECEF Z-value.
30792 * @param {number} refLat Reference latitude in degrees.
30793 * @param {number} refLon Reference longitude in degrees.
30794 * @param {number} refAlt Reference altitude in meters.
30795 * @returns {Array<number>} The x, y, z topocentric ENU coordinates in East, North
30796 * and Up directions respectively.
30798 GeoCoords.prototype.ecefToEnu = function (X, Y, Z, refLat, refLon, refAlt) {
30799 var refEcef = this.geodeticToEcef(refLat, refLon, refAlt);
30800 var V = [X - refEcef[0], Y - refEcef[1], Z - refEcef[2]];
30801 refLat = refLat * Math.PI / 180.0;
30802 refLon = refLon * Math.PI / 180.0;
30803 var cosLat = Math.cos(refLat);
30804 var sinLat = Math.sin(refLat);
30805 var cosLon = Math.cos(refLon);
30806 var sinLon = Math.sin(refLon);
30807 var x = -sinLon * V[0] + cosLon * V[1];
30808 var y = -sinLat * cosLon * V[0] - sinLat * sinLon * V[1] + cosLat * V[2];
30809 var z = cosLat * cosLon * V[0] + cosLat * sinLon * V[1] + sinLat * V[2];
30813 * Convert coordinates from local topocentric (ENU) reference
30814 * to Earth-Centered, Earth-Fixed (ECEF) reference.
30816 * @param {number} x Topocentric ENU coordinate in East direction.
30817 * @param {number} y Topocentric ENU coordinate in North direction.
30818 * @param {number} z Topocentric ENU coordinate in Up direction.
30819 * @param {number} refLat Reference latitude in degrees.
30820 * @param {number} refLon Reference longitude in degrees.
30821 * @param {number} refAlt Reference altitude in meters.
30822 * @returns {Array<number>} The X, Y, Z ECEF coordinates.
30824 GeoCoords.prototype.enuToEcef = function (x, y, z, refLat, refLon, refAlt) {
30825 var refEcef = this.geodeticToEcef(refLat, refLon, refAlt);
30826 refLat = refLat * Math.PI / 180.0;
30827 refLon = refLon * Math.PI / 180.0;
30828 var cosLat = Math.cos(refLat);
30829 var sinLat = Math.sin(refLat);
30830 var cosLon = Math.cos(refLon);
30831 var sinLon = Math.sin(refLon);
30832 var X = -sinLon * x - sinLat * cosLon * y + cosLat * cosLon * z + refEcef[0];
30833 var Y = cosLon * x - sinLat * sinLon * y + cosLat * sinLon * z + refEcef[1];
30834 var Z = cosLat * y + sinLat * z + refEcef[2];
30838 * Convert coordinates from geodetic reference (WGS84) to Earth-Centered,
30839 * Earth-Fixed (ECEF) reference.
30841 * @param {number} lat Latitude in degrees.
30842 * @param {number} lon Longitude in degrees.
30843 * @param {number} alt Altitude in meters.
30844 * @returns {Array<number>} The X, Y, Z ECEF coordinates.
30846 GeoCoords.prototype.geodeticToEcef = function (lat, lon, alt) {
30847 var a = this._wgs84a;
30848 var b = this._wgs84b;
30849 lat = lat * Math.PI / 180.0;
30850 lon = lon * Math.PI / 180.0;
30851 var cosLat = Math.cos(lat);
30852 var sinLat = Math.sin(lat);
30853 var cosLon = Math.cos(lon);
30854 var sinLon = Math.sin(lon);
30857 var L = 1.0 / Math.sqrt(a2 * cosLat * cosLat + b2 * sinLat * sinLat);
30858 var nhcl = (a2 * L + alt) * cosLat;
30859 var X = nhcl * cosLon;
30860 var Y = nhcl * sinLon;
30861 var Z = (b2 * L + alt) * sinLat;
30865 * Convert coordinates from Earth-Centered, Earth-Fixed (ECEF) reference
30866 * to geodetic reference (WGS84).
30868 * @param {number} X ECEF X-value.
30869 * @param {number} Y ECEF Y-value.
30870 * @param {number} Z ECEF Z-value.
30871 * @returns {Array<number>} The latitude and longitude in degrees
30872 * as well as altitude in meters.
30874 GeoCoords.prototype.ecefToGeodetic = function (X, Y, Z) {
30875 var a = this._wgs84a;
30876 var b = this._wgs84b;
30879 var a2mb2 = a2 - b2;
30880 var ea = Math.sqrt(a2mb2 / a2);
30881 var eb = Math.sqrt(a2mb2 / b2);
30882 var p = Math.sqrt(X * X + Y * Y);
30883 var theta = Math.atan2(Z * a, p * b);
30884 var sinTheta = Math.sin(theta);
30885 var cosTheta = Math.cos(theta);
30886 var lon = Math.atan2(Y, X);
30887 var lat = Math.atan2(Z + eb * eb * b * sinTheta * sinTheta * sinTheta, p - ea * ea * a * cosTheta * cosTheta * cosTheta);
30888 var sinLat = Math.sin(lat);
30889 var cosLat = Math.cos(lat);
30890 var N = a / Math.sqrt(1 - ea * ea * sinLat * sinLat);
30891 var alt = p / cosLat - N;
30892 return [lat * 180.0 / Math.PI, lon * 180.0 / Math.PI, alt];
30896 exports.GeoCoords = GeoCoords;
30897 exports.default = GeoCoords;
30899 },{}],308:[function(require,module,exports){
30901 /// <reference path="../../typings/index.d.ts" />
30902 Object.defineProperty(exports, "__esModule", { value: true });
30903 var THREE = require("three");
30907 * @classdesc Provides methods for scalar, vector and matrix calculations.
30909 var Spatial = (function () {
30910 function Spatial() {
30911 this._epsilon = 1e-9;
30914 * Converts azimuthal phi rotation (counter-clockwise with origin on X-axis) to
30915 * bearing (clockwise with origin at north or Y-axis).
30917 * @param {number} phi - Azimuthal phi angle in radians.
30918 * @returns {number} Bearing in radians.
30920 Spatial.prototype.azimuthalToBearing = function (phi) {
30921 return -phi + Math.PI / 2;
30924 * Converts degrees to radians.
30926 * @param {number} deg - Degrees.
30927 * @returns {number} Radians.
30929 Spatial.prototype.degToRad = function (deg) {
30930 return Math.PI * deg / 180;
30933 * Converts radians to degrees.
30935 * @param {number} rad - Radians.
30936 * @returns {number} Degrees.
30938 Spatial.prototype.radToDeg = function (rad) {
30939 return 180 * rad / Math.PI;
30942 * Creates a rotation matrix from an angle-axis vector.
30944 * @param {Array<number>} angleAxis - Angle-axis representation of a rotation.
30945 * @returns {THREE.Matrix4} Rotation matrix.
30947 Spatial.prototype.rotationMatrix = function (angleAxis) {
30948 var axis = new THREE.Vector3(angleAxis[0], angleAxis[1], angleAxis[2]);
30949 var angle = axis.length();
30953 return new THREE.Matrix4().makeRotationAxis(axis, angle);
30956 * Rotates a vector according to a angle-axis rotation vector.
30958 * @param {Array<number>} vector - Vector to rotate.
30959 * @param {Array<number>} angleAxis - Angle-axis representation of a rotation.
30960 * @returns {THREE.Vector3} Rotated vector.
30962 Spatial.prototype.rotate = function (vector, angleAxis) {
30963 var v = new THREE.Vector3(vector[0], vector[1], vector[2]);
30964 var rotationMatrix = this.rotationMatrix(angleAxis);
30965 v.applyMatrix4(rotationMatrix);
30969 * Calculates the optical center from a rotation vector
30970 * on the angle-axis representation and a translation vector
30971 * according to C = -R^T t.
30973 * @param {Array<number>} rotation - Angle-axis representation of a rotation.
30974 * @param {Array<number>} translation - Translation vector.
30975 * @returns {THREE.Vector3} Optical center.
30977 Spatial.prototype.opticalCenter = function (rotation, translation) {
30978 var angleAxis = [-rotation[0], -rotation[1], -rotation[2]];
30979 var vector = [-translation[0], -translation[1], -translation[2]];
30980 return this.rotate(vector, angleAxis);
30983 * Calculates the viewing direction from a rotation vector
30984 * on the angle-axis representation.
30986 * @param {number[]} rotation - Angle-axis representation of a rotation.
30987 * @returns {THREE.Vector3} Viewing direction.
30989 Spatial.prototype.viewingDirection = function (rotation) {
30990 var angleAxis = [-rotation[0], -rotation[1], -rotation[2]];
30991 return this.rotate([0, 0, 1], angleAxis);
30994 * Wrap a number on the interval [min, max].
30996 * @param {number} value - Value to wrap.
30997 * @param {number} min - Lower endpoint of interval.
30998 * @param {number} max - Upper endpoint of interval.
30999 * @returns {number} The wrapped number.
31001 Spatial.prototype.wrap = function (value, min, max) {
31003 throw new Error("Invalid arguments: max must be larger than min.");
31005 var interval = (max - min);
31006 while (value > max || value < min) {
31008 value = value - interval;
31010 else if (value < min) {
31011 value = value + interval;
31017 * Wrap an angle on the interval [-Pi, Pi].
31019 * @param {number} angle - Value to wrap.
31020 * @returns {number} Wrapped angle.
31022 Spatial.prototype.wrapAngle = function (angle) {
31023 return this.wrap(angle, -Math.PI, Math.PI);
31026 * Limit the value to the interval [min, max] by changing the value to
31027 * the nearest available one when it is outside the interval.
31029 * @param {number} value - Value to clamp.
31030 * @param {number} min - Minimum of the interval.
31031 * @param {number} max - Maximum of the interval.
31032 * @returns {number} Clamped value.
31034 Spatial.prototype.clamp = function (value, min, max) {
31044 * Calculates the counter-clockwise angle from the first
31045 * vector (x1, y1)^T to the second (x2, y2)^T.
31047 * @param {number} x1 - X coordinate of first vector.
31048 * @param {number} y1 - Y coordinate of first vector.
31049 * @param {number} x2 - X coordinate of second vector.
31050 * @param {number} y2 - Y coordinate of second vector.
31051 * @returns {number} Counter clockwise angle between the vectors.
31053 Spatial.prototype.angleBetweenVector2 = function (x1, y1, x2, y2) {
31054 var angle = Math.atan2(y2, x2) - Math.atan2(y1, x1);
31055 return this.wrapAngle(angle);
31058 * Calculates the minimum (absolute) angle change for rotation
31059 * from one angle to another on the [-Pi, Pi] interval.
31061 * @param {number} angle1 - Start angle.
31062 * @param {number} angle2 - Destination angle.
31063 * @returns {number} Absolute angle change between angles.
31065 Spatial.prototype.angleDifference = function (angle1, angle2) {
31066 var angle = angle2 - angle1;
31067 return this.wrapAngle(angle);
31070 * Calculates the relative rotation angle between two
31071 * angle-axis vectors.
31073 * @param {number} rotation1 - First angle-axis vector.
31074 * @param {number} rotation2 - Second angle-axis vector.
31075 * @returns {number} Relative rotation angle.
31077 Spatial.prototype.relativeRotationAngle = function (rotation1, rotation2) {
31078 var R1T = this.rotationMatrix([-rotation1[0], -rotation1[1], -rotation1[2]]);
31079 var R2 = this.rotationMatrix(rotation2);
31080 var R = R1T.multiply(R2);
31081 var elements = R.elements;
31082 // from Tr(R) = 1 + 2*cos(theta)
31083 var theta = Math.acos((elements[0] + elements[5] + elements[10] - 1) / 2);
31087 * Calculates the angle from a vector to a plane.
31089 * @param {Array<number>} vector - The vector.
31090 * @param {Array<number>} planeNormal - Normal of the plane.
31091 * @returns {number} Angle from between plane and vector.
31093 Spatial.prototype.angleToPlane = function (vector, planeNormal) {
31094 var v = new THREE.Vector3().fromArray(vector);
31095 var norm = v.length();
31096 if (norm < this._epsilon) {
31099 var projection = v.dot(new THREE.Vector3().fromArray(planeNormal));
31100 return Math.asin(projection / norm);
31103 * Calculates the distance between two coordinates
31104 * (latitude longitude pairs) in meters according to
31105 * the haversine formula.
31107 * @param {number} lat1 - Latitude of the first coordinate.
31108 * @param {number} lon1 - Longitude of the first coordinate.
31109 * @param {number} lat2 - Latitude of the second coordinate.
31110 * @param {number} lon2 - Longitude of the second coordinate.
31111 * @returns {number} Distance between lat lon positions.
31113 Spatial.prototype.distanceFromLatLon = function (lat1, lon1, lat2, lon2) {
31115 var dLat = this.degToRad(lat2 - lat1);
31116 var dLon = this.degToRad(lon2 - lon1);
31117 var hav = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
31118 Math.cos(lat1) * Math.cos(lat2) *
31119 Math.sin(dLon / 2) * Math.sin(dLon / 2);
31120 var d = 2 * r * Math.atan2(Math.sqrt(hav), Math.sqrt(1 - hav));
31125 exports.Spatial = Spatial;
31126 exports.default = Spatial;
31128 },{"three":176}],309:[function(require,module,exports){
31130 /// <reference path="../../typings/index.d.ts" />
31131 Object.defineProperty(exports, "__esModule", { value: true });
31132 var THREE = require("three");
31136 * @classdesc Class used for calculating coordinate transformations
31139 var Transform = (function () {
31141 * Create a new transform instance.
31142 * @param {Node} apiNavImIm - Node properties.
31143 * @param {HTMLImageElement} image - Node image.
31144 * @param {Array<number>} translation - Node translation vector in three dimensions.
31146 function Transform(node, image, translation) {
31147 this._orientation = this._getValue(node.orientation, 1);
31148 var imageWidth = image != null ? image.width : 4;
31149 var imageHeight = image != null ? image.height : 3;
31150 var keepOrientation = this._orientation < 5;
31151 this._width = this._getValue(node.width, keepOrientation ? imageWidth : imageHeight);
31152 this._height = this._getValue(node.height, keepOrientation ? imageHeight : imageWidth);
31153 this._basicAspect = keepOrientation ?
31154 this._width / this._height :
31155 this._height / this._width;
31156 this._basicWidth = keepOrientation ? node.width : node.height;
31157 this._basicHeight = keepOrientation ? node.height : node.width;
31158 this._focal = this._getValue(node.focal, 1);
31159 this._scale = this._getValue(node.scale, 0);
31160 this._gpano = node.gpano != null ? node.gpano : null;
31161 this._rt = this._getRt(node.rotation, translation);
31162 this._srt = this._getSrt(this._rt, this._scale);
31164 Object.defineProperty(Transform.prototype, "basicAspect", {
31166 * Get basic aspect.
31167 * @returns {number} The orientation adjusted aspect ratio.
31170 return this._basicAspect;
31175 Object.defineProperty(Transform.prototype, "basicHeight", {
31177 * Get basic height.
31179 * @description Does not fall back to node image height but
31180 * uses original value from API so can be faulty.
31182 * @returns {number} The height of the basic version image
31183 * (adjusted for orientation).
31186 return this._basicHeight;
31191 Object.defineProperty(Transform.prototype, "basicWidth", {
31195 * @description Does not fall back to node image width but
31196 * uses original value from API so can be faulty.
31198 * @returns {number} The width of the basic version image
31199 * (adjusted for orientation).
31202 return this._basicWidth;
31207 Object.defineProperty(Transform.prototype, "focal", {
31210 * @returns {number} The node focal length.
31213 return this._focal;
31218 Object.defineProperty(Transform.prototype, "fullPano", {
31222 * @returns {boolean} Value indicating whether the node is a complete
31226 return this._gpano != null &&
31227 this._gpano.CroppedAreaLeftPixels === 0 &&
31228 this._gpano.CroppedAreaTopPixels === 0 &&
31229 this._gpano.CroppedAreaImageWidthPixels === this._gpano.FullPanoWidthPixels &&
31230 this._gpano.CroppedAreaImageHeightPixels === this._gpano.FullPanoHeightPixels;
31235 Object.defineProperty(Transform.prototype, "gpano", {
31238 * @returns {number} The node gpano information.
31241 return this._gpano;
31246 Object.defineProperty(Transform.prototype, "height", {
31250 * @description Falls back to the node image height if
31251 * the API data is faulty.
31253 * @returns {number} The orientation adjusted image height.
31256 return this._height;
31261 Object.defineProperty(Transform.prototype, "orientation", {
31264 * @returns {number} The image orientation.
31267 return this._orientation;
31272 Object.defineProperty(Transform.prototype, "rt", {
31275 * @returns {THREE.Matrix4} The extrinsic camera matrix.
31283 Object.defineProperty(Transform.prototype, "srt", {
31286 * @returns {THREE.Matrix4} The scaled extrinsic camera matrix.
31294 Object.defineProperty(Transform.prototype, "scale", {
31297 * @returns {number} The node atomic reconstruction scale.
31300 return this._scale;
31305 Object.defineProperty(Transform.prototype, "hasValidScale", {
31307 * Get has valid scale.
31308 * @returns {boolean} Value indicating if the scale of the transform is valid.
31311 return this._scale > 1e-2 && this._scale < 50;
31316 Object.defineProperty(Transform.prototype, "width", {
31320 * @description Falls back to the node image width if
31321 * the API data is faulty.
31323 * @returns {number} The orientation adjusted image width.
31326 return this._width;
31332 * Calculate the up vector for the node transform.
31334 * @returns {THREE.Vector3} Normalized and orientation adjusted up vector.
31336 Transform.prototype.upVector = function () {
31337 var rte = this._rt.elements;
31338 switch (this._orientation) {
31340 return new THREE.Vector3(-rte[1], -rte[5], -rte[9]);
31342 return new THREE.Vector3(rte[1], rte[5], rte[9]);
31344 return new THREE.Vector3(-rte[0], -rte[4], -rte[8]);
31346 return new THREE.Vector3(rte[0], rte[4], rte[8]);
31348 return new THREE.Vector3(-rte[1], -rte[5], -rte[9]);
31352 * Calculate projector matrix for projecting 3D points to texture map
31353 * coordinates (u and v).
31355 * @returns {THREE.Matrix4} Projection matrix for 3D point to texture
31356 * map coordinate calculations.
31358 Transform.prototype.projectorMatrix = function () {
31359 var projector = this._normalizedToTextureMatrix();
31360 var f = this._focal;
31361 var projection = new THREE.Matrix4().set(f, 0, 0, 0, 0, f, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0);
31362 projector.multiply(projection);
31363 projector.multiply(this._rt);
31367 * Project 3D world coordinates to basic coordinates.
31369 * @param {Array<number>} point3d - 3D world coordinates.
31370 * @return {Array<number>} 2D basic coordinates.
31372 Transform.prototype.projectBasic = function (point3d) {
31373 var sfm = this.projectSfM(point3d);
31374 return this._sfmToBasic(sfm);
31377 * Unproject basic coordinates to 3D world coordinates.
31379 * @param {Array<number>} basic - 2D basic coordinates.
31380 * @param {Array<number>} distance - Depth to unproject from camera center.
31381 * @returns {Array<number>} Unprojected 3D world coordinates.
31383 Transform.prototype.unprojectBasic = function (basic, distance) {
31384 var sfm = this._basicToSfm(basic);
31385 return this.unprojectSfM(sfm, distance);
31388 * Project 3D world coordinates to SfM coordinates.
31390 * @param {Array<number>} point3d - 3D world coordinates.
31391 * @return {Array<number>} 2D SfM coordinates.
31393 Transform.prototype.projectSfM = function (point3d) {
31394 var v = new THREE.Vector4(point3d[0], point3d[1], point3d[2], 1);
31395 v.applyMatrix4(this._rt);
31396 return this._bearingToSfm([v.x, v.y, v.z]);
31399 * Unproject SfM coordinates to a 3D world coordinates.
31401 * @param {Array<number>} sfm - 2D SfM coordinates.
31402 * @param {Array<number>} distance - Depth to unproject from camera center.
31403 * @returns {Array<number>} Unprojected 3D world coordinates.
31405 Transform.prototype.unprojectSfM = function (sfm, distance) {
31406 var bearing = this._sfmToBearing(sfm);
31407 var v = new THREE.Vector4(distance * bearing[0], distance * bearing[1], distance * bearing[2], 1);
31408 v.applyMatrix4(new THREE.Matrix4().getInverse(this._rt));
31409 return [v.x / v.w, v.y / v.w, v.z / v.w];
31412 * Transform SfM coordinates to bearing vector (3D cartesian
31413 * coordinates on the unit sphere).
31415 * @param {Array<number>} sfm - 2D SfM coordinates.
31416 * @returns {Array<number>} Bearing vector (3D cartesian coordinates
31417 * on the unit sphere).
31419 Transform.prototype._sfmToBearing = function (sfm) {
31420 if (this._fullPano()) {
31421 var lon = sfm[0] * 2 * Math.PI;
31422 var lat = -sfm[1] * 2 * Math.PI;
31423 var x = Math.cos(lat) * Math.sin(lon);
31424 var y = -Math.sin(lat);
31425 var z = Math.cos(lat) * Math.cos(lon);
31428 else if (this._gpano) {
31429 var size = Math.max(this.gpano.CroppedAreaImageWidthPixels, this.gpano.CroppedAreaImageHeightPixels);
31430 var fullPanoPixel = [
31431 sfm[0] * size + this.gpano.CroppedAreaImageWidthPixels / 2 + this.gpano.CroppedAreaLeftPixels,
31432 sfm[1] * size + this.gpano.CroppedAreaImageHeightPixels / 2 + this.gpano.CroppedAreaTopPixels,
31434 var lon = 2 * Math.PI * (fullPanoPixel[0] / this.gpano.FullPanoWidthPixels - 0.5);
31435 var lat = -Math.PI * (fullPanoPixel[1] / this.gpano.FullPanoHeightPixels - 0.5);
31436 var x = Math.cos(lat) * Math.sin(lon);
31437 var y = -Math.sin(lat);
31438 var z = Math.cos(lat) * Math.cos(lon);
31442 var v = new THREE.Vector3(sfm[0], sfm[1], this._focal);
31444 return [v.x, v.y, v.z];
31448 * Transform bearing vector (3D cartesian coordiantes on the unit sphere) to
31451 * @param {Array<number>} bearing - Bearing vector (3D cartesian coordinates on the
31453 * @returns {Array<number>} 2D SfM coordinates.
31455 Transform.prototype._bearingToSfm = function (bearing) {
31456 if (this._fullPano()) {
31457 var x = bearing[0];
31458 var y = bearing[1];
31459 var z = bearing[2];
31460 var lon = Math.atan2(x, z);
31461 var lat = Math.atan2(-y, Math.sqrt(x * x + z * z));
31462 return [lon / (2 * Math.PI), -lat / (2 * Math.PI)];
31464 else if (this._gpano) {
31465 var x = bearing[0];
31466 var y = bearing[1];
31467 var z = bearing[2];
31468 var lon = Math.atan2(x, z);
31469 var lat = Math.atan2(-y, Math.sqrt(x * x + z * z));
31470 var fullPanoPixel = [
31471 (lon / (2 * Math.PI) + 0.5) * this.gpano.FullPanoWidthPixels,
31472 (-lat / Math.PI + 0.5) * this.gpano.FullPanoHeightPixels,
31474 var size = Math.max(this.gpano.CroppedAreaImageWidthPixels, this.gpano.CroppedAreaImageHeightPixels);
31476 (fullPanoPixel[0] - this.gpano.CroppedAreaLeftPixels - this.gpano.CroppedAreaImageWidthPixels / 2) / size,
31477 (fullPanoPixel[1] - this.gpano.CroppedAreaTopPixels - this.gpano.CroppedAreaImageHeightPixels / 2) / size,
31481 if (bearing[2] > 0) {
31483 bearing[0] * this._focal / bearing[2],
31484 bearing[1] * this._focal / bearing[2],
31489 bearing[0] < 0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
31490 bearing[1] < 0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
31496 * Convert basic coordinates to SfM coordinates.
31498 * @param {Array<number>} basic - 2D basic coordinates.
31499 * @returns {Array<number>} 2D SfM coordinates.
31501 Transform.prototype._basicToSfm = function (basic) {
31504 switch (this._orientation) {
31506 rotatedX = basic[0];
31507 rotatedY = basic[1];
31510 rotatedX = 1 - basic[0];
31511 rotatedY = 1 - basic[1];
31514 rotatedX = basic[1];
31515 rotatedY = 1 - basic[0];
31518 rotatedX = 1 - basic[1];
31519 rotatedY = basic[0];
31522 rotatedX = basic[0];
31523 rotatedY = basic[1];
31526 var w = this._width;
31527 var h = this._height;
31528 var s = Math.max(w, h);
31529 var sfmX = rotatedX * w / s - w / s / 2;
31530 var sfmY = rotatedY * h / s - h / s / 2;
31531 return [sfmX, sfmY];
31534 * Convert SfM coordinates to basic coordinates.
31536 * @param {Array<number>} sfm - 2D SfM coordinates.
31537 * @returns {Array<number>} 2D basic coordinates.
31539 Transform.prototype._sfmToBasic = function (sfm) {
31540 var w = this._width;
31541 var h = this._height;
31542 var s = Math.max(w, h);
31543 var rotatedX = (sfm[0] + w / s / 2) / w * s;
31544 var rotatedY = (sfm[1] + h / s / 2) / h * s;
31547 switch (this._orientation) {
31553 basicX = 1 - rotatedX;
31554 basicY = 1 - rotatedY;
31557 basicX = 1 - rotatedY;
31562 basicY = 1 - rotatedX;
31569 return [basicX, basicY];
31572 * Determines if the gpano information indicates a full panorama.
31574 * @returns {boolean} Value determining if the gpano information indicates
31577 Transform.prototype._fullPano = function () {
31578 return this.gpano != null &&
31579 this.gpano.CroppedAreaLeftPixels === 0 &&
31580 this.gpano.CroppedAreaTopPixels === 0 &&
31581 this.gpano.CroppedAreaImageWidthPixels === this.gpano.FullPanoWidthPixels &&
31582 this.gpano.CroppedAreaImageHeightPixels === this.gpano.FullPanoHeightPixels;
31585 * Checks a value and returns it if it exists and is larger than 0.
31586 * Fallbacks if it is null.
31588 * @param {number} value - Value to check.
31589 * @param {number} fallback - Value to fall back to.
31590 * @returns {number} The value or its fallback value if it is not defined or negative.
31592 Transform.prototype._getValue = function (value, fallback) {
31593 return value != null && value > 0 ? value : fallback;
31596 * Creates the extrinsic camera matrix [ R | t ].
31598 * @param {Array<number>} rotation - Rotation vector in angle axis representation.
31599 * @param {Array<number>} translation - Translation vector.
31600 * @returns {THREE.Matrix4} Extrisic camera matrix.
31602 Transform.prototype._getRt = function (rotation, translation) {
31603 var axis = new THREE.Vector3(rotation[0], rotation[1], rotation[2]);
31604 var angle = axis.length();
31608 var rt = new THREE.Matrix4();
31609 rt.makeRotationAxis(axis, angle);
31610 rt.setPosition(new THREE.Vector3(translation[0], translation[1], translation[2]));
31614 * Calculates the scaled extrinsic camera matrix scale * [ R | t ].
31616 * @param {THREE.Matrix4} rt - Extrisic camera matrix.
31617 * @param {number} scale - Scale factor.
31618 * @returns {THREE.Matrix4} Scaled extrisic camera matrix.
31620 Transform.prototype._getSrt = function (rt, scale) {
31621 var srt = rt.clone();
31622 var elements = srt.elements;
31623 elements[12] = scale * elements[12];
31624 elements[13] = scale * elements[13];
31625 elements[14] = scale * elements[14];
31626 srt.scale(new THREE.Vector3(scale, scale, scale));
31630 * Calculate a transformation matrix from normalized coordinates for
31631 * texture map coordinates.
31633 * @returns {THREE.Matrix4} Normalized coordinates to texture map
31634 * coordinates transformation matrix.
31636 Transform.prototype._normalizedToTextureMatrix = function () {
31637 var size = Math.max(this._width, this._height);
31638 var w = size / this._width;
31639 var h = size / this._height;
31640 switch (this._orientation) {
31642 return new THREE.Matrix4().set(w, 0, 0, 0.5, 0, -h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
31644 return new THREE.Matrix4().set(-w, 0, 0, 0.5, 0, h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
31646 return new THREE.Matrix4().set(0, -h, 0, 0.5, -w, 0, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
31648 return new THREE.Matrix4().set(0, h, 0, 0.5, w, 0, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
31650 return new THREE.Matrix4().set(w, 0, 0, 0.5, 0, -h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
31655 exports.Transform = Transform;
31657 },{"three":176}],310:[function(require,module,exports){
31659 /// <reference path="../../typings/index.d.ts" />
31660 Object.defineProperty(exports, "__esModule", { value: true });
31661 var THREE = require("three");
31663 * @class ViewportCoords
31665 * @classdesc Provides methods for calculating 2D coordinate conversions
31666 * as well as 3D projection and unprojection.
31668 * Basic coordinates are 2D coordinates on the [0, 1] interval and
31669 * have the origin point, (0, 0), at the top left corner and the
31670 * maximum value, (1, 1), at the bottom right corner of the original
31673 * Viewport coordinates are 2D coordinates on the [-1, 1] interval and
31674 * have the origin point in the center. The bottom left corner point is
31675 * (-1, -1) and the top right corner point is (1, 1).
31677 * Canvas coordiantes are 2D pixel coordinates on the [0, canvasWidth] and
31678 * [0, canvasHeight] intervals. The origin point (0, 0) is in the top left
31679 * corner and the maximum value is (canvasWidth, canvasHeight) is in the
31680 * bottom right corner.
31682 * 3D coordinates are in the topocentric world reference frame.
31684 var ViewportCoords = (function () {
31685 function ViewportCoords() {
31686 this._unprojectDepth = 200;
31689 * Convert basic coordinates to canvas coordinates.
31691 * @description Transform origin and camera position needs to be the
31692 * equal for reliable return value.
31694 * @param {number} basicX - Basic X coordinate.
31695 * @param {number} basicY - Basic Y coordinate.
31696 * @param {HTMLElement} container - The viewer container.
31697 * @param {Transform} transform - Transform of the node to unproject from.
31698 * @param {THREE.Camera} camera - Camera used in rendering.
31699 * @returns {Array<number>} 2D canvas coordinates.
31701 ViewportCoords.prototype.basicToCanvas = function (basicX, basicY, container, transform, camera) {
31702 var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
31703 var canvas = this.projectToCanvas(point3d, container, camera);
31707 * Convert basic coordinates to canvas coordinates safely. If 3D point is
31708 * behind camera null will be returned.
31710 * @description Transform origin and camera position needs to be the
31711 * equal for reliable return value.
31713 * @param {number} basicX - Basic X coordinate.
31714 * @param {number} basicY - Basic Y coordinate.
31715 * @param {HTMLElement} container - The viewer container.
31716 * @param {Transform} transform - Transform of the node to unproject from.
31717 * @param {THREE.Camera} camera - Camera used in rendering.
31718 * @returns {Array<number>} 2D canvas coordinates if the basic point represents a 3D point
31719 * in front of the camera, otherwise null.
31721 ViewportCoords.prototype.basicToCanvasSafe = function (basicX, basicY, container, transform, camera) {
31722 var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
31723 var pointCamera = this.worldToCamera(point3d, camera);
31724 if (pointCamera[2] > 0) {
31727 var _a = this.cameraToViewport(pointCamera, camera), viewportX = _a[0], viewportY = _a[1];
31728 var canvas = this.viewportToCanvas(viewportX, viewportY, container);
31732 * Convert basic coordinates to viewport coordinates.
31734 * @description Transform origin and camera position needs to be the
31735 * equal for reliable return value.
31737 * @param {number} basicX - Basic X coordinate.
31738 * @param {number} basicY - Basic Y coordinate.
31739 * @param {Transform} transform - Transform of the node to unproject from.
31740 * @param {THREE.Camera} camera - Camera used in rendering.
31741 * @returns {Array<number>} 2D viewport coordinates.
31743 ViewportCoords.prototype.basicToViewport = function (basicX, basicY, transform, camera) {
31744 var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
31745 var viewport = this.projectToViewport(point3d, camera);
31749 * Convert camera 3D coordinates to viewport coordinates.
31751 * @param {number} pointCamera - 3D point in camera coordinate system.
31752 * @param {THREE.Camera} camera - Camera used in rendering.
31753 * @returns {Array<number>} 2D viewport coordinates.
31755 ViewportCoords.prototype.cameraToViewport = function (pointCamera, camera) {
31756 var viewport = new THREE.Vector3().fromArray(pointCamera)
31757 .applyMatrix4(camera.projectionMatrix);
31758 return [viewport.x, viewport.y];
31761 * Get canvas pixel position from event.
31763 * @param {Event} event - Event containing clientX and clientY properties.
31764 * @param {HTMLElement} element - HTML element.
31765 * @returns {Array<number>} 2D canvas coordinates.
31767 ViewportCoords.prototype.canvasPosition = function (event, element) {
31768 var clientRect = element.getBoundingClientRect();
31769 var canvasX = event.clientX - clientRect.left - element.clientLeft;
31770 var canvasY = event.clientY - clientRect.top - element.clientTop;
31771 return [canvasX, canvasY];
31774 * Convert canvas coordinates to basic coordinates.
31776 * @description Transform origin and camera position needs to be the
31777 * equal for reliable return value.
31779 * @param {number} canvasX - Canvas X coordinate.
31780 * @param {number} canvasY - Canvas Y coordinate.
31781 * @param {HTMLElement} container - The viewer container.
31782 * @param {Transform} transform - Transform of the node to unproject from.
31783 * @param {THREE.Camera} camera - Camera used in rendering.
31784 * @returns {Array<number>} 2D basic coordinates.
31786 ViewportCoords.prototype.canvasToBasic = function (canvasX, canvasY, container, transform, camera) {
31787 var point3d = this.unprojectFromCanvas(canvasX, canvasY, container, camera)
31789 var basic = transform.projectBasic(point3d);
31793 * Convert canvas coordinates to viewport coordinates.
31795 * @param {number} canvasX - Canvas X coordinate.
31796 * @param {number} canvasY - Canvas Y coordinate.
31797 * @param {HTMLElement} container - The viewer container.
31798 * @returns {Array<number>} 2D viewport coordinates.
31800 ViewportCoords.prototype.canvasToViewport = function (canvasX, canvasY, container) {
31801 var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
31802 var viewportX = 2 * canvasX / canvasWidth - 1;
31803 var viewportY = 1 - 2 * canvasY / canvasHeight;
31804 return [viewportX, viewportY];
31807 * Determines the width and height of the container in canvas coordinates.
31809 * @param {HTMLElement} container - The viewer container.
31810 * @returns {Array<number>} 2D canvas coordinates.
31812 ViewportCoords.prototype.containerToCanvas = function (container) {
31813 return [container.offsetWidth, container.offsetHeight];
31816 * Determine basic distances from image to canvas corners.
31818 * @description Transform origin and camera position needs to be the
31819 * equal for reliable return value.
31821 * Determines the smallest basic distance for every side of the canvas.
31823 * @param {Transform} transform - Transform of the node to unproject from.
31824 * @param {THREE.Camera} camera - Camera used in rendering.
31825 * @returns {Array<number>} Array of basic distances as [top, right, bottom, left].
31827 ViewportCoords.prototype.getBasicDistances = function (transform, camera) {
31828 var topLeftBasic = this.viewportToBasic(-1, 1, transform, camera);
31829 var topRightBasic = this.viewportToBasic(1, 1, transform, camera);
31830 var bottomRightBasic = this.viewportToBasic(1, -1, transform, camera);
31831 var bottomLeftBasic = this.viewportToBasic(-1, -1, transform, camera);
31832 var topBasicDistance = 0;
31833 var rightBasicDistance = 0;
31834 var bottomBasicDistance = 0;
31835 var leftBasicDistance = 0;
31836 if (topLeftBasic[1] < 0 && topRightBasic[1] < 0) {
31837 topBasicDistance = topLeftBasic[1] > topRightBasic[1] ?
31841 if (topRightBasic[0] > 1 && bottomRightBasic[0] > 1) {
31842 rightBasicDistance = topRightBasic[0] < bottomRightBasic[0] ?
31843 topRightBasic[0] - 1 :
31844 bottomRightBasic[0] - 1;
31846 if (bottomRightBasic[1] > 1 && bottomLeftBasic[1] > 1) {
31847 bottomBasicDistance = bottomRightBasic[1] < bottomLeftBasic[1] ?
31848 bottomRightBasic[1] - 1 :
31849 bottomLeftBasic[1] - 1;
31851 if (bottomLeftBasic[0] < 0 && topLeftBasic[0] < 0) {
31852 leftBasicDistance = bottomLeftBasic[0] > topLeftBasic[0] ?
31853 -bottomLeftBasic[0] :
31856 return [topBasicDistance, rightBasicDistance, bottomBasicDistance, leftBasicDistance];
31859 * Determine pixel distances from image to canvas corners.
31861 * @description Transform origin and camera position needs to be the
31862 * equal for reliable return value.
31864 * Determines the smallest pixel distance for every side of the canvas.
31866 * @param {HTMLElement} container - The viewer container.
31867 * @param {Transform} transform - Transform of the node to unproject from.
31868 * @param {THREE.Camera} camera - Camera used in rendering.
31869 * @returns {Array<number>} Array of pixel distances as [top, right, bottom, left].
31871 ViewportCoords.prototype.getPixelDistances = function (container, transform, camera) {
31872 var topLeftBasic = this.viewportToBasic(-1, 1, transform, camera);
31873 var topRightBasic = this.viewportToBasic(1, 1, transform, camera);
31874 var bottomRightBasic = this.viewportToBasic(1, -1, transform, camera);
31875 var bottomLeftBasic = this.viewportToBasic(-1, -1, transform, camera);
31876 var topPixelDistance = 0;
31877 var rightPixelDistance = 0;
31878 var bottomPixelDistance = 0;
31879 var leftPixelDistance = 0;
31880 var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
31881 if (topLeftBasic[1] < 0 && topRightBasic[1] < 0) {
31882 var basicX = topLeftBasic[1] > topRightBasic[1] ?
31885 var canvas = this.basicToCanvas(basicX, 0, container, transform, camera);
31886 topPixelDistance = canvas[1] > 0 ? canvas[1] : 0;
31888 if (topRightBasic[0] > 1 && bottomRightBasic[0] > 1) {
31889 var basicY = topRightBasic[0] < bottomRightBasic[0] ?
31891 bottomRightBasic[1];
31892 var canvas = this.basicToCanvas(1, basicY, container, transform, camera);
31893 rightPixelDistance = canvas[0] < canvasWidth ? canvasWidth - canvas[0] : 0;
31895 if (bottomRightBasic[1] > 1 && bottomLeftBasic[1] > 1) {
31896 var basicX = bottomRightBasic[1] < bottomLeftBasic[1] ?
31897 bottomRightBasic[0] :
31898 bottomLeftBasic[0];
31899 var canvas = this.basicToCanvas(basicX, 1, container, transform, camera);
31900 bottomPixelDistance = canvas[1] < canvasHeight ? canvasHeight - canvas[1] : 0;
31902 if (bottomLeftBasic[0] < 0 && topLeftBasic[0] < 0) {
31903 var basicY = bottomLeftBasic[0] > topLeftBasic[0] ?
31904 bottomLeftBasic[1] :
31906 var canvas = this.basicToCanvas(0, basicY, container, transform, camera);
31907 leftPixelDistance = canvas[0] > 0 ? canvas[0] : 0;
31909 return [topPixelDistance, rightPixelDistance, bottomPixelDistance, leftPixelDistance];
31912 * Determine if an event occured inside an element.
31914 * @param {Event} event - Event containing clientX and clientY properties.
31915 * @param {HTMLElement} element - HTML element.
31916 * @returns {boolean} Value indicating if the event occured inside the element or not.
31918 ViewportCoords.prototype.insideElement = function (event, element) {
31919 var clientRect = element.getBoundingClientRect();
31920 var minX = clientRect.left + element.clientLeft;
31921 var maxX = minX + element.clientWidth;
31922 var minY = clientRect.top + element.clientTop;
31923 var maxY = minY + element.clientHeight;
31924 return event.clientX > minX &&
31925 event.clientX < maxX &&
31926 event.clientY > minY &&
31927 event.clientY < maxY;
31930 * Project 3D world coordinates to canvas coordinates.
31932 * @param {Array<number>} point3D - 3D world coordinates.
31933 * @param {HTMLElement} container - The viewer container.
31934 * @param {THREE.Camera} camera - Camera used in rendering.
31935 * @returns {Array<number>} 2D canvas coordinates.
31937 ViewportCoords.prototype.projectToCanvas = function (point3d, container, camera) {
31938 var viewport = this.projectToViewport(point3d, camera);
31939 var canvas = this.viewportToCanvas(viewport[0], viewport[1], container);
31943 * Project 3D world coordinates to viewport coordinates.
31945 * @param {Array<number>} point3D - 3D world coordinates.
31946 * @param {THREE.Camera} camera - Camera used in rendering.
31947 * @returns {Array<number>} 2D viewport coordinates.
31949 ViewportCoords.prototype.projectToViewport = function (point3d, camera) {
31950 var viewport = new THREE.Vector3(point3d[0], point3d[1], point3d[2])
31952 return [viewport.x, viewport.y];
31955 * Uproject canvas coordinates to 3D world coordinates.
31957 * @param {number} canvasX - Canvas X coordinate.
31958 * @param {number} canvasY - Canvas Y coordinate.
31959 * @param {HTMLElement} container - The viewer container.
31960 * @param {THREE.Camera} camera - Camera used in rendering.
31961 * @returns {Array<number>} 3D world coordinates.
31963 ViewportCoords.prototype.unprojectFromCanvas = function (canvasX, canvasY, container, camera) {
31964 var viewport = this.canvasToViewport(canvasX, canvasY, container);
31965 var point3d = this.unprojectFromViewport(viewport[0], viewport[1], camera);
31969 * Unproject viewport coordinates to 3D world coordinates.
31971 * @param {number} viewportX - Viewport X coordinate.
31972 * @param {number} viewportY - Viewport Y coordinate.
31973 * @param {THREE.Camera} camera - Camera used in rendering.
31974 * @returns {Array<number>} 3D world coordinates.
31976 ViewportCoords.prototype.unprojectFromViewport = function (viewportX, viewportY, camera) {
31977 var point3d = new THREE.Vector3(viewportX, viewportY, 1)
31978 .unproject(camera);
31982 * Convert viewport coordinates to basic coordinates.
31984 * @description Transform origin and camera position needs to be the
31985 * equal for reliable return value.
31987 * @param {number} viewportX - Viewport X coordinate.
31988 * @param {number} viewportY - Viewport Y coordinate.
31989 * @param {Transform} transform - Transform of the node to unproject from.
31990 * @param {THREE.Camera} camera - Camera used in rendering.
31991 * @returns {Array<number>} 2D basic coordinates.
31993 ViewportCoords.prototype.viewportToBasic = function (viewportX, viewportY, transform, camera) {
31994 var point3d = new THREE.Vector3(viewportX, viewportY, 1)
31997 var basic = transform.projectBasic(point3d);
32001 * Convert viewport coordinates to canvas coordinates.
32003 * @param {number} viewportX - Viewport X coordinate.
32004 * @param {number} viewportY - Viewport Y coordinate.
32005 * @param {HTMLElement} container - The viewer container.
32006 * @returns {Array<number>} 2D canvas coordinates.
32008 ViewportCoords.prototype.viewportToCanvas = function (viewportX, viewportY, container) {
32009 var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
32010 var canvasX = canvasWidth * (viewportX + 1) / 2;
32011 var canvasY = -canvasHeight * (viewportY - 1) / 2;
32012 return [canvasX, canvasY];
32015 * Convert 3D world coordinates to 3D camera coordinates.
32017 * @param {number} point3D - 3D point in world coordinate system.
32018 * @param {THREE.Camera} camera - Camera used in rendering.
32019 * @returns {Array<number>} 3D camera coordinates.
32021 ViewportCoords.prototype.worldToCamera = function (point3d, camera) {
32022 var pointCamera = new THREE.Vector3(point3d[0], point3d[1], point3d[2])
32023 .applyMatrix4(camera.matrixWorldInverse);
32024 return pointCamera.toArray();
32026 return ViewportCoords;
32028 exports.ViewportCoords = ViewportCoords;
32029 exports.default = ViewportCoords;
32031 },{"three":176}],311:[function(require,module,exports){
32033 Object.defineProperty(exports, "__esModule", { value: true });
32037 * @classdesc Represents a class for creating node filters. Implementation and
32038 * definitions based on https://github.com/mapbox/feature-filter.
32040 var FilterCreator = (function () {
32041 function FilterCreator() {
32044 * Create a filter from a filter expression.
32046 * @description The following filters are supported:
32063 * @param {FilterExpression} filter - Comparison, set membership or combinding filter
32065 * @returns {FilterFunction} Function taking a node and returning a boolean that
32066 * indicates whether the node passed the test or not.
32068 FilterCreator.prototype.createFilter = function (filter) {
32069 return new Function("node", "return " + this._compile(filter) + ";");
32071 FilterCreator.prototype._compile = function (filter) {
32072 if (filter == null || filter.length <= 1) {
32075 var operator = filter[0];
32076 var operation = operator === "==" ? this._compileComparisonOp("===", filter[1], filter[2], false) :
32077 operator === "!=" ? this._compileComparisonOp("!==", filter[1], filter[2], false) :
32078 operator === ">" ||
32079 operator === ">=" ||
32080 operator === "<" ||
32081 operator === "<=" ? this._compileComparisonOp(operator, filter[1], filter[2], true) :
32082 operator === "in" ?
32083 this._compileInOp(filter[1], filter.slice(2)) :
32084 operator === "!in" ?
32085 this._compileNegation(this._compileInOp(filter[1], filter.slice(2))) :
32086 operator === "all" ? this._compileLogicalOp(filter.slice(1), "&&") :
32088 return "(" + operation + ")";
32090 FilterCreator.prototype._compare = function (a, b) {
32091 return a < b ? -1 : a > b ? 1 : 0;
32093 FilterCreator.prototype._compileComparisonOp = function (operator, property, value, checkType) {
32094 var left = this._compilePropertyReference(property);
32095 var right = JSON.stringify(value);
32096 return (checkType ? "typeof " + left + "===typeof " + right + "&&" : "") + left + operator + right;
32098 FilterCreator.prototype._compileInOp = function (property, values) {
32099 var compare = this._compare;
32100 var left = JSON.stringify(values.sort(compare));
32101 var right = this._compilePropertyReference(property);
32102 return left + ".indexOf(" + right + ")!==-1";
32104 FilterCreator.prototype._compileLogicalOp = function (filters, operator) {
32105 var compile = this._compile.bind(this);
32106 return filters.map(compile).join(operator);
32108 FilterCreator.prototype._compileNegation = function (expression) {
32109 return "!(" + expression + ")";
32111 FilterCreator.prototype._compilePropertyReference = function (property) {
32112 return "node[" + JSON.stringify(property) + "]";
32114 return FilterCreator;
32116 exports.FilterCreator = FilterCreator;
32117 exports.default = FilterCreator;
32119 },{}],312:[function(require,module,exports){
32121 /// <reference path="../../typings/index.d.ts" />
32122 Object.defineProperty(exports, "__esModule", { value: true });
32123 var rbush = require("rbush");
32124 var Subject_1 = require("rxjs/Subject");
32125 require("rxjs/add/observable/from");
32126 require("rxjs/add/operator/catch");
32127 require("rxjs/add/operator/do");
32128 require("rxjs/add/operator/finally");
32129 require("rxjs/add/operator/map");
32130 require("rxjs/add/operator/publish");
32131 var Edge_1 = require("../Edge");
32132 var Error_1 = require("../Error");
32133 var Graph_1 = require("../Graph");
32137 * @classdesc Represents a graph of nodes with edges.
32139 var Graph = (function () {
32141 * Create a new graph instance.
32143 * @param {APIv3} [apiV3] - API instance for retrieving data.
32144 * @param {rbush.RBush<NodeIndexItem>} [nodeIndex] - Node index for fast spatial retreival.
32145 * @param {GraphCalculator} [graphCalculator] - Instance for graph calculations.
32146 * @param {EdgeCalculator} [edgeCalculator] - Instance for edge calculations.
32147 * @param {FilterCreator} [filterCreator] - Instance for filter creation.
32148 * @param {IGraphConfiguration} [configuration] - Configuration struct.
32150 function Graph(apiV3, nodeIndex, graphCalculator, edgeCalculator, filterCreator, configuration) {
32151 this._apiV3 = apiV3;
32152 this._cachedNodes = {};
32153 this._cachedNodeTiles = {};
32154 this._cachedSpatialEdges = {};
32155 this._cachedTiles = {};
32156 this._cachingFill$ = {};
32157 this._cachingFull$ = {};
32158 this._cachingSequences$ = {};
32159 this._cachingSpatialArea$ = {};
32160 this._cachingTiles$ = {};
32161 this._changed$ = new Subject_1.Subject();
32162 this._defaultAlt = 2;
32163 this._edgeCalculator = edgeCalculator != null ? edgeCalculator : new Edge_1.EdgeCalculator();
32164 this._filterCreator = filterCreator != null ? filterCreator : new Graph_1.FilterCreator();
32165 this._filter = this._filterCreator.createFilter(undefined);
32166 this._graphCalculator = graphCalculator != null ? graphCalculator : new Graph_1.GraphCalculator();
32167 this._configuration = configuration != null ?
32171 maxUnusedNodes: 100,
32172 maxUnusedTiles: 20,
32175 this._nodeIndex = nodeIndex != null ? nodeIndex : rbush(16, [".lat", ".lon", ".lat", ".lon"]);
32176 this._nodeIndexTiles = {};
32177 this._nodeToTile = {};
32178 this._preStored = {};
32179 this._requiredNodeTiles = {};
32180 this._requiredSpatialArea = {};
32181 this._sequences = {};
32182 this._tilePrecision = 7;
32183 this._tileThreshold = 20;
32185 Object.defineProperty(Graph.prototype, "changed$", {
32189 * @returns {Observable<Graph>} Observable emitting
32190 * the graph every time it has changed.
32193 return this._changed$;
32199 * Retrieve and cache node fill properties.
32201 * @param {string} key - Key of node to fill.
32202 * @returns {Observable<Graph>} Observable emitting the graph
32203 * when the node has been updated.
32204 * @throws {GraphMapillaryError} When the operation is not valid on the
32207 Graph.prototype.cacheFill$ = function (key) {
32209 if (key in this._cachingFull$) {
32210 throw new Error_1.GraphMapillaryError("Cannot fill node while caching full (" + key + ").");
32212 if (!this.hasNode(key)) {
32213 throw new Error_1.GraphMapillaryError("Cannot fill node that does not exist in graph (" + key + ").");
32215 if (key in this._cachingFill$) {
32216 return this._cachingFill$[key];
32218 var node = this.getNode(key);
32220 throw new Error_1.GraphMapillaryError("Cannot fill node that is already full (" + key + ").");
32222 this._cachingFill$[key] = this._apiV3.imageByKeyFill$([key])
32223 .do(function (imageByKeyFill) {
32225 _this._makeFull(node, imageByKeyFill[key]);
32227 delete _this._cachingFill$[key];
32229 .map(function (imageByKeyFill) {
32232 .finally(function () {
32233 if (key in _this._cachingFill$) {
32234 delete _this._cachingFill$[key];
32236 _this._changed$.next(_this);
32240 return this._cachingFill$[key];
32243 * Retrieve and cache full node properties.
32245 * @param {string} key - Key of node to fill.
32246 * @returns {Observable<Graph>} Observable emitting the graph
32247 * when the node has been updated.
32248 * @throws {GraphMapillaryError} When the operation is not valid on the
32251 Graph.prototype.cacheFull$ = function (key) {
32253 if (key in this._cachingFull$) {
32254 return this._cachingFull$[key];
32256 if (this.hasNode(key)) {
32257 throw new Error_1.GraphMapillaryError("Cannot cache full node that already exist in graph (" + key + ").");
32259 this._cachingFull$[key] = this._apiV3.imageByKeyFull$([key])
32260 .do(function (imageByKeyFull) {
32261 var fn = imageByKeyFull[key];
32262 if (_this.hasNode(key)) {
32263 var node = _this.getNode(key);
32265 _this._makeFull(node, fn);
32269 if (fn.sequence == null || fn.sequence.key == null) {
32270 throw new Error_1.GraphMapillaryError("Node has no sequence (" + key + ").");
32272 var node = new Graph_1.Node(fn);
32273 _this._makeFull(node, fn);
32274 var h = _this._graphCalculator.encodeH(node.originalLatLon, _this._tilePrecision);
32275 _this._preStore(h, node);
32276 _this._setNode(node);
32277 delete _this._cachingFull$[key];
32280 .map(function (imageByKeyFull) {
32283 .finally(function () {
32284 if (key in _this._cachingFull$) {
32285 delete _this._cachingFull$[key];
32287 _this._changed$.next(_this);
32291 return this._cachingFull$[key];
32294 * Retrieve and cache a node sequence.
32296 * @param {string} key - Key of node for which to retrieve sequence.
32297 * @returns {Observable<Graph>} Observable emitting the graph
32298 * when the sequence has been retrieved.
32299 * @throws {GraphMapillaryError} When the operation is not valid on the
32302 Graph.prototype.cacheNodeSequence$ = function (key) {
32303 if (!this.hasNode(key)) {
32304 throw new Error_1.GraphMapillaryError("Cannot cache sequence edges of node that does not exist in graph (" + key + ").");
32306 var node = this.getNode(key);
32307 if (node.sequenceKey in this._sequences) {
32308 throw new Error_1.GraphMapillaryError("Sequence already cached (" + key + "), (" + node.sequenceKey + ").");
32310 return this._cacheSequence$(node.sequenceKey);
32313 * Retrieve and cache a sequence.
32315 * @param {string} sequenceKey - Key of sequence to cache.
32316 * @returns {Observable<Graph>} Observable emitting the graph
32317 * when the sequence has been retrieved.
32318 * @throws {GraphMapillaryError} When the operation is not valid on the
32321 Graph.prototype.cacheSequence$ = function (sequenceKey) {
32322 if (sequenceKey in this._sequences) {
32323 throw new Error_1.GraphMapillaryError("Sequence already cached (" + sequenceKey + ")");
32325 return this._cacheSequence$(sequenceKey);
32328 * Cache sequence edges for a node.
32330 * @param {string} key - Key of node.
32331 * @throws {GraphMapillaryError} When the operation is not valid on the
32334 Graph.prototype.cacheSequenceEdges = function (key) {
32335 var node = this.getNode(key);
32336 if (!(node.sequenceKey in this._sequences)) {
32337 throw new Error_1.GraphMapillaryError("Sequence is not cached (" + key + "), (" + node.sequenceKey + ")");
32339 var sequence = this._sequences[node.sequenceKey].sequence;
32340 var edges = this._edgeCalculator.computeSequenceEdges(node, sequence);
32341 node.cacheSequenceEdges(edges);
32344 * Retrieve and cache full nodes for a node spatial area.
32346 * @param {string} key - Key of node for which to retrieve sequence.
32347 * @returns {Observable<Graph>} Observable emitting the graph
32348 * when the nodes in the spatial area has been made full.
32349 * @throws {GraphMapillaryError} When the operation is not valid on the
32352 Graph.prototype.cacheSpatialArea$ = function (key) {
32354 if (!this.hasNode(key)) {
32355 throw new Error_1.GraphMapillaryError("Cannot cache spatial area of node that does not exist in graph (" + key + ").");
32357 if (key in this._cachedSpatialEdges) {
32358 throw new Error_1.GraphMapillaryError("Node already spatially cached (" + key + ").");
32360 if (!(key in this._requiredSpatialArea)) {
32361 throw new Error_1.GraphMapillaryError("Spatial area not determined (" + key + ").");
32363 var spatialArea = this._requiredSpatialArea[key];
32364 if (Object.keys(spatialArea.cacheNodes).length === 0) {
32365 throw new Error_1.GraphMapillaryError("Spatial nodes already cached (" + key + ").");
32367 if (key in this._cachingSpatialArea$) {
32368 return this._cachingSpatialArea$[key];
32371 while (spatialArea.cacheKeys.length > 0) {
32372 batches.push(spatialArea.cacheKeys.splice(0, 200));
32374 var batchesToCache = batches.length;
32375 var spatialNodes$ = [];
32376 var _loop_1 = function (batch) {
32377 var spatialNodeBatch$ = this_1._apiV3.imageByKeyFill$(batch)
32378 .do(function (imageByKeyFill) {
32379 for (var fillKey in imageByKeyFill) {
32380 if (!imageByKeyFill.hasOwnProperty(fillKey)) {
32383 var spatialNode = spatialArea.cacheNodes[fillKey];
32384 if (spatialNode.full) {
32385 delete spatialArea.cacheNodes[fillKey];
32388 var fillNode = imageByKeyFill[fillKey];
32389 _this._makeFull(spatialNode, fillNode);
32390 delete spatialArea.cacheNodes[fillKey];
32392 if (--batchesToCache === 0) {
32393 delete _this._cachingSpatialArea$[key];
32396 .map(function (imageByKeyFill) {
32399 .catch(function (error) {
32400 for (var _i = 0, batch_1 = batch; _i < batch_1.length; _i++) {
32401 var batchKey = batch_1[_i];
32402 if (batchKey in spatialArea.all) {
32403 delete spatialArea.all[batchKey];
32405 if (batchKey in spatialArea.cacheNodes) {
32406 delete spatialArea.cacheNodes[batchKey];
32409 if (--batchesToCache === 0) {
32410 delete _this._cachingSpatialArea$[key];
32414 .finally(function () {
32415 if (Object.keys(spatialArea.cacheNodes).length === 0) {
32416 _this._changed$.next(_this);
32421 spatialNodes$.push(spatialNodeBatch$);
32424 for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {
32425 var batch = batches_1[_i];
32428 this._cachingSpatialArea$[key] = spatialNodes$;
32429 return spatialNodes$;
32432 * Cache spatial edges for a node.
32434 * @param {string} key - Key of node.
32435 * @throws {GraphMapillaryError} When the operation is not valid on the
32438 Graph.prototype.cacheSpatialEdges = function (key) {
32439 if (key in this._cachedSpatialEdges) {
32440 throw new Error_1.GraphMapillaryError("Spatial edges already cached (" + key + ").");
32442 var node = this.getNode(key);
32443 var sequence = this._sequences[node.sequenceKey].sequence;
32444 var fallbackKeys = [];
32445 var prevKey = sequence.findPrevKey(node.key);
32446 if (prevKey != null) {
32447 fallbackKeys.push(prevKey);
32449 var nextKey = sequence.findNextKey(node.key);
32450 if (nextKey != null) {
32451 fallbackKeys.push(nextKey);
32453 var allSpatialNodes = this._requiredSpatialArea[key].all;
32454 var potentialNodes = [];
32455 var filter = this._filter;
32456 for (var spatialNodeKey in allSpatialNodes) {
32457 if (!allSpatialNodes.hasOwnProperty(spatialNodeKey)) {
32460 var spatialNode = allSpatialNodes[spatialNodeKey];
32461 if (filter(spatialNode)) {
32462 potentialNodes.push(spatialNode);
32465 var potentialEdges = this._edgeCalculator.getPotentialEdges(node, potentialNodes, fallbackKeys);
32466 var edges = this._edgeCalculator.computeStepEdges(node, potentialEdges, prevKey, nextKey);
32467 edges = edges.concat(this._edgeCalculator.computeTurnEdges(node, potentialEdges));
32468 edges = edges.concat(this._edgeCalculator.computePanoEdges(node, potentialEdges));
32469 edges = edges.concat(this._edgeCalculator.computePerspectiveToPanoEdges(node, potentialEdges));
32470 edges = edges.concat(this._edgeCalculator.computeSimilarEdges(node, potentialEdges));
32471 node.cacheSpatialEdges(edges);
32472 this._cachedSpatialEdges[key] = node;
32473 delete this._requiredSpatialArea[key];
32474 delete this._cachedNodeTiles[key];
32477 * Retrieve and cache geohash tiles for a node.
32479 * @param {string} key - Key of node for which to retrieve tiles.
32480 * @returns {Observable<Graph>} Observable emitting the graph
32481 * when the tiles required for the node has been cached.
32482 * @throws {GraphMapillaryError} When the operation is not valid on the
32485 Graph.prototype.cacheTiles$ = function (key) {
32487 if (key in this._cachedNodeTiles) {
32488 throw new Error_1.GraphMapillaryError("Tiles already cached (" + key + ").");
32490 if (key in this._cachedSpatialEdges) {
32491 throw new Error_1.GraphMapillaryError("Spatial edges already cached so tiles considered cached (" + key + ").");
32493 if (!(key in this._requiredNodeTiles)) {
32494 throw new Error_1.GraphMapillaryError("Tiles have not been determined (" + key + ").");
32496 var nodeTiles = this._requiredNodeTiles[key];
32497 if (nodeTiles.cache.length === 0 &&
32498 nodeTiles.caching.length === 0) {
32499 throw new Error_1.GraphMapillaryError("Tiles already cached (" + key + ").");
32501 if (!this.hasNode(key)) {
32502 throw new Error_1.GraphMapillaryError("Cannot cache tiles of node that does not exist in graph (" + key + ").");
32504 var hs = nodeTiles.cache.slice();
32505 nodeTiles.caching = this._requiredNodeTiles[key].caching.concat(hs);
32506 nodeTiles.cache = [];
32507 var cacheTiles$ = [];
32508 var _loop_2 = function (h) {
32509 var cacheTile$ = null;
32510 if (h in this_2._cachingTiles$) {
32511 cacheTile$ = this_2._cachingTiles$[h];
32514 cacheTile$ = this_2._apiV3.imagesByH$([h])
32515 .do(function (imagesByH) {
32516 var coreNodes = imagesByH[h];
32517 if (h in _this._cachedTiles) {
32520 _this._nodeIndexTiles[h] = [];
32521 _this._cachedTiles[h] = { accessed: new Date().getTime(), nodes: [] };
32522 var hCache = _this._cachedTiles[h].nodes;
32523 var preStored = _this._removeFromPreStore(h);
32524 for (var index in coreNodes) {
32525 if (!coreNodes.hasOwnProperty(index)) {
32528 var coreNode = coreNodes[index];
32529 if (coreNode == null) {
32532 if (coreNode.sequence == null ||
32533 coreNode.sequence.key == null) {
32534 console.warn("Sequence missing, discarding (" + coreNode.key + ")");
32537 if (preStored != null && coreNode.key in preStored) {
32538 var node_1 = preStored[coreNode.key];
32539 delete preStored[coreNode.key];
32540 hCache.push(node_1);
32541 var nodeIndexItem_1 = {
32542 lat: node_1.latLon.lat,
32543 lon: node_1.latLon.lon,
32546 _this._nodeIndex.insert(nodeIndexItem_1);
32547 _this._nodeIndexTiles[h].push(nodeIndexItem_1);
32548 _this._nodeToTile[node_1.key] = h;
32551 var node = new Graph_1.Node(coreNode);
32553 var nodeIndexItem = {
32554 lat: node.latLon.lat,
32555 lon: node.latLon.lon,
32558 _this._nodeIndex.insert(nodeIndexItem);
32559 _this._nodeIndexTiles[h].push(nodeIndexItem);
32560 _this._nodeToTile[node.key] = h;
32561 _this._setNode(node);
32563 delete _this._cachingTiles$[h];
32565 .map(function (imagesByH) {
32568 .catch(function (error) {
32569 delete _this._cachingTiles$[h];
32574 this_2._cachingTiles$[h] = cacheTile$;
32576 cacheTiles$.push(cacheTile$
32577 .do(function (graph) {
32578 var index = nodeTiles.caching.indexOf(h);
32580 nodeTiles.caching.splice(index, 1);
32582 if (nodeTiles.caching.length === 0 &&
32583 nodeTiles.cache.length === 0) {
32584 delete _this._requiredNodeTiles[key];
32585 _this._cachedNodeTiles[key] = true;
32588 .catch(function (error) {
32589 var index = nodeTiles.caching.indexOf(h);
32591 nodeTiles.caching.splice(index, 1);
32593 if (nodeTiles.caching.length === 0 &&
32594 nodeTiles.cache.length === 0) {
32595 delete _this._requiredNodeTiles[key];
32596 _this._cachedNodeTiles[key] = true;
32600 .finally(function () {
32601 _this._changed$.next(_this);
32607 for (var _i = 0, _a = nodeTiles.caching; _i < _a.length; _i++) {
32611 return cacheTiles$;
32614 * Initialize the cache for a node.
32616 * @param {string} key - Key of node.
32617 * @throws {GraphMapillaryError} When the operation is not valid on the
32620 Graph.prototype.initializeCache = function (key) {
32621 if (key in this._cachedNodes) {
32622 throw new Error_1.GraphMapillaryError("Node already in cache (" + key + ").");
32624 var node = this.getNode(key);
32625 node.initializeCache(new Graph_1.NodeCache());
32626 var accessed = new Date().getTime();
32627 this._cachedNodes[key] = { accessed: accessed, node: node };
32628 this._updateCachedTileAccess(key, accessed);
32631 * Get a value indicating if the graph is fill caching a node.
32633 * @param {string} key - Key of node.
32634 * @returns {boolean} Value indicating if the node is being fill cached.
32636 Graph.prototype.isCachingFill = function (key) {
32637 return key in this._cachingFill$;
32640 * Get a value indicating if the graph is fully caching a node.
32642 * @param {string} key - Key of node.
32643 * @returns {boolean} Value indicating if the node is being fully cached.
32645 Graph.prototype.isCachingFull = function (key) {
32646 return key in this._cachingFull$;
32649 * Get a value indicating if the graph is caching a sequence of a node.
32651 * @param {string} key - Key of node.
32652 * @returns {boolean} Value indicating if the sequence of a node is
32655 Graph.prototype.isCachingNodeSequence = function (key) {
32656 var node = this.getNode(key);
32657 return node.sequenceKey in this._cachingSequences$;
32660 * Get a value indicating if the graph is caching a sequence.
32662 * @param {string} sequenceKey - Key of sequence.
32663 * @returns {boolean} Value indicating if the sequence is
32666 Graph.prototype.isCachingSequence = function (sequenceKey) {
32667 return sequenceKey in this._cachingSequences$;
32670 * Get a value indicating if the graph is caching the tiles
32671 * required for calculating spatial edges of a node.
32673 * @param {string} key - Key of node.
32674 * @returns {boolean} Value indicating if the tiles of
32675 * a node are being cached.
32677 Graph.prototype.isCachingTiles = function (key) {
32678 return key in this._requiredNodeTiles &&
32679 this._requiredNodeTiles[key].cache.length === 0 &&
32680 this._requiredNodeTiles[key].caching.length > 0;
32683 * Get a value indicating if the cache has been initialized
32686 * @param {string} key - Key of node.
32687 * @returns {boolean} Value indicating if the cache has been
32688 * initialized for a node.
32690 Graph.prototype.hasInitializedCache = function (key) {
32691 return key in this._cachedNodes;
32694 * Get a value indicating if a node exist in the graph.
32696 * @param {string} key - Key of node.
32697 * @returns {boolean} Value indicating if a node exist in the graph.
32699 Graph.prototype.hasNode = function (key) {
32700 var accessed = new Date().getTime();
32701 this._updateCachedNodeAccess(key, accessed);
32702 this._updateCachedTileAccess(key, accessed);
32703 return key in this._nodes;
32706 * Get a value indicating if a node sequence exist in the graph.
32708 * @param {string} key - Key of node.
32709 * @returns {boolean} Value indicating if a node sequence exist
32712 Graph.prototype.hasNodeSequence = function (key) {
32713 var node = this.getNode(key);
32714 var sequenceKey = node.sequenceKey;
32715 var hasNodeSequence = sequenceKey in this._sequences;
32716 if (hasNodeSequence) {
32717 this._sequences[sequenceKey].accessed = new Date().getTime();
32719 return hasNodeSequence;
32722 * Get a value indicating if a sequence exist in the graph.
32724 * @param {string} sequenceKey - Key of sequence.
32725 * @returns {boolean} Value indicating if a sequence exist
32728 Graph.prototype.hasSequence = function (sequenceKey) {
32729 var hasSequence = sequenceKey in this._sequences;
32731 this._sequences[sequenceKey].accessed = new Date().getTime();
32733 return hasSequence;
32736 * Get a value indicating if the graph has fully cached
32737 * all nodes in the spatial area of a node.
32739 * @param {string} key - Key of node.
32740 * @returns {boolean} Value indicating if the spatial area
32741 * of a node has been cached.
32743 Graph.prototype.hasSpatialArea = function (key) {
32744 if (!this.hasNode(key)) {
32745 throw new Error_1.GraphMapillaryError("Spatial area nodes cannot be determined if node not in graph (" + key + ").");
32747 if (key in this._cachedSpatialEdges) {
32750 if (key in this._requiredSpatialArea) {
32751 return Object.keys(this._requiredSpatialArea[key].cacheNodes).length === 0;
32753 var node = this.getNode(key);
32754 var bbox = this._graphCalculator.boundingBoxCorners(node.latLon, this._tileThreshold);
32755 var spatialItems = this._nodeIndex.search({
32761 var spatialNodes = {
32766 for (var _i = 0, spatialItems_1 = spatialItems; _i < spatialItems_1.length; _i++) {
32767 var spatialItem = spatialItems_1[_i];
32768 spatialNodes.all[spatialItem.node.key] = spatialItem.node;
32769 if (!spatialItem.node.full) {
32770 spatialNodes.cacheKeys.push(spatialItem.node.key);
32771 spatialNodes.cacheNodes[spatialItem.node.key] = spatialItem.node;
32774 this._requiredSpatialArea[key] = spatialNodes;
32775 return spatialNodes.cacheKeys.length === 0;
32778 * Get a value indicating if the graph has a tiles required
32781 * @param {string} key - Key of node.
32782 * @returns {boolean} Value indicating if the the tiles required
32783 * by a node has been cached.
32785 Graph.prototype.hasTiles = function (key) {
32787 if (key in this._cachedNodeTiles) {
32790 if (key in this._cachedSpatialEdges) {
32793 if (!this.hasNode(key)) {
32794 throw new Error_1.GraphMapillaryError("Node does not exist in graph (" + key + ").");
32796 var nodeTiles = { cache: [], caching: [] };
32797 if (!(key in this._requiredNodeTiles)) {
32798 var node = this.getNode(key);
32799 nodeTiles.cache = this._graphCalculator
32800 .encodeHs(node.latLon, this._tilePrecision, this._tileThreshold)
32801 .filter(function (h) {
32802 return !(h in _this._cachedTiles);
32804 if (nodeTiles.cache.length > 0) {
32805 this._requiredNodeTiles[key] = nodeTiles;
32809 nodeTiles = this._requiredNodeTiles[key];
32811 return nodeTiles.cache.length === 0 && nodeTiles.caching.length === 0;
32816 * @param {string} key - Key of node.
32817 * @returns {Node} Retrieved node.
32819 Graph.prototype.getNode = function (key) {
32820 var accessed = new Date().getTime();
32821 this._updateCachedNodeAccess(key, accessed);
32822 this._updateCachedTileAccess(key, accessed);
32823 return this._nodes[key];
32828 * @param {string} sequenceKey - Key of sequence.
32829 * @returns {Node} Retrieved sequence.
32831 Graph.prototype.getSequence = function (sequenceKey) {
32832 var sequenceAccess = this._sequences[sequenceKey];
32833 sequenceAccess.accessed = new Date().getTime();
32834 return sequenceAccess.sequence;
32837 * Reset all spatial edges of the graph nodes.
32839 Graph.prototype.resetSpatialEdges = function () {
32840 var cachedKeys = Object.keys(this._cachedSpatialEdges);
32841 for (var _i = 0, cachedKeys_1 = cachedKeys; _i < cachedKeys_1.length; _i++) {
32842 var cachedKey = cachedKeys_1[_i];
32843 var node = this._cachedSpatialEdges[cachedKey];
32844 node.resetSpatialEdges();
32845 delete this._cachedSpatialEdges[cachedKey];
32849 * Reset the complete graph but keep the nodes corresponding
32850 * to the supplied keys. All other nodes will be disposed.
32852 * @param {Array<string>} keepKeys - Keys for nodes to keep
32853 * in graph after reset.
32855 Graph.prototype.reset = function (keepKeys) {
32857 for (var _i = 0, keepKeys_1 = keepKeys; _i < keepKeys_1.length; _i++) {
32858 var key = keepKeys_1[_i];
32859 if (!this.hasNode(key)) {
32860 throw new Error("Node does not exist " + key);
32862 var node = this.getNode(key);
32863 node.resetSequenceEdges();
32864 node.resetSpatialEdges();
32867 for (var _a = 0, _b = Object.keys(this._cachedNodes); _a < _b.length; _a++) {
32868 var cachedKey = _b[_a];
32869 if (keepKeys.indexOf(cachedKey) !== -1) {
32872 this._cachedNodes[cachedKey].node.dispose();
32873 delete this._cachedNodes[cachedKey];
32875 this._cachedNodeTiles = {};
32876 this._cachedSpatialEdges = {};
32877 this._cachedTiles = {};
32878 this._cachingFill$ = {};
32879 this._cachingFull$ = {};
32880 this._cachingSequences$ = {};
32881 this._cachingSpatialArea$ = {};
32882 this._cachingTiles$ = {};
32884 this._nodeToTile = {};
32885 this._preStored = {};
32886 for (var _c = 0, nodes_1 = nodes; _c < nodes_1.length; _c++) {
32887 var node = nodes_1[_c];
32888 this._nodes[node.key] = node;
32889 var h = this._graphCalculator.encodeH(node.originalLatLon, this._tilePrecision);
32890 this._preStore(h, node);
32892 this._requiredNodeTiles = {};
32893 this._requiredSpatialArea = {};
32894 this._sequences = {};
32895 this._nodeIndexTiles = {};
32896 this._nodeIndex.clear();
32899 * Set the spatial node filter.
32901 * @param {FilterExpression} filter - Filter expression to be applied
32902 * when calculating spatial edges.
32904 Graph.prototype.setFilter = function (filter) {
32905 this._filter = this._filterCreator.createFilter(filter);
32908 * Uncache the graph according to the graph configuration.
32910 * @description Uncaches unused tiles, unused nodes and
32911 * sequences according to the numbers specified in the
32912 * graph configuration. Sequences does not have a direct
32913 * reference to either tiles or nodes and may be uncached
32914 * even if they are related to the nodes that should be kept.
32916 * @param {Array<string>} keepKeys - Keys of nodes to keep in
32917 * graph unrelated to last access. Tiles related to those keys
32918 * will also be kept in graph.
32920 Graph.prototype.uncache = function (keepKeys) {
32921 var keysInUse = {};
32922 this._addNewKeys(keysInUse, this._cachingFull$);
32923 this._addNewKeys(keysInUse, this._cachingFill$);
32924 this._addNewKeys(keysInUse, this._cachingTiles$);
32925 this._addNewKeys(keysInUse, this._cachingSpatialArea$);
32926 this._addNewKeys(keysInUse, this._requiredNodeTiles);
32927 this._addNewKeys(keysInUse, this._requiredSpatialArea);
32928 for (var _i = 0, keepKeys_2 = keepKeys; _i < keepKeys_2.length; _i++) {
32929 var key = keepKeys_2[_i];
32930 if (key in keysInUse) {
32933 keysInUse[key] = true;
32936 for (var key in keysInUse) {
32937 if (!keysInUse.hasOwnProperty(key)) {
32940 var node = this._nodes[key];
32941 var nodeHs = this._graphCalculator.encodeHs(node.latLon);
32942 for (var _a = 0, nodeHs_1 = nodeHs; _a < nodeHs_1.length; _a++) {
32943 var nodeH = nodeHs_1[_a];
32944 if (!(nodeH in keepHs)) {
32945 keepHs[nodeH] = true;
32949 var potentialHs = [];
32950 for (var h in this._cachedTiles) {
32951 if (!this._cachedTiles.hasOwnProperty(h) || h in keepHs) {
32954 potentialHs.push([h, this._cachedTiles[h]]);
32956 var uncacheHs = potentialHs
32957 .sort(function (h1, h2) {
32958 return h2[1].accessed - h1[1].accessed;
32960 .slice(this._configuration.maxUnusedTiles)
32961 .map(function (h) {
32964 for (var _b = 0, uncacheHs_1 = uncacheHs; _b < uncacheHs_1.length; _b++) {
32965 var uncacheH = uncacheHs_1[_b];
32966 this._uncacheTile(uncacheH);
32968 var potentialNodes = [];
32969 for (var key in this._cachedNodes) {
32970 if (!this._cachedNodes.hasOwnProperty(key) || key in keysInUse) {
32973 potentialNodes.push(this._cachedNodes[key]);
32975 var uncacheNodes = potentialNodes
32976 .sort(function (n1, n2) {
32977 return n2.accessed - n1.accessed;
32979 .slice(this._configuration.maxUnusedNodes);
32980 for (var _c = 0, uncacheNodes_1 = uncacheNodes; _c < uncacheNodes_1.length; _c++) {
32981 var nodeAccess = uncacheNodes_1[_c];
32982 nodeAccess.node.uncache();
32983 var key = nodeAccess.node.key;
32984 delete this._cachedNodes[key];
32985 if (key in this._cachedNodeTiles) {
32986 delete this._cachedNodeTiles[key];
32988 if (key in this._cachedSpatialEdges) {
32989 delete this._cachedSpatialEdges[key];
32992 var potentialSequences = [];
32993 for (var sequenceKey in this._sequences) {
32994 if (!this._sequences.hasOwnProperty(sequenceKey) ||
32995 sequenceKey in this._cachingSequences$) {
32998 potentialSequences.push(this._sequences[sequenceKey]);
33000 var uncacheSequences = potentialSequences
33001 .sort(function (s1, s2) {
33002 return s2.accessed - s1.accessed;
33004 .slice(this._configuration.maxSequences);
33005 for (var _d = 0, uncacheSequences_1 = uncacheSequences; _d < uncacheSequences_1.length; _d++) {
33006 var sequenceAccess = uncacheSequences_1[_d];
33007 var sequenceKey = sequenceAccess.sequence.key;
33008 delete this._sequences[sequenceKey];
33009 sequenceAccess.sequence.dispose();
33012 Graph.prototype._addNewKeys = function (keys, dict) {
33013 for (var key in dict) {
33014 if (!dict.hasOwnProperty(key) || !this.hasNode(key)) {
33017 if (!(key in keys)) {
33022 Graph.prototype._cacheSequence$ = function (sequenceKey) {
33024 if (sequenceKey in this._cachingSequences$) {
33025 return this._cachingSequences$[sequenceKey];
33027 this._cachingSequences$[sequenceKey] = this._apiV3.sequenceByKey$([sequenceKey])
33028 .do(function (sequenceByKey) {
33029 if (!(sequenceKey in _this._sequences)) {
33030 _this._sequences[sequenceKey] = {
33031 accessed: new Date().getTime(),
33032 sequence: new Graph_1.Sequence(sequenceByKey[sequenceKey]),
33035 delete _this._cachingSequences$[sequenceKey];
33037 .map(function (sequenceByKey) {
33040 .finally(function () {
33041 if (sequenceKey in _this._cachingSequences$) {
33042 delete _this._cachingSequences$[sequenceKey];
33044 _this._changed$.next(_this);
33048 return this._cachingSequences$[sequenceKey];
33050 Graph.prototype._makeFull = function (node, fillNode) {
33051 if (fillNode.calt == null) {
33052 fillNode.calt = this._defaultAlt;
33054 if (fillNode.c_rotation == null) {
33055 fillNode.c_rotation = this._graphCalculator.rotationFromCompass(fillNode.ca, fillNode.orientation);
33057 node.makeFull(fillNode);
33059 Graph.prototype._preStore = function (h, node) {
33060 if (!(h in this._preStored)) {
33061 this._preStored[h] = {};
33063 this._preStored[h][node.key] = node;
33065 Graph.prototype._removeFromPreStore = function (h) {
33066 var preStored = null;
33067 if (h in this._preStored) {
33068 preStored = this._preStored[h];
33069 delete this._preStored[h];
33073 Graph.prototype._setNode = function (node) {
33074 var key = node.key;
33075 if (this.hasNode(key)) {
33076 throw new Error_1.GraphMapillaryError("Node already exist (" + key + ").");
33078 this._nodes[key] = node;
33080 Graph.prototype._uncacheTile = function (h) {
33081 for (var _i = 0, _a = this._cachedTiles[h].nodes; _i < _a.length; _i++) {
33083 var key = node.key;
33084 delete this._nodes[key];
33085 delete this._nodeToTile[key];
33086 if (key in this._cachedNodes) {
33087 delete this._cachedNodes[key];
33089 if (key in this._cachedNodeTiles) {
33090 delete this._cachedNodeTiles[key];
33092 if (key in this._cachedSpatialEdges) {
33093 delete this._cachedSpatialEdges[key];
33097 for (var _b = 0, _c = this._nodeIndexTiles[h]; _b < _c.length; _b++) {
33098 var nodeIndexItem = _c[_b];
33099 this._nodeIndex.remove(nodeIndexItem);
33101 delete this._nodeIndexTiles[h];
33102 delete this._cachedTiles[h];
33104 Graph.prototype._updateCachedTileAccess = function (key, accessed) {
33105 if (key in this._nodeToTile) {
33106 this._cachedTiles[this._nodeToTile[key]].accessed = accessed;
33109 Graph.prototype._updateCachedNodeAccess = function (key, accessed) {
33110 if (key in this._cachedNodes) {
33111 this._cachedNodes[key].accessed = accessed;
33116 exports.Graph = Graph;
33117 exports.default = Graph;
33119 },{"../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}],313:[function(require,module,exports){
33121 /// <reference path="../../typings/index.d.ts" />
33122 Object.defineProperty(exports, "__esModule", { value: true });
33123 var geohash = require("latlon-geohash");
33124 var THREE = require("three");
33125 var Geo_1 = require("../Geo");
33126 var GeoHashDirections = (function () {
33127 function GeoHashDirections() {
33129 GeoHashDirections.n = "n";
33130 GeoHashDirections.nw = "nw";
33131 GeoHashDirections.w = "w";
33132 GeoHashDirections.sw = "sw";
33133 GeoHashDirections.s = "s";
33134 GeoHashDirections.se = "se";
33135 GeoHashDirections.e = "e";
33136 GeoHashDirections.ne = "ne";
33137 return GeoHashDirections;
33140 * @class GraphCalculator
33142 * @classdesc Represents a calculator for graph entities.
33144 var GraphCalculator = (function () {
33146 * Create a new graph calculator instance.
33148 * @param {GeoCoords} geoCoords - Geo coords instance.
33150 function GraphCalculator(geoCoords) {
33151 this._geoCoords = geoCoords != null ? geoCoords : new Geo_1.GeoCoords();
33154 * Encode the geohash tile for geodetic coordinates.
33156 * @param {ILatLon} latlon - Latitude and longitude to encode.
33157 * @param {number} precision - Precision of the encoding.
33159 * @returns {string} The geohash tile for the lat, lon and precision.
33161 GraphCalculator.prototype.encodeH = function (latLon, precision) {
33162 if (precision === void 0) { precision = 7; }
33163 return geohash.encode(latLon.lat, latLon.lon, precision);
33166 * Encode the geohash tiles within a threshold from a position
33167 * using Manhattan distance.
33169 * @param {ILatLon} latlon - Latitude and longitude to encode.
33170 * @param {number} precision - Precision of the encoding.
33171 * @param {number} threshold - Threshold of the encoding in meters.
33173 * @returns {string} The geohash tiles reachable within the threshold.
33175 GraphCalculator.prototype.encodeHs = function (latLon, precision, threshold) {
33176 if (precision === void 0) { precision = 7; }
33177 if (threshold === void 0) { threshold = 20; }
33178 var h = geohash.encode(latLon.lat, latLon.lon, precision);
33179 var bounds = geohash.bounds(h);
33180 var ne = bounds.ne;
33181 var sw = bounds.sw;
33182 var neighbours = geohash.neighbours(h);
33183 var bl = [0, 0, 0];
33184 var tr = this._geoCoords.geodeticToEnu(ne.lat, ne.lon, 0, sw.lat, sw.lon, 0);
33185 var position = this._geoCoords.geodeticToEnu(latLon.lat, latLon.lon, 0, sw.lat, sw.lon, 0);
33186 var left = position[0] - bl[0];
33187 var right = tr[0] - position[0];
33188 var bottom = position[1] - bl[1];
33189 var top = tr[1] - position[1];
33190 var l = left < threshold;
33191 var r = right < threshold;
33192 var b = bottom < threshold;
33193 var t = top < threshold;
33196 hs.push(neighbours[GeoHashDirections.n]);
33199 hs.push(neighbours[GeoHashDirections.nw]);
33202 hs.push(neighbours[GeoHashDirections.w]);
33205 hs.push(neighbours[GeoHashDirections.sw]);
33208 hs.push(neighbours[GeoHashDirections.s]);
33211 hs.push(neighbours[GeoHashDirections.se]);
33214 hs.push(neighbours[GeoHashDirections.e]);
33217 hs.push(neighbours[GeoHashDirections.ne]);
33222 * Get the bounding box corners for a circle with radius of a threshold
33223 * with center in a geodetic position.
33225 * @param {ILatLon} latlon - Latitude and longitude to encode.
33226 * @param {number} threshold - Threshold distance from the position in meters.
33228 * @returns {Array<ILatLon>} The south west and north east corners of the
33231 GraphCalculator.prototype.boundingBoxCorners = function (latLon, threshold) {
33232 var bl = this._geoCoords.enuToGeodetic(-threshold, -threshold, 0, latLon.lat, latLon.lon, 0);
33233 var tr = this._geoCoords.enuToGeodetic(threshold, threshold, 0, latLon.lat, latLon.lon, 0);
33235 { lat: bl[0], lon: bl[1] },
33236 { lat: tr[0], lon: tr[1] },
33240 * Convert a compass angle to an angle axis rotation vector.
33242 * @param {number} compassAngle - The compass angle in degrees.
33243 * @param {number} orientation - The orientation of the original image.
33245 * @returns {Array<number>} Angle axis rotation vector.
33247 GraphCalculator.prototype.rotationFromCompass = function (compassAngle, orientation) {
33251 switch (orientation) {
33270 var rz = new THREE.Matrix4().makeRotationZ(z);
33271 var euler = new THREE.Euler(x, y, compassAngle * Math.PI / 180, "XYZ");
33272 var re = new THREE.Matrix4().makeRotationFromEuler(euler);
33273 var rotation = new THREE.Vector4().setAxisAngleFromRotationMatrix(re.multiply(rz));
33274 return rotation.multiplyScalar(rotation.w).toArray().slice(0, 3);
33276 return GraphCalculator;
33278 exports.GraphCalculator = GraphCalculator;
33279 exports.default = GraphCalculator;
33281 },{"../Geo":229,"latlon-geohash":21,"three":176}],314:[function(require,module,exports){
33283 Object.defineProperty(exports, "__esModule", { value: true });
33284 var Observable_1 = require("rxjs/Observable");
33285 var Subject_1 = require("rxjs/Subject");
33286 require("rxjs/add/operator/catch");
33287 require("rxjs/add/operator/concat");
33288 require("rxjs/add/operator/do");
33289 require("rxjs/add/operator/expand");
33290 require("rxjs/add/operator/finally");
33291 require("rxjs/add/operator/first");
33292 require("rxjs/add/operator/last");
33293 require("rxjs/add/operator/map");
33294 require("rxjs/add/operator/mergeMap");
33295 require("rxjs/add/operator/publishReplay");
33297 * @class GraphService
33299 * @classdesc Represents a service for graph operations.
33301 var GraphService = (function () {
33303 * Create a new graph service instance.
33305 * @param {Graph} graph - Graph instance to be operated on.
33307 function GraphService(graph, imageLoadingService) {
33308 this._graph$ = Observable_1.Observable
33310 .concat(graph.changed$)
33313 this._graph$.subscribe(function () { });
33314 this._imageLoadingService = imageLoadingService;
33315 this._firstGraphSubjects$ = [];
33316 this._initializeCacheSubscriptions = [];
33317 this._sequenceSubscriptions = [];
33318 this._spatialSubscriptions = [];
33321 * Cache a node in the graph and retrieve it.
33323 * @description When called, the full properties of
33324 * the node are retrieved and the node cache is initialized.
33325 * After that the node assets are cached and the node
33326 * is emitted to the observable when.
33327 * In parallel to caching the node assets, the sequence and
33328 * spatial edges of the node are cached. For this, the sequence
33329 * of the node and the required tiles and spatial nodes are
33330 * retrieved. The sequence and spatial edges may be set before
33331 * or after the node is returned.
33333 * @param {string} key - Key of the node to cache.
33334 * @return {Observable<Node>} Observable emitting a single item,
33335 * the node, when it has been retrieved and its assets are cached.
33336 * @throws {Error} Propagates any IO node caching errors to the caller.
33338 GraphService.prototype.cacheNode$ = function (key) {
33340 var firstGraphSubject$ = new Subject_1.Subject();
33341 this._firstGraphSubjects$.push(firstGraphSubject$);
33342 var firstGraph$ = firstGraphSubject$
33345 var node$ = firstGraph$
33346 .map(function (graph) {
33347 return graph.getNode(key);
33349 .mergeMap(function (node) {
33350 return node.assetsCached ?
33351 Observable_1.Observable.of(node) :
33352 node.cacheAssets$();
33356 node$.subscribe(function (node) {
33357 _this._imageLoadingService.loadnode$.next(node);
33358 }, function (error) {
33359 console.error("Failed to cache node (" + key + ")", error);
33361 var initializeCacheSubscription = this._graph$
33363 .mergeMap(function (graph) {
33364 if (graph.isCachingFull(key) || !graph.hasNode(key)) {
33365 return graph.cacheFull$(key);
33367 if (graph.isCachingFill(key) || !graph.getNode(key).full) {
33368 return graph.cacheFill$(key);
33370 return Observable_1.Observable.of(graph);
33372 .do(function (graph) {
33373 if (!graph.hasInitializedCache(key)) {
33374 graph.initializeCache(key);
33377 .finally(function () {
33378 if (initializeCacheSubscription == null) {
33381 _this._removeFromArray(initializeCacheSubscription, _this._initializeCacheSubscriptions);
33382 _this._removeFromArray(firstGraphSubject$, _this._firstGraphSubjects$);
33384 .subscribe(function (graph) {
33385 firstGraphSubject$.next(graph);
33386 firstGraphSubject$.complete();
33387 }, function (error) {
33388 firstGraphSubject$.error(error);
33390 if (!initializeCacheSubscription.closed) {
33391 this._initializeCacheSubscriptions.push(initializeCacheSubscription);
33393 var sequenceSubscription = firstGraph$
33394 .mergeMap(function (graph) {
33395 if (graph.isCachingNodeSequence(key) || !graph.hasNodeSequence(key)) {
33396 return graph.cacheNodeSequence$(key);
33398 return Observable_1.Observable.of(graph);
33400 .do(function (graph) {
33401 if (!graph.getNode(key).sequenceEdges.cached) {
33402 graph.cacheSequenceEdges(key);
33405 .finally(function () {
33406 if (sequenceSubscription == null) {
33409 _this._removeFromArray(sequenceSubscription, _this._sequenceSubscriptions);
33411 .subscribe(function (graph) { return; }, function (error) {
33412 console.error("Failed to cache sequence edges (" + key + ").", error);
33414 if (!sequenceSubscription.closed) {
33415 this._sequenceSubscriptions.push(sequenceSubscription);
33417 var spatialSubscription = firstGraph$
33418 .expand(function (graph) {
33419 if (graph.hasTiles(key)) {
33420 return Observable_1.Observable.empty();
33422 return Observable_1.Observable
33423 .from(graph.cacheTiles$(key))
33424 .mergeMap(function (graph$) {
33426 .mergeMap(function (g) {
33427 if (g.isCachingTiles(key)) {
33428 return Observable_1.Observable.empty();
33430 return Observable_1.Observable.of(g);
33432 .catch(function (error, caught$) {
33433 console.error("Failed to cache tile data (" + key + ").", error);
33434 return Observable_1.Observable.empty();
33439 .mergeMap(function (graph) {
33440 if (graph.hasSpatialArea(key)) {
33441 return Observable_1.Observable.of(graph);
33443 return Observable_1.Observable
33444 .from(graph.cacheSpatialArea$(key))
33445 .mergeMap(function (graph$) {
33447 .catch(function (error, caught$) {
33448 console.error("Failed to cache spatial nodes (" + key + ").", error);
33449 return Observable_1.Observable.empty();
33454 .mergeMap(function (graph) {
33455 return graph.hasNodeSequence(key) ?
33456 Observable_1.Observable.of(graph) :
33457 graph.cacheNodeSequence$(key);
33459 .do(function (graph) {
33460 if (!graph.getNode(key).spatialEdges.cached) {
33461 graph.cacheSpatialEdges(key);
33464 .finally(function () {
33465 if (spatialSubscription == null) {
33468 _this._removeFromArray(spatialSubscription, _this._spatialSubscriptions);
33470 .subscribe(function (graph) { return; }, function (error) {
33471 console.error("Failed to cache spatial edges (" + key + ").", error);
33473 if (!spatialSubscription.closed) {
33474 this._spatialSubscriptions.push(spatialSubscription);
33477 .first(function (node) {
33478 return node.assetsCached;
33482 * Cache a sequence in the graph and retrieve it.
33484 * @param {string} sequenceKey - Sequence key.
33485 * @returns {Observable<Sequence>} Observable emitting a single item,
33486 * the sequence, when it has been retrieved and its assets are cached.
33487 * @throws {Error} Propagates any IO node caching errors to the caller.
33489 GraphService.prototype.cacheSequence$ = function (sequenceKey) {
33490 return this._graph$
33492 .mergeMap(function (graph) {
33493 if (graph.isCachingSequence(sequenceKey) || !graph.hasSequence(sequenceKey)) {
33494 return graph.cacheSequence$(sequenceKey);
33496 return Observable_1.Observable.of(graph);
33498 .map(function (graph) {
33499 return graph.getSequence(sequenceKey);
33503 * Set a spatial edge filter on the graph.
33505 * @description Resets the spatial edges of all cached nodes.
33507 * @param {FilterExpression} filter - Filter expression to be applied.
33508 * @return {Observable<Graph>} Observable emitting a single item,
33509 * the graph, when the spatial edges have been reset.
33511 GraphService.prototype.setFilter$ = function (filter) {
33512 this._resetSubscriptions(this._spatialSubscriptions);
33513 return this._graph$
33515 .do(function (graph) {
33516 graph.resetSpatialEdges();
33517 graph.setFilter(filter);
33523 * @description Resets the graph but keeps the nodes of the
33526 * @param {Array<string>} keepKeys - Keys of nodes to keep in graph.
33527 * @return {Observable<Node>} Observable emitting a single item,
33528 * the graph, when it has been reset.
33530 GraphService.prototype.reset$ = function (keepKeys) {
33531 this._abortSubjects(this._firstGraphSubjects$);
33532 this._resetSubscriptions(this._initializeCacheSubscriptions);
33533 this._resetSubscriptions(this._sequenceSubscriptions);
33534 this._resetSubscriptions(this._spatialSubscriptions);
33535 return this._graph$
33537 .do(function (graph) {
33538 graph.reset(keepKeys);
33542 * Uncache the graph.
33544 * @description Uncaches the graph by removing tiles, nodes and
33545 * sequences. Keeps the nodes of the supplied keys and the tiles
33546 * related to those nodes.
33548 * @param {Array<string>} keepKeys - Keys of nodes to keep in graph.
33549 * @return {Observable<Graph>} Observable emitting a single item,
33550 * the graph, when the graph has been uncached.
33552 GraphService.prototype.uncache$ = function (keepKeys) {
33553 return this._graph$
33555 .do(function (graph) {
33556 graph.uncache(keepKeys);
33559 GraphService.prototype._abortSubjects = function (subjects) {
33560 for (var _i = 0, _a = subjects.slice(); _i < _a.length; _i++) {
33561 var subject = _a[_i];
33562 this._removeFromArray(subject, subjects);
33563 subject.error(new Error("Cache node request was aborted."));
33566 GraphService.prototype._removeFromArray = function (object, objects) {
33567 var index = objects.indexOf(object);
33568 if (index !== -1) {
33569 objects.splice(index, 1);
33572 GraphService.prototype._resetSubscriptions = function (subscriptions) {
33573 for (var _i = 0, _a = subscriptions.slice(); _i < _a.length; _i++) {
33574 var subscription = _a[_i];
33575 this._removeFromArray(subscription, subscriptions);
33576 if (!subscription.closed) {
33577 subscription.unsubscribe();
33581 return GraphService;
33583 exports.GraphService = GraphService;
33584 exports.default = GraphService;
33586 },{"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}],315:[function(require,module,exports){
33588 /// <reference path="../../typings/index.d.ts" />
33589 Object.defineProperty(exports, "__esModule", { value: true });
33590 var Subject_1 = require("rxjs/Subject");
33591 var ImageLoadingService = (function () {
33592 function ImageLoadingService() {
33593 this._loadnode$ = new Subject_1.Subject();
33594 this._loadstatus$ = this._loadnode$
33595 .scan(function (nodes, node) {
33596 nodes[node.key] = node.loadStatus;
33601 this._loadstatus$.subscribe(function () { });
33603 Object.defineProperty(ImageLoadingService.prototype, "loadnode$", {
33605 return this._loadnode$;
33610 Object.defineProperty(ImageLoadingService.prototype, "loadstatus$", {
33612 return this._loadstatus$;
33617 return ImageLoadingService;
33619 exports.ImageLoadingService = ImageLoadingService;
33621 },{"rxjs/Subject":34}],316:[function(require,module,exports){
33623 /// <reference path="../../typings/index.d.ts" />
33624 Object.defineProperty(exports, "__esModule", { value: true });
33625 var Pbf = require("pbf");
33626 var MeshReader = (function () {
33627 function MeshReader() {
33629 MeshReader.read = function (buffer) {
33630 var pbf = new Pbf(buffer);
33631 return pbf.readFields(MeshReader._readMeshField, { faces: [], vertices: [] });
33633 MeshReader._readMeshField = function (tag, mesh, pbf) {
33635 mesh.vertices.push(pbf.readFloat());
33637 else if (tag === 2) {
33638 mesh.faces.push(pbf.readVarint());
33643 exports.MeshReader = MeshReader;
33645 },{"pbf":23}],317:[function(require,module,exports){
33647 Object.defineProperty(exports, "__esModule", { value: true });
33648 require("rxjs/add/observable/combineLatest");
33649 require("rxjs/add/operator/map");
33653 * @classdesc Represents a node in the navigation graph.
33655 * Explanation of position and bearing properties:
33657 * When images are uploaded they will have GPS information in the EXIF, this is what
33658 * is called `originalLatLon`(@link Node#originalLatLon).
33660 * When Structure from Motions has been run for a node a `computedLatLon` that
33661 * differs from the `originalLatLon` will be created. It is different because
33662 * GPS positions are not very exact and SfM aligns the camera positions according
33663 * to the 3D reconstruction (@link Node#computedLatLon).
33665 * At last there exist a `latLon` property which evaluates to
33666 * the `computedLatLon` from SfM if it exists but falls back
33667 * to the `originalLatLon` from the EXIF GPS otherwise (@link Node#latlon).
33669 * Everything that is done in in the Viewer is based on the SfM positions,
33670 * i.e. `computedLatLon`. That is why the smooth transitions go in the right
33671 * direction (nd not in strange directions because of bad GPS).
33673 * E.g. when placing a marker in the Viewer it is relative to the SfM
33674 * position i.e. the `computedLatLon`.
33676 * The same concept as above also applies to the compass angle (or bearing) properties
33677 * `originalCa`, `computedCa` and `ca`.
33679 var Node = (function () {
33681 * Create a new node instance.
33683 * @description Nodes are always created internally by the library.
33684 * Nodes can not be added to the library through any API method.
33686 * @param {ICoreNode} coreNode - Raw core node data.
33688 function Node(core) {
33689 this._cache = null;
33693 Object.defineProperty(Node.prototype, "assetsCached", {
33695 * Get assets cached.
33697 * @description The assets that need to be cached for this property
33698 * to report true are the following: fill properties, image and mesh.
33699 * The library ensures that the current node will always have the
33702 * @returns {boolean} Value indicating whether all assets have been
33706 return this._core != null &&
33707 this._fill != null &&
33708 this._cache != null &&
33709 this._cache.image != null &&
33710 this._cache.mesh != null;
33715 Object.defineProperty(Node.prototype, "alt", {
33719 * @description If SfM has not been run the computed altitude is
33720 * set to a default value of two meters.
33722 * @returns {number} Altitude, in meters.
33725 return this._fill.calt;
33730 Object.defineProperty(Node.prototype, "ca", {
33734 * @description If the SfM computed compass angle exists it will
33735 * be returned, otherwise the original EXIF compass angle.
33737 * @returns {number} Compass angle, measured in degrees.
33740 return this._fill.cca != null ? this._fill.cca : this._fill.ca;
33745 Object.defineProperty(Node.prototype, "capturedAt", {
33749 * @returns {number} Timestamp when the image was captured.
33752 return this._fill.captured_at;
33757 Object.defineProperty(Node.prototype, "computedCA", {
33761 * @description Will not be set if SfM has not been run.
33763 * @returns {number} SfM computed compass angle, measured in degrees.
33766 return this._fill.cca;
33771 Object.defineProperty(Node.prototype, "computedLatLon", {
33773 * Get computedLatLon.
33775 * @description Will not be set if SfM has not been run.
33777 * @returns {ILatLon} SfM computed latitude longitude in WGS84 datum,
33778 * measured in degrees.
33781 return this._core.cl;
33786 Object.defineProperty(Node.prototype, "focal", {
33790 * @description Will not be set if SfM has not been run.
33792 * @returns {number} SfM computed focal length.
33795 return this._fill.cfocal;
33800 Object.defineProperty(Node.prototype, "full", {
33804 * @description The library ensures that the current node will
33807 * @returns {boolean} Value indicating whether the node has all
33808 * properties filled.
33811 return this._fill != null;
33816 Object.defineProperty(Node.prototype, "fullPano", {
33820 * @returns {boolean} Value indicating whether the node is a complete
33824 return this._fill.gpano != null &&
33825 this._fill.gpano.CroppedAreaLeftPixels === 0 &&
33826 this._fill.gpano.CroppedAreaTopPixels === 0 &&
33827 this._fill.gpano.CroppedAreaImageWidthPixels === this._fill.gpano.FullPanoWidthPixels &&
33828 this._fill.gpano.CroppedAreaImageHeightPixels === this._fill.gpano.FullPanoHeightPixels;
33833 Object.defineProperty(Node.prototype, "gpano", {
33837 * @description Will not be set for non panoramic images.
33839 * @returns {IGPano} Panorama information for panorama images.
33842 return this._fill.gpano;
33847 Object.defineProperty(Node.prototype, "height", {
33851 * @returns {number} Height of original image, not adjusted
33855 return this._fill.height;
33860 Object.defineProperty(Node.prototype, "image", {
33864 * @description The image will always be set on the current node.
33866 * @returns {HTMLImageElement} Cached image element of the node.
33869 return this._cache.image;
33874 Object.defineProperty(Node.prototype, "key", {
33878 * @returns {string} Unique key of the node.
33881 return this._core.key;
33886 Object.defineProperty(Node.prototype, "latLon", {
33890 * @description If the SfM computed latitude longitude exist
33891 * it will be returned, otherwise the original EXIF latitude
33894 * @returns {ILatLon} Latitude longitude in WGS84 datum,
33895 * measured in degrees.
33898 return this._core.cl != null ? this._core.cl : this._core.l;
33903 Object.defineProperty(Node.prototype, "loadStatus", {
33907 * @returns {ILoadStatus} Value indicating the load status
33908 * of the mesh and image.
33911 return this._cache.loadStatus;
33916 Object.defineProperty(Node.prototype, "merged", {
33920 * @returns {boolean} Value indicating whether SfM has been
33921 * run on the node and the node has been merged into a
33922 * connected component.
33925 return this._fill != null &&
33926 this._fill.merge_version != null &&
33927 this._fill.merge_version > 0;
33932 Object.defineProperty(Node.prototype, "mergeCC", {
33936 * @description Will not be set if SfM has not yet been run on
33939 * @returns {number} SfM connected component key to which
33943 return this._fill.merge_cc;
33948 Object.defineProperty(Node.prototype, "mergeVersion", {
33950 * Get mergeVersion.
33952 * @returns {number} Version for which SfM was run and image was merged.
33955 return this._fill.merge_version;
33960 Object.defineProperty(Node.prototype, "mesh", {
33964 * @description The mesh will always be set on the current node.
33966 * @returns {IMesh} SfM triangulated mesh of reconstructed
33967 * atomic 3D points.
33970 return this._cache.mesh;
33975 Object.defineProperty(Node.prototype, "orientation", {
33979 * @returns {number} EXIF orientation of original image.
33982 return this._fill.orientation;
33987 Object.defineProperty(Node.prototype, "originalCA", {
33991 * @returns {number} Original EXIF compass angle, measured in
33995 return this._fill.ca;
34000 Object.defineProperty(Node.prototype, "originalLatLon", {
34002 * Get originalLatLon.
34004 * @returns {ILatLon} Original EXIF latitude longitude in
34005 * WGS84 datum, measured in degrees.
34008 return this._core.l;
34013 Object.defineProperty(Node.prototype, "pano", {
34017 * @returns {boolean} Value indicating whether the node is a panorama.
34018 * It could be a cropped or full panorama.
34021 return this._fill.gpano != null &&
34022 this._fill.gpano.FullPanoWidthPixels != null;
34027 Object.defineProperty(Node.prototype, "projectKey", {
34031 * @returns {string} Unique key of the project to which
34032 * the node belongs.
34035 return this._fill.project != null ?
34036 this._fill.project.key :
34042 Object.defineProperty(Node.prototype, "rotation", {
34046 * @description Will not be set if SfM has not been run.
34048 * @returns {Array<number>} Rotation vector in angle axis representation.
34051 return this._fill.c_rotation;
34056 Object.defineProperty(Node.prototype, "scale", {
34060 * @description Will not be set if SfM has not been run.
34062 * @returns {number} Scale of atomic reconstruction.
34065 return this._fill.atomic_scale;
34070 Object.defineProperty(Node.prototype, "sequenceKey", {
34074 * @returns {string} Unique key of the sequence to which
34075 * the node belongs.
34078 return this._core.sequence.key;
34083 Object.defineProperty(Node.prototype, "sequenceEdges", {
34085 * Get sequenceEdges.
34087 * @returns {IEdgeStatus} Value describing the status of the
34091 return this._cache.sequenceEdges;
34096 Object.defineProperty(Node.prototype, "sequenceEdges$", {
34098 * Get sequenceEdges$.
34100 * @returns {Observable<IEdgeStatus>} Observable emitting
34101 * values describing the status of the sequence edges.
34104 return this._cache.sequenceEdges$;
34109 Object.defineProperty(Node.prototype, "spatialEdges", {
34111 * Get spatialEdges.
34113 * @returns {IEdgeStatus} Value describing the status of the
34117 return this._cache.spatialEdges;
34122 Object.defineProperty(Node.prototype, "spatialEdges$", {
34124 * Get spatialEdges$.
34126 * @returns {Observable<IEdgeStatus>} Observable emitting
34127 * values describing the status of the spatial edges.
34130 return this._cache.spatialEdges$;
34135 Object.defineProperty(Node.prototype, "userKey", {
34139 * @returns {string} Unique key of the user who uploaded
34143 return this._fill.user.key;
34148 Object.defineProperty(Node.prototype, "username", {
34152 * @returns {string} Username of the user who uploaded
34156 return this._fill.user.username;
34161 Object.defineProperty(Node.prototype, "width", {
34165 * @returns {number} Width of original image, not
34166 * adjusted for orientation.
34169 return this._fill.width;
34175 * Cache the image and mesh assets.
34177 * @description The assets are always cached internally by the
34178 * library prior to setting a node as the current node.
34180 * @returns {Observable<Node>} Observable emitting this node whenever the
34181 * load status has changed and when the mesh or image has been fully loaded.
34183 Node.prototype.cacheAssets$ = function () {
34185 return this._cache.cacheAssets$(this.key, this.pano, this.merged)
34186 .map(function (cache) {
34190 Node.prototype.cacheImage$ = function (imageSize) {
34192 return this._cache.cacheImage$(this.key, imageSize)
34193 .map(function (cache) {
34198 * Cache the sequence edges.
34200 * @description The sequence edges are cached asynchronously
34201 * internally by the library.
34203 * @param {Array<IEdge>} edges - Sequence edges to cache.
34205 Node.prototype.cacheSequenceEdges = function (edges) {
34206 this._cache.cacheSequenceEdges(edges);
34209 * Cache the spatial edges.
34211 * @description The spatial edges are cached asynchronously
34212 * internally by the library.
34214 * @param {Array<IEdge>} edges - Spatial edges to cache.
34216 Node.prototype.cacheSpatialEdges = function (edges) {
34217 this._cache.cacheSpatialEdges(edges);
34220 * Dispose the node.
34222 * @description Disposes all cached assets.
34224 Node.prototype.dispose = function () {
34225 if (this._cache != null) {
34226 this._cache.dispose();
34227 this._cache = null;
34233 * Initialize the node cache.
34235 * @description The node cache is initialized internally by
34238 * @param {NodeCache} cache - The node cache to set as cache.
34240 Node.prototype.initializeCache = function (cache) {
34241 if (this._cache != null) {
34242 throw new Error("Node cache already initialized (" + this.key + ").");
34244 this._cache = cache;
34247 * Fill the node with all properties.
34249 * @description The node is filled internally by
34252 * @param {IFillNode} fill - The fill node struct.
34254 Node.prototype.makeFull = function (fill) {
34255 if (fill == null) {
34256 throw new Error("Fill can not be null.");
34261 * Reset the sequence edges.
34263 Node.prototype.resetSequenceEdges = function () {
34264 this._cache.resetSequenceEdges();
34267 * Reset the spatial edges.
34269 Node.prototype.resetSpatialEdges = function () {
34270 this._cache.resetSpatialEdges();
34273 * Clears the image and mesh assets, aborts
34274 * any outstanding requests and resets edges.
34276 Node.prototype.uncache = function () {
34277 if (this._cache == null) {
34280 this._cache.dispose();
34281 this._cache = null;
34285 exports.Node = Node;
34286 exports.default = Node;
34288 },{"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/map":65}],318:[function(require,module,exports){
34289 (function (Buffer){
34291 Object.defineProperty(exports, "__esModule", { value: true });
34292 var Subject_1 = require("rxjs/Subject");
34293 var Observable_1 = require("rxjs/Observable");
34294 require("rxjs/add/observable/combineLatest");
34295 require("rxjs/add/operator/publishReplay");
34296 var Graph_1 = require("../Graph");
34297 var Utils_1 = require("../Utils");
34301 * @classdesc Represents the cached properties of a node.
34303 var NodeCache = (function () {
34305 * Create a new node cache instance.
34307 function NodeCache() {
34308 this._disposed = false;
34309 this._image = null;
34310 this._loadStatus = { loaded: 0, total: 0 };
34312 this._sequenceEdges = { cached: false, edges: [] };
34313 this._spatialEdges = { cached: false, edges: [] };
34314 this._sequenceEdgesChanged$ = new Subject_1.Subject();
34315 this._sequenceEdges$ = this._sequenceEdgesChanged$
34316 .startWith(this._sequenceEdges)
34319 this._sequenceEdgesSubscription = this._sequenceEdges$.subscribe(function () { });
34320 this._spatialEdgesChanged$ = new Subject_1.Subject();
34321 this._spatialEdges$ = this._spatialEdgesChanged$
34322 .startWith(this._spatialEdges)
34325 this._spatialEdgesSubscription = this._spatialEdges$.subscribe(function () { });
34326 this._cachingAssets$ = null;
34328 Object.defineProperty(NodeCache.prototype, "image", {
34332 * @description Will not be set when assets have not been cached
34333 * or when the object has been disposed.
34335 * @returns {HTMLImageElement} Cached image element of the node.
34338 return this._image;
34343 Object.defineProperty(NodeCache.prototype, "loadStatus", {
34347 * @returns {ILoadStatus} Value indicating the load status
34348 * of the mesh and image.
34351 return this._loadStatus;
34356 Object.defineProperty(NodeCache.prototype, "mesh", {
34360 * @description Will not be set when assets have not been cached
34361 * or when the object has been disposed.
34363 * @returns {IMesh} SfM triangulated mesh of reconstructed
34364 * atomic 3D points.
34372 Object.defineProperty(NodeCache.prototype, "sequenceEdges", {
34374 * Get sequenceEdges.
34376 * @returns {IEdgeStatus} Value describing the status of the
34380 return this._sequenceEdges;
34385 Object.defineProperty(NodeCache.prototype, "sequenceEdges$", {
34387 * Get sequenceEdges$.
34389 * @returns {Observable<IEdgeStatus>} Observable emitting
34390 * values describing the status of the sequence edges.
34393 return this._sequenceEdges$;
34398 Object.defineProperty(NodeCache.prototype, "spatialEdges", {
34400 * Get spatialEdges.
34402 * @returns {IEdgeStatus} Value describing the status of the
34406 return this._spatialEdges;
34411 Object.defineProperty(NodeCache.prototype, "spatialEdges$", {
34413 * Get spatialEdges$.
34415 * @returns {Observable<IEdgeStatus>} Observable emitting
34416 * values describing the status of the spatial edges.
34419 return this._spatialEdges$;
34425 * Cache the image and mesh assets.
34427 * @param {string} key - Key of the node to cache.
34428 * @param {boolean} pano - Value indicating whether node is a panorama.
34429 * @param {boolean} merged - Value indicating whether node is merged.
34430 * @returns {Observable<NodeCache>} Observable emitting this node
34431 * cache whenever the load status has changed and when the mesh or image
34432 * has been fully loaded.
34434 NodeCache.prototype.cacheAssets$ = function (key, pano, merged) {
34436 if (this._cachingAssets$ != null) {
34437 return this._cachingAssets$;
34439 var imageSize = pano ?
34440 Utils_1.Settings.basePanoramaSize :
34441 Utils_1.Settings.baseImageSize;
34442 this._cachingAssets$ = Observable_1.Observable
34443 .combineLatest(this._cacheImage$(key, imageSize), this._cacheMesh$(key, merged), function (imageStatus, meshStatus) {
34444 _this._loadStatus.loaded = 0;
34445 _this._loadStatus.total = 0;
34447 _this._mesh = meshStatus.object;
34448 _this._loadStatus.loaded += meshStatus.loaded.loaded;
34449 _this._loadStatus.total += meshStatus.loaded.total;
34452 _this._image = imageStatus.object;
34453 _this._loadStatus.loaded += imageStatus.loaded.loaded;
34454 _this._loadStatus.total += imageStatus.loaded.total;
34458 .finally(function () {
34459 _this._cachingAssets$ = null;
34463 return this._cachingAssets$;
34466 * Cache an image with a higher resolution than the current one.
34468 * @param {string} key - Key of the node to cache.
34469 * @param {ImageSize} imageSize - The size to cache.
34470 * @returns {Observable<NodeCache>} Observable emitting a single item,
34471 * the node cache, when the image has been cached. If supplied image
34472 * size is not larger than the current image size the node cache is
34473 * returned immediately.
34475 NodeCache.prototype.cacheImage$ = function (key, imageSize) {
34477 if (this._image != null && imageSize <= Math.max(this._image.width, this._image.height)) {
34478 return Observable_1.Observable.of(this);
34480 return this._cacheImage$(key, imageSize)
34481 .first(function (status) {
34482 return status.object != null;
34484 .do(function (status) {
34485 _this._disposeImage();
34486 _this._image = status.object;
34488 .map(function (imageStatus) {
34493 * Cache the sequence edges.
34495 * @param {Array<IEdge>} edges - Sequence edges to cache.
34497 NodeCache.prototype.cacheSequenceEdges = function (edges) {
34498 this._sequenceEdges = { cached: true, edges: edges };
34499 this._sequenceEdgesChanged$.next(this._sequenceEdges);
34502 * Cache the spatial edges.
34504 * @param {Array<IEdge>} edges - Spatial edges to cache.
34506 NodeCache.prototype.cacheSpatialEdges = function (edges) {
34507 this._spatialEdges = { cached: true, edges: edges };
34508 this._spatialEdgesChanged$.next(this._spatialEdges);
34511 * Dispose the node cache.
34513 * @description Disposes all cached assets and unsubscribes to
34516 NodeCache.prototype.dispose = function () {
34517 this._sequenceEdgesSubscription.unsubscribe();
34518 this._spatialEdgesSubscription.unsubscribe();
34519 this._disposeImage();
34521 this._loadStatus.loaded = 0;
34522 this._loadStatus.total = 0;
34523 this._sequenceEdges = { cached: false, edges: [] };
34524 this._spatialEdges = { cached: false, edges: [] };
34525 this._sequenceEdgesChanged$.next(this._sequenceEdges);
34526 this._spatialEdgesChanged$.next(this._spatialEdges);
34527 this._disposed = true;
34528 if (this._imageRequest != null) {
34529 this._imageRequest.abort();
34531 if (this._meshRequest != null) {
34532 this._meshRequest.abort();
34536 * Reset the sequence edges.
34538 NodeCache.prototype.resetSequenceEdges = function () {
34539 this._sequenceEdges = { cached: false, edges: [] };
34540 this._sequenceEdgesChanged$.next(this._sequenceEdges);
34543 * Reset the spatial edges.
34545 NodeCache.prototype.resetSpatialEdges = function () {
34546 this._spatialEdges = { cached: false, edges: [] };
34547 this._spatialEdgesChanged$.next(this._spatialEdges);
34552 * @param {string} key - Key of the node to cache.
34553 * @param {boolean} pano - Value indicating whether node is a panorama.
34554 * @returns {Observable<ILoadStatusObject<HTMLImageElement>>} Observable
34555 * emitting a load status object every time the load status changes
34556 * and completes when the image is fully loaded.
34558 NodeCache.prototype._cacheImage$ = function (key, imageSize) {
34560 return Observable_1.Observable.create(function (subscriber) {
34561 var xmlHTTP = new XMLHttpRequest();
34562 xmlHTTP.open("GET", Utils_1.Urls.thumbnail(key, imageSize), true);
34563 xmlHTTP.responseType = "arraybuffer";
34564 xmlHTTP.timeout = 15000;
34565 xmlHTTP.onload = function (pe) {
34566 if (xmlHTTP.status !== 200) {
34567 _this._imageRequest = null;
34568 subscriber.error(new Error("Failed to fetch image (" + key + "). Status: " + xmlHTTP.status + ", " + xmlHTTP.statusText));
34571 var image = new Image();
34572 image.crossOrigin = "Anonymous";
34573 image.onload = function (e) {
34574 _this._imageRequest = null;
34575 if (_this._disposed) {
34576 window.URL.revokeObjectURL(image.src);
34577 subscriber.error(new Error("Image load was aborted (" + key + ")"));
34580 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: image });
34581 subscriber.complete();
34583 image.onerror = function (error) {
34584 _this._imageRequest = null;
34585 subscriber.error(new Error("Failed to load image (" + key + ")"));
34587 var blob = new Blob([xmlHTTP.response]);
34588 image.src = window.URL.createObjectURL(blob);
34590 xmlHTTP.onprogress = function (pe) {
34591 if (_this._disposed) {
34594 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: null });
34596 xmlHTTP.onerror = function (error) {
34597 _this._imageRequest = null;
34598 subscriber.error(new Error("Failed to fetch image (" + key + ")"));
34600 xmlHTTP.ontimeout = function (e) {
34601 _this._imageRequest = null;
34602 subscriber.error(new Error("Image request timed out (" + key + ")"));
34604 xmlHTTP.onabort = function (event) {
34605 _this._imageRequest = null;
34606 subscriber.error(new Error("Image request was aborted (" + key + ")"));
34608 _this._imageRequest = xmlHTTP;
34609 xmlHTTP.send(null);
34615 * @param {string} key - Key of the node to cache.
34616 * @param {boolean} merged - Value indicating whether node is merged.
34617 * @returns {Observable<ILoadStatusObject<IMesh>>} Observable emitting
34618 * a load status object every time the load status changes and completes
34619 * when the mesh is fully loaded.
34621 NodeCache.prototype._cacheMesh$ = function (key, merged) {
34623 return Observable_1.Observable.create(function (subscriber) {
34625 subscriber.next(_this._createEmptyMeshLoadStatus());
34626 subscriber.complete();
34629 var xmlHTTP = new XMLHttpRequest();
34630 xmlHTTP.open("GET", Utils_1.Urls.protoMesh(key), true);
34631 xmlHTTP.responseType = "arraybuffer";
34632 xmlHTTP.timeout = 15000;
34633 xmlHTTP.onload = function (pe) {
34634 _this._meshRequest = null;
34635 if (_this._disposed) {
34638 var mesh = xmlHTTP.status === 200 ?
34639 Graph_1.MeshReader.read(new Buffer(xmlHTTP.response)) :
34640 { faces: [], vertices: [] };
34641 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: mesh });
34642 subscriber.complete();
34644 xmlHTTP.onprogress = function (pe) {
34645 if (_this._disposed) {
34648 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: null });
34650 xmlHTTP.onerror = function (e) {
34651 _this._meshRequest = null;
34652 console.error("Failed to cache mesh (" + key + ")");
34653 subscriber.next(_this._createEmptyMeshLoadStatus());
34654 subscriber.complete();
34656 xmlHTTP.ontimeout = function (e) {
34657 _this._meshRequest = null;
34658 console.error("Mesh request timed out (" + key + ")");
34659 subscriber.next(_this._createEmptyMeshLoadStatus());
34660 subscriber.complete();
34662 xmlHTTP.onabort = function (e) {
34663 _this._meshRequest = null;
34664 subscriber.error(new Error("Mesh request was aborted (" + key + ")"));
34666 _this._meshRequest = xmlHTTP;
34667 xmlHTTP.send(null);
34671 * Create a load status object with an empty mesh.
34673 * @returns {ILoadStatusObject<IMesh>} Load status object
34676 NodeCache.prototype._createEmptyMeshLoadStatus = function () {
34678 loaded: { loaded: 0, total: 0 },
34679 object: { faces: [], vertices: [] },
34682 NodeCache.prototype._disposeImage = function () {
34683 if (this._image != null) {
34684 window.URL.revokeObjectURL(this._image.src);
34686 this._image = null;
34690 exports.NodeCache = NodeCache;
34691 exports.default = NodeCache;
34693 }).call(this,require("buffer").Buffer)
34695 },{"../Graph":230,"../Utils":235,"buffer":7,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/publishReplay":72}],319:[function(require,module,exports){
34697 /// <reference path="../../typings/index.d.ts" />
34698 Object.defineProperty(exports, "__esModule", { value: true });
34699 var _ = require("underscore");
34703 * @classdesc Represents a sequence of ordered nodes.
34705 var Sequence = (function () {
34707 * Create a new sequene instance.
34709 * @param {ISequence} sequence - Raw sequence data.
34711 function Sequence(sequence) {
34712 this._key = sequence.key;
34713 this._keys = sequence.keys;
34715 Object.defineProperty(Sequence.prototype, "key", {
34719 * @returns {string} Unique sequence key.
34727 Object.defineProperty(Sequence.prototype, "keys", {
34731 * @returns {Array<string>} Array of ordered node keys in the sequence.
34740 * Dispose the sequence.
34742 * @description Disposes all cached assets.
34744 Sequence.prototype.dispose = function () {
34749 * Find the next node key in the sequence with respect to
34750 * the provided node key.
34752 * @param {string} key - Reference node key.
34753 * @returns {string} Next key in sequence if it exists, null otherwise.
34755 Sequence.prototype.findNextKey = function (key) {
34756 var i = _.indexOf(this._keys, key);
34757 if ((i + 1) >= this._keys.length || i === -1) {
34761 return this._keys[i + 1];
34765 * Find the previous node key in the sequence with respect to
34766 * the provided node key.
34768 * @param {string} key - Reference node key.
34769 * @returns {string} Previous key in sequence if it exists, null otherwise.
34771 Sequence.prototype.findPrevKey = function (key) {
34772 var i = _.indexOf(this._keys, key);
34773 if (i === 0 || i === -1) {
34777 return this._keys[i - 1];
34782 exports.Sequence = Sequence;
34783 exports.default = Sequence;
34785 },{"underscore":178}],320:[function(require,module,exports){
34787 /// <reference path="../../../typings/index.d.ts" />
34788 Object.defineProperty(exports, "__esModule", { value: true });
34789 var THREE = require("three");
34790 var Edge_1 = require("../../Edge");
34791 var Error_1 = require("../../Error");
34792 var Geo_1 = require("../../Geo");
34794 * @class EdgeCalculator
34796 * @classdesc Represents a class for calculating node edges.
34798 var EdgeCalculator = (function () {
34800 * Create a new edge calculator instance.
34802 * @param {EdgeCalculatorSettings} settings - Settings struct.
34803 * @param {EdgeCalculatorDirections} directions - Directions struct.
34804 * @param {EdgeCalculatorCoefficients} coefficients - Coefficients struct.
34806 function EdgeCalculator(settings, directions, coefficients) {
34807 this._spatial = new Geo_1.Spatial();
34808 this._geoCoords = new Geo_1.GeoCoords();
34809 this._settings = settings != null ? settings : new Edge_1.EdgeCalculatorSettings();
34810 this._directions = directions != null ? directions : new Edge_1.EdgeCalculatorDirections();
34811 this._coefficients = coefficients != null ? coefficients : new Edge_1.EdgeCalculatorCoefficients();
34814 * Returns the potential edges to destination nodes for a set
34815 * of nodes with respect to a source node.
34817 * @param {Node} node - Source node.
34818 * @param {Array<Node>} nodes - Potential destination nodes.
34819 * @param {Array<string>} fallbackKeys - Keys for destination nodes that should
34820 * be returned even if they do not meet the criteria for a potential edge.
34821 * @throws {ArgumentMapillaryError} If node is not full.
34823 EdgeCalculator.prototype.getPotentialEdges = function (node, potentialNodes, fallbackKeys) {
34825 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
34827 if (!node.merged) {
34830 var currentDirection = this._spatial.viewingDirection(node.rotation);
34831 var currentVerticalDirection = this._spatial.angleToPlane(currentDirection.toArray(), [0, 0, 1]);
34832 var potentialEdges = [];
34833 for (var _i = 0, potentialNodes_1 = potentialNodes; _i < potentialNodes_1.length; _i++) {
34834 var potential = potentialNodes_1[_i];
34835 if (!potential.merged ||
34836 potential.key === node.key) {
34839 var enu = this._geoCoords.geodeticToEnu(potential.latLon.lat, potential.latLon.lon, potential.alt, node.latLon.lat, node.latLon.lon, node.alt);
34840 var motion = new THREE.Vector3(enu[0], enu[1], enu[2]);
34841 var distance = motion.length();
34842 if (distance > this._settings.maxDistance &&
34843 fallbackKeys.indexOf(potential.key) < 0) {
34846 var motionChange = this._spatial.angleBetweenVector2(currentDirection.x, currentDirection.y, motion.x, motion.y);
34847 var verticalMotion = this._spatial.angleToPlane(motion.toArray(), [0, 0, 1]);
34848 var direction = this._spatial.viewingDirection(potential.rotation);
34849 var directionChange = this._spatial.angleBetweenVector2(currentDirection.x, currentDirection.y, direction.x, direction.y);
34850 var verticalDirection = this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
34851 var verticalDirectionChange = verticalDirection - currentVerticalDirection;
34852 var rotation = this._spatial.relativeRotationAngle(node.rotation, potential.rotation);
34853 var worldMotionAzimuth = this._spatial.angleBetweenVector2(1, 0, motion.x, motion.y);
34854 var sameSequence = potential.sequenceKey != null &&
34855 node.sequenceKey != null &&
34856 potential.sequenceKey === node.sequenceKey;
34857 var sameMergeCC = (potential.mergeCC == null && node.mergeCC == null) ||
34858 potential.mergeCC === node.mergeCC;
34859 var sameUser = potential.userKey === node.userKey;
34860 var potentialEdge = {
34861 capturedAt: potential.capturedAt,
34862 croppedPano: potential.pano && !potential.fullPano,
34863 directionChange: directionChange,
34864 distance: distance,
34865 fullPano: potential.fullPano,
34866 key: potential.key,
34867 motionChange: motionChange,
34868 rotation: rotation,
34869 sameMergeCC: sameMergeCC,
34870 sameSequence: sameSequence,
34871 sameUser: sameUser,
34872 sequenceKey: potential.sequenceKey,
34873 verticalDirectionChange: verticalDirectionChange,
34874 verticalMotion: verticalMotion,
34875 worldMotionAzimuth: worldMotionAzimuth,
34877 potentialEdges.push(potentialEdge);
34879 return potentialEdges;
34882 * Computes the sequence edges for a node.
34884 * @param {Node} node - Source node.
34885 * @throws {ArgumentMapillaryError} If node is not full.
34887 EdgeCalculator.prototype.computeSequenceEdges = function (node, sequence) {
34889 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
34891 if (node.sequenceKey !== sequence.key) {
34892 throw new Error_1.ArgumentMapillaryError("Node and sequence does not correspond.");
34895 var nextKey = sequence.findNextKey(node.key);
34896 if (nextKey != null) {
34899 direction: Edge_1.EdgeDirection.Next,
34900 worldMotionAzimuth: Number.NaN,
34906 var prevKey = sequence.findPrevKey(node.key);
34907 if (prevKey != null) {
34910 direction: Edge_1.EdgeDirection.Prev,
34911 worldMotionAzimuth: Number.NaN,
34920 * Computes the similar edges for a node.
34922 * @description Similar edges for perspective images and cropped panoramas
34923 * look roughly in the same direction and are positioned closed to the node.
34924 * Similar edges for full panoramas only target other full panoramas.
34926 * @param {Node} node - Source node.
34927 * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
34928 * @throws {ArgumentMapillaryError} If node is not full.
34930 EdgeCalculator.prototype.computeSimilarEdges = function (node, potentialEdges) {
34933 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
34935 var nodeFullPano = node.fullPano;
34936 var sequenceGroups = {};
34937 for (var _i = 0, potentialEdges_1 = potentialEdges; _i < potentialEdges_1.length; _i++) {
34938 var potentialEdge = potentialEdges_1[_i];
34939 if (potentialEdge.sequenceKey == null) {
34942 if (potentialEdge.sameSequence ||
34943 !potentialEdge.sameMergeCC) {
34946 if (nodeFullPano) {
34947 if (!potentialEdge.fullPano) {
34952 if (!potentialEdge.fullPano &&
34953 Math.abs(potentialEdge.directionChange) > this._settings.similarMaxDirectionChange) {
34957 if (potentialEdge.distance > this._settings.similarMaxDistance) {
34960 if (potentialEdge.sameUser &&
34961 Math.abs(potentialEdge.capturedAt - node.capturedAt) <
34962 this._settings.similarMinTimeDifference) {
34965 if (sequenceGroups[potentialEdge.sequenceKey] == null) {
34966 sequenceGroups[potentialEdge.sequenceKey] = [];
34968 sequenceGroups[potentialEdge.sequenceKey].push(potentialEdge);
34970 var similarEdges = [];
34971 var calculateScore = node.fullPano ?
34972 function (potentialEdge) {
34973 return potentialEdge.distance;
34975 function (potentialEdge) {
34976 return _this._coefficients.similarDistance * potentialEdge.distance +
34977 _this._coefficients.similarRotation * potentialEdge.rotation;
34979 for (var sequenceKey in sequenceGroups) {
34980 if (!sequenceGroups.hasOwnProperty(sequenceKey)) {
34983 var lowestScore = Number.MAX_VALUE;
34984 var similarEdge = null;
34985 for (var _a = 0, _b = sequenceGroups[sequenceKey]; _a < _b.length; _a++) {
34986 var potentialEdge = _b[_a];
34987 var score = calculateScore(potentialEdge);
34988 if (score < lowestScore) {
34989 lowestScore = score;
34990 similarEdge = potentialEdge;
34993 if (similarEdge == null) {
34996 similarEdges.push(similarEdge);
34998 return similarEdges
34999 .map(function (potentialEdge) {
35002 direction: Edge_1.EdgeDirection.Similar,
35003 worldMotionAzimuth: potentialEdge.worldMotionAzimuth,
35006 to: potentialEdge.key,
35011 * Computes the step edges for a perspective node.
35013 * @description Step edge targets can only be other perspective nodes.
35014 * Returns an empty array for cropped and full panoramas.
35016 * @param {Node} node - Source node.
35017 * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
35018 * @param {string} prevKey - Key of previous node in sequence.
35019 * @param {string} prevKey - Key of next node in sequence.
35020 * @throws {ArgumentMapillaryError} If node is not full.
35022 EdgeCalculator.prototype.computeStepEdges = function (node, potentialEdges, prevKey, nextKey) {
35024 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
35030 for (var k in this._directions.steps) {
35031 if (!this._directions.steps.hasOwnProperty(k)) {
35034 var step = this._directions.steps[k];
35035 var lowestScore = Number.MAX_VALUE;
35037 var fallback = null;
35038 for (var _i = 0, potentialEdges_2 = potentialEdges; _i < potentialEdges_2.length; _i++) {
35039 var potential = potentialEdges_2[_i];
35040 if (potential.croppedPano || potential.fullPano) {
35043 if (Math.abs(potential.directionChange) > this._settings.stepMaxDirectionChange) {
35046 var motionDifference = this._spatial.angleDifference(step.motionChange, potential.motionChange);
35047 var directionMotionDifference = this._spatial.angleDifference(potential.directionChange, motionDifference);
35048 var drift = Math.max(Math.abs(motionDifference), Math.abs(directionMotionDifference));
35049 if (Math.abs(drift) > this._settings.stepMaxDrift) {
35052 var potentialKey = potential.key;
35053 if (step.useFallback && (potentialKey === prevKey || potentialKey === nextKey)) {
35054 fallback = potential;
35056 if (potential.distance > this._settings.stepMaxDistance) {
35059 motionDifference = Math.sqrt(motionDifference * motionDifference +
35060 potential.verticalMotion * potential.verticalMotion);
35061 var score = this._coefficients.stepPreferredDistance *
35062 Math.abs(potential.distance - this._settings.stepPreferredDistance) /
35063 this._settings.stepMaxDistance +
35064 this._coefficients.stepMotion * motionDifference / this._settings.stepMaxDrift +
35065 this._coefficients.stepRotation * potential.rotation / this._settings.stepMaxDirectionChange +
35066 this._coefficients.stepSequencePenalty * (potential.sameSequence ? 0 : 1) +
35067 this._coefficients.stepMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
35068 if (score < lowestScore) {
35069 lowestScore = score;
35073 edge = edge == null ? fallback : edge;
35074 if (edge != null) {
35077 direction: step.direction,
35078 worldMotionAzimuth: edge.worldMotionAzimuth,
35088 * Computes the turn edges for a perspective node.
35090 * @description Turn edge targets can only be other perspective images.
35091 * Returns an empty array for cropped and full panoramas.
35093 * @param {Node} node - Source node.
35094 * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
35095 * @throws {ArgumentMapillaryError} If node is not full.
35097 EdgeCalculator.prototype.computeTurnEdges = function (node, potentialEdges) {
35099 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
35105 for (var k in this._directions.turns) {
35106 if (!this._directions.turns.hasOwnProperty(k)) {
35109 var turn = this._directions.turns[k];
35110 var lowestScore = Number.MAX_VALUE;
35112 for (var _i = 0, potentialEdges_3 = potentialEdges; _i < potentialEdges_3.length; _i++) {
35113 var potential = potentialEdges_3[_i];
35114 if (potential.croppedPano || potential.fullPano) {
35117 if (potential.distance > this._settings.turnMaxDistance) {
35120 var rig = turn.direction !== Edge_1.EdgeDirection.TurnU &&
35121 potential.distance < this._settings.turnMaxRigDistance &&
35122 Math.abs(potential.directionChange) > this._settings.turnMinRigDirectionChange;
35123 var directionDifference = this._spatial.angleDifference(turn.directionChange, potential.directionChange);
35124 var score = void 0;
35126 potential.directionChange * turn.directionChange > 0 &&
35127 Math.abs(potential.directionChange) < Math.abs(turn.directionChange)) {
35128 score = -Math.PI / 2 + Math.abs(potential.directionChange);
35131 if (Math.abs(directionDifference) > this._settings.turnMaxDirectionChange) {
35134 var motionDifference = turn.motionChange ?
35135 this._spatial.angleDifference(turn.motionChange, potential.motionChange) : 0;
35136 motionDifference = Math.sqrt(motionDifference * motionDifference +
35137 potential.verticalMotion * potential.verticalMotion);
35139 this._coefficients.turnDistance * potential.distance /
35140 this._settings.turnMaxDistance +
35141 this._coefficients.turnMotion * motionDifference / Math.PI +
35142 this._coefficients.turnSequencePenalty * (potential.sameSequence ? 0 : 1) +
35143 this._coefficients.turnMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
35145 if (score < lowestScore) {
35146 lowestScore = score;
35150 if (edge != null) {
35153 direction: turn.direction,
35154 worldMotionAzimuth: edge.worldMotionAzimuth,
35164 * Computes the pano edges for a perspective node.
35166 * @description Perspective to pano edge targets can only be
35167 * full pano nodes. Returns an empty array for cropped and full panoramas.
35169 * @param {Node} node - Source node.
35170 * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
35171 * @throws {ArgumentMapillaryError} If node is not full.
35173 EdgeCalculator.prototype.computePerspectiveToPanoEdges = function (node, potentialEdges) {
35175 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
35180 var lowestScore = Number.MAX_VALUE;
35182 for (var _i = 0, potentialEdges_4 = potentialEdges; _i < potentialEdges_4.length; _i++) {
35183 var potential = potentialEdges_4[_i];
35184 if (!potential.fullPano) {
35187 var score = this._coefficients.panoPreferredDistance *
35188 Math.abs(potential.distance - this._settings.panoPreferredDistance) /
35189 this._settings.panoMaxDistance +
35190 this._coefficients.panoMotion * Math.abs(potential.motionChange) / Math.PI +
35191 this._coefficients.panoMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
35192 if (score < lowestScore) {
35193 lowestScore = score;
35197 if (edge == null) {
35203 direction: Edge_1.EdgeDirection.Pano,
35204 worldMotionAzimuth: edge.worldMotionAzimuth,
35212 * Computes the full pano and step edges for a full pano node.
35214 * @description Pano to pano edge targets can only be
35215 * full pano nodes. Pano to step edge targets can only be perspective
35217 * Returns an empty array for cropped panoramas and perspective nodes.
35219 * @param {Node} node - Source node.
35220 * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
35221 * @throws {ArgumentMapillaryError} If node is not full.
35223 EdgeCalculator.prototype.computePanoEdges = function (node, potentialEdges) {
35225 throw new Error_1.ArgumentMapillaryError("Node has to be full.");
35227 if (!node.fullPano) {
35230 var panoEdges = [];
35231 var potentialPanos = [];
35232 var potentialSteps = [];
35233 for (var _i = 0, potentialEdges_5 = potentialEdges; _i < potentialEdges_5.length; _i++) {
35234 var potential = potentialEdges_5[_i];
35235 if (potential.distance > this._settings.panoMaxDistance) {
35238 if (potential.fullPano) {
35239 if (potential.distance < this._settings.panoMinDistance) {
35242 potentialPanos.push(potential);
35245 if (potential.croppedPano) {
35248 for (var k in this._directions.panos) {
35249 if (!this._directions.panos.hasOwnProperty(k)) {
35252 var pano = this._directions.panos[k];
35253 var turn = this._spatial.angleDifference(potential.directionChange, potential.motionChange);
35254 var turnChange = this._spatial.angleDifference(pano.directionChange, turn);
35255 if (Math.abs(turnChange) > this._settings.panoMaxStepTurnChange) {
35258 potentialSteps.push([pano.direction, potential]);
35259 // break if step direction found
35264 var maxRotationDifference = Math.PI / this._settings.panoMaxItems;
35265 var occupiedAngles = [];
35266 var stepAngles = [];
35267 for (var index = 0; index < this._settings.panoMaxItems; index++) {
35268 var rotation = index / this._settings.panoMaxItems * 2 * Math.PI;
35269 var lowestScore = Number.MAX_VALUE;
35271 for (var _a = 0, potentialPanos_1 = potentialPanos; _a < potentialPanos_1.length; _a++) {
35272 var potential = potentialPanos_1[_a];
35273 var motionDifference = this._spatial.angleDifference(rotation, potential.motionChange);
35274 if (Math.abs(motionDifference) > maxRotationDifference) {
35277 var occupiedDifference = Number.MAX_VALUE;
35278 for (var _b = 0, occupiedAngles_1 = occupiedAngles; _b < occupiedAngles_1.length; _b++) {
35279 var occupiedAngle = occupiedAngles_1[_b];
35280 var difference = Math.abs(this._spatial.angleDifference(occupiedAngle, potential.motionChange));
35281 if (difference < occupiedDifference) {
35282 occupiedDifference = difference;
35285 if (occupiedDifference <= maxRotationDifference) {
35288 var score = this._coefficients.panoPreferredDistance *
35289 Math.abs(potential.distance - this._settings.panoPreferredDistance) /
35290 this._settings.panoMaxDistance +
35291 this._coefficients.panoMotion * Math.abs(motionDifference) / maxRotationDifference +
35292 this._coefficients.panoSequencePenalty * (potential.sameSequence ? 0 : 1) +
35293 this._coefficients.panoMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
35294 if (score < lowestScore) {
35295 lowestScore = score;
35299 if (edge != null) {
35300 occupiedAngles.push(edge.motionChange);
35303 direction: Edge_1.EdgeDirection.Pano,
35304 worldMotionAzimuth: edge.worldMotionAzimuth,
35311 stepAngles.push(rotation);
35314 var occupiedStepAngles = {};
35315 occupiedStepAngles[Edge_1.EdgeDirection.Pano] = occupiedAngles;
35316 occupiedStepAngles[Edge_1.EdgeDirection.StepForward] = [];
35317 occupiedStepAngles[Edge_1.EdgeDirection.StepLeft] = [];
35318 occupiedStepAngles[Edge_1.EdgeDirection.StepBackward] = [];
35319 occupiedStepAngles[Edge_1.EdgeDirection.StepRight] = [];
35320 for (var _c = 0, stepAngles_1 = stepAngles; _c < stepAngles_1.length; _c++) {
35321 var stepAngle = stepAngles_1[_c];
35322 var occupations = [];
35323 for (var k in this._directions.panos) {
35324 if (!this._directions.panos.hasOwnProperty(k)) {
35327 var pano = this._directions.panos[k];
35328 var allOccupiedAngles = occupiedStepAngles[Edge_1.EdgeDirection.Pano]
35329 .concat(occupiedStepAngles[pano.direction])
35330 .concat(occupiedStepAngles[pano.prev])
35331 .concat(occupiedStepAngles[pano.next]);
35332 var lowestScore = Number.MAX_VALUE;
35334 for (var _d = 0, potentialSteps_1 = potentialSteps; _d < potentialSteps_1.length; _d++) {
35335 var potential = potentialSteps_1[_d];
35336 if (potential[0] !== pano.direction) {
35339 var motionChange = this._spatial.angleDifference(stepAngle, potential[1].motionChange);
35340 if (Math.abs(motionChange) > maxRotationDifference) {
35343 var minOccupiedDifference = Number.MAX_VALUE;
35344 for (var _e = 0, allOccupiedAngles_1 = allOccupiedAngles; _e < allOccupiedAngles_1.length; _e++) {
35345 var occupiedAngle = allOccupiedAngles_1[_e];
35346 var occupiedDifference = Math.abs(this._spatial.angleDifference(occupiedAngle, potential[1].motionChange));
35347 if (occupiedDifference < minOccupiedDifference) {
35348 minOccupiedDifference = occupiedDifference;
35351 if (minOccupiedDifference <= maxRotationDifference) {
35354 var score = this._coefficients.panoPreferredDistance *
35355 Math.abs(potential[1].distance - this._settings.panoPreferredDistance) /
35356 this._settings.panoMaxDistance +
35357 this._coefficients.panoMotion * Math.abs(motionChange) / maxRotationDifference +
35358 this._coefficients.panoMergeCCPenalty * (potential[1].sameMergeCC ? 0 : 1);
35359 if (score < lowestScore) {
35360 lowestScore = score;
35364 if (edge != null) {
35365 occupations.push(edge);
35368 direction: edge[0],
35369 worldMotionAzimuth: edge[1].worldMotionAzimuth,
35376 for (var _f = 0, occupations_1 = occupations; _f < occupations_1.length; _f++) {
35377 var occupation = occupations_1[_f];
35378 occupiedStepAngles[occupation[0]].push(occupation[1].motionChange);
35383 return EdgeCalculator;
35385 exports.EdgeCalculator = EdgeCalculator;
35386 exports.default = EdgeCalculator;
35388 },{"../../Edge":227,"../../Error":228,"../../Geo":229,"three":176}],321:[function(require,module,exports){
35390 Object.defineProperty(exports, "__esModule", { value: true });
35391 var EdgeCalculatorCoefficients = (function () {
35392 function EdgeCalculatorCoefficients() {
35393 this.panoPreferredDistance = 2;
35394 this.panoMotion = 2;
35395 this.panoSequencePenalty = 1;
35396 this.panoMergeCCPenalty = 4;
35397 this.stepPreferredDistance = 4;
35398 this.stepMotion = 3;
35399 this.stepRotation = 4;
35400 this.stepSequencePenalty = 2;
35401 this.stepMergeCCPenalty = 6;
35402 this.similarDistance = 2;
35403 this.similarRotation = 3;
35404 this.turnDistance = 4;
35405 this.turnMotion = 2;
35406 this.turnSequencePenalty = 1;
35407 this.turnMergeCCPenalty = 4;
35409 return EdgeCalculatorCoefficients;
35411 exports.EdgeCalculatorCoefficients = EdgeCalculatorCoefficients;
35412 exports.default = EdgeCalculatorCoefficients;
35414 },{}],322:[function(require,module,exports){
35416 Object.defineProperty(exports, "__esModule", { value: true });
35417 var Edge_1 = require("../../Edge");
35418 var EdgeCalculatorDirections = (function () {
35419 function EdgeCalculatorDirections() {
35423 this.steps[Edge_1.EdgeDirection.StepForward] = {
35424 direction: Edge_1.EdgeDirection.StepForward,
35428 this.steps[Edge_1.EdgeDirection.StepBackward] = {
35429 direction: Edge_1.EdgeDirection.StepBackward,
35430 motionChange: Math.PI,
35433 this.steps[Edge_1.EdgeDirection.StepLeft] = {
35434 direction: Edge_1.EdgeDirection.StepLeft,
35435 motionChange: Math.PI / 2,
35436 useFallback: false,
35438 this.steps[Edge_1.EdgeDirection.StepRight] = {
35439 direction: Edge_1.EdgeDirection.StepRight,
35440 motionChange: -Math.PI / 2,
35441 useFallback: false,
35443 this.turns[Edge_1.EdgeDirection.TurnLeft] = {
35444 direction: Edge_1.EdgeDirection.TurnLeft,
35445 directionChange: Math.PI / 2,
35446 motionChange: Math.PI / 4,
35448 this.turns[Edge_1.EdgeDirection.TurnRight] = {
35449 direction: Edge_1.EdgeDirection.TurnRight,
35450 directionChange: -Math.PI / 2,
35451 motionChange: -Math.PI / 4,
35453 this.turns[Edge_1.EdgeDirection.TurnU] = {
35454 direction: Edge_1.EdgeDirection.TurnU,
35455 directionChange: Math.PI,
35456 motionChange: null,
35458 this.panos[Edge_1.EdgeDirection.StepForward] = {
35459 direction: Edge_1.EdgeDirection.StepForward,
35460 directionChange: 0,
35461 next: Edge_1.EdgeDirection.StepLeft,
35462 prev: Edge_1.EdgeDirection.StepRight,
35464 this.panos[Edge_1.EdgeDirection.StepBackward] = {
35465 direction: Edge_1.EdgeDirection.StepBackward,
35466 directionChange: Math.PI,
35467 next: Edge_1.EdgeDirection.StepRight,
35468 prev: Edge_1.EdgeDirection.StepLeft,
35470 this.panos[Edge_1.EdgeDirection.StepLeft] = {
35471 direction: Edge_1.EdgeDirection.StepLeft,
35472 directionChange: Math.PI / 2,
35473 next: Edge_1.EdgeDirection.StepBackward,
35474 prev: Edge_1.EdgeDirection.StepForward,
35476 this.panos[Edge_1.EdgeDirection.StepRight] = {
35477 direction: Edge_1.EdgeDirection.StepRight,
35478 directionChange: -Math.PI / 2,
35479 next: Edge_1.EdgeDirection.StepForward,
35480 prev: Edge_1.EdgeDirection.StepBackward,
35483 return EdgeCalculatorDirections;
35485 exports.EdgeCalculatorDirections = EdgeCalculatorDirections;
35487 },{"../../Edge":227}],323:[function(require,module,exports){
35489 Object.defineProperty(exports, "__esModule", { value: true });
35490 var EdgeCalculatorSettings = (function () {
35491 function EdgeCalculatorSettings() {
35492 this.panoMinDistance = 0.1;
35493 this.panoMaxDistance = 20;
35494 this.panoPreferredDistance = 5;
35495 this.panoMaxItems = 4;
35496 this.panoMaxStepTurnChange = Math.PI / 8;
35497 this.rotationMaxDistance = this.turnMaxRigDistance;
35498 this.rotationMaxDirectionChange = Math.PI / 6;
35499 this.rotationMaxVerticalDirectionChange = Math.PI / 8;
35500 this.similarMaxDirectionChange = Math.PI / 8;
35501 this.similarMaxDistance = 12;
35502 this.similarMinTimeDifference = 12 * 3600 * 1000;
35503 this.stepMaxDistance = 20;
35504 this.stepMaxDirectionChange = Math.PI / 6;
35505 this.stepMaxDrift = Math.PI / 6;
35506 this.stepPreferredDistance = 4;
35507 this.turnMaxDistance = 15;
35508 this.turnMaxDirectionChange = 2 * Math.PI / 9;
35509 this.turnMaxRigDistance = 0.65;
35510 this.turnMinRigDirectionChange = Math.PI / 6;
35512 Object.defineProperty(EdgeCalculatorSettings.prototype, "maxDistance", {
35514 return Math.max(this.panoMaxDistance, this.similarMaxDistance, this.stepMaxDistance, this.turnMaxDistance);
35519 return EdgeCalculatorSettings;
35521 exports.EdgeCalculatorSettings = EdgeCalculatorSettings;
35522 exports.default = EdgeCalculatorSettings;
35524 },{}],324:[function(require,module,exports){
35526 Object.defineProperty(exports, "__esModule", { value: true });
35528 * Enumeration for edge directions
35531 * @description Directions for edges in node graph describing
35532 * sequence, spatial and node type relations between nodes.
35535 (function (EdgeDirection) {
35537 * Next node in the sequence.
35539 EdgeDirection[EdgeDirection["Next"] = 0] = "Next";
35541 * Previous node in the sequence.
35543 EdgeDirection[EdgeDirection["Prev"] = 1] = "Prev";
35545 * Step to the left keeping viewing direction.
35547 EdgeDirection[EdgeDirection["StepLeft"] = 2] = "StepLeft";
35549 * Step to the right keeping viewing direction.
35551 EdgeDirection[EdgeDirection["StepRight"] = 3] = "StepRight";
35553 * Step forward keeping viewing direction.
35555 EdgeDirection[EdgeDirection["StepForward"] = 4] = "StepForward";
35557 * Step backward keeping viewing direction.
35559 EdgeDirection[EdgeDirection["StepBackward"] = 5] = "StepBackward";
35561 * Turn 90 degrees counter clockwise.
35563 EdgeDirection[EdgeDirection["TurnLeft"] = 6] = "TurnLeft";
35565 * Turn 90 degrees clockwise.
35567 EdgeDirection[EdgeDirection["TurnRight"] = 7] = "TurnRight";
35569 * Turn 180 degrees.
35571 EdgeDirection[EdgeDirection["TurnU"] = 8] = "TurnU";
35573 * Panorama in general direction.
35575 EdgeDirection[EdgeDirection["Pano"] = 9] = "Pano";
35577 * Looking in roughly the same direction at rougly the same position.
35579 EdgeDirection[EdgeDirection["Similar"] = 10] = "Similar";
35580 })(EdgeDirection = exports.EdgeDirection || (exports.EdgeDirection = {}));
35582 },{}],325:[function(require,module,exports){
35584 /// <reference path="../../typings/index.d.ts" />
35585 Object.defineProperty(exports, "__esModule", { value: true });
35586 var _ = require("underscore");
35587 var vd = require("virtual-dom");
35588 var Subject_1 = require("rxjs/Subject");
35589 require("rxjs/add/operator/combineLatest");
35590 require("rxjs/add/operator/distinctUntilChanged");
35591 require("rxjs/add/operator/filter");
35592 require("rxjs/add/operator/map");
35593 require("rxjs/add/operator/pluck");
35594 require("rxjs/add/operator/scan");
35595 var Render_1 = require("../Render");
35596 var DOMRenderer = (function () {
35597 function DOMRenderer(element, renderService, currentFrame$) {
35598 this._adaptiveOperation$ = new Subject_1.Subject();
35599 this._render$ = new Subject_1.Subject();
35600 this._renderAdaptive$ = new Subject_1.Subject();
35601 this._renderService = renderService;
35602 this._currentFrame$ = currentFrame$;
35603 var rootNode = vd.create(vd.h("div.domRenderer", []));
35604 element.appendChild(rootNode);
35605 this._offset$ = this._adaptiveOperation$
35606 .scan(function (adaptive, operation) {
35607 return operation(adaptive);
35609 elementHeight: element.offsetHeight,
35610 elementWidth: element.offsetWidth,
35612 renderMode: Render_1.RenderMode.Fill,
35614 .filter(function (adaptive) {
35615 return adaptive.imageAspect > 0 && adaptive.elementWidth > 0 && adaptive.elementHeight > 0;
35617 .map(function (adaptive) {
35618 var elementAspect = adaptive.elementWidth / adaptive.elementHeight;
35619 var ratio = adaptive.imageAspect / elementAspect;
35620 var verticalOffset = 0;
35621 var horizontalOffset = 0;
35622 if (adaptive.renderMode === Render_1.RenderMode.Letterbox) {
35623 if (adaptive.imageAspect > elementAspect) {
35624 verticalOffset = adaptive.elementHeight * (1 - 1 / ratio) / 2;
35627 horizontalOffset = adaptive.elementWidth * (1 - ratio) / 2;
35631 if (adaptive.imageAspect > elementAspect) {
35632 horizontalOffset = -adaptive.elementWidth * (ratio - 1) / 2;
35635 verticalOffset = -adaptive.elementHeight * (1 / ratio - 1) / 2;
35639 bottom: verticalOffset,
35640 left: horizontalOffset,
35641 right: horizontalOffset,
35642 top: verticalOffset,
35645 this._currentFrame$
35646 .filter(function (frame) {
35647 return frame.state.currentNode != null;
35649 .distinctUntilChanged(function (k1, k2) {
35651 }, function (frame) {
35652 return frame.state.currentNode.key;
35654 .map(function (frame) {
35655 return frame.state.currentTransform.basicAspect;
35657 .map(function (aspect) {
35658 return function (adaptive) {
35659 adaptive.imageAspect = aspect;
35663 .subscribe(this._adaptiveOperation$);
35664 this._renderAdaptive$
35665 .scan(function (vNodeHashes, vNodeHash) {
35666 if (vNodeHash.vnode == null) {
35667 delete vNodeHashes[vNodeHash.name];
35670 vNodeHashes[vNodeHash.name] = vNodeHash.vnode;
35672 return vNodeHashes;
35674 .combineLatest(this._offset$)
35675 .map(function (vo) {
35676 var vNodes = _.values(vo[0]);
35677 var offset = vo[1];
35680 bottom: offset.bottom + "px",
35681 left: offset.left + "px",
35682 "pointer-events": "none",
35683 position: "absolute",
35684 right: offset.right + "px",
35685 top: offset.top + "px",
35689 name: "adaptiveDomRenderer",
35690 vnode: vd.h("div.adaptiveDomRenderer", properties, vNodes),
35693 .subscribe(this._render$);
35694 this._vNode$ = this._render$
35695 .scan(function (vNodeHashes, vNodeHash) {
35696 if (vNodeHash.vnode == null) {
35697 delete vNodeHashes[vNodeHash.name];
35700 vNodeHashes[vNodeHash.name] = vNodeHash.vnode;
35702 return vNodeHashes;
35704 .map(function (vNodeHashes) {
35705 var vNodes = _.values(vNodeHashes);
35706 return vd.h("div.domRenderer", vNodes);
35708 this._vPatch$ = this._vNode$
35709 .scan(function (nodePatch, vNode) {
35710 nodePatch.vpatch = vd.diff(nodePatch.vnode, vNode);
35711 nodePatch.vnode = vNode;
35713 }, { vnode: vd.h("div.domRenderer", []), vpatch: null })
35715 this._element$ = this._vPatch$
35716 .scan(function (oldElement, vPatch) {
35717 return vd.patch(oldElement, vPatch);
35721 this._element$.subscribe(function () { });
35722 this._renderService.size$
35723 .map(function (size) {
35724 return function (adaptive) {
35725 adaptive.elementWidth = size.width;
35726 adaptive.elementHeight = size.height;
35730 .subscribe(this._adaptiveOperation$);
35731 this._renderService.renderMode$
35732 .map(function (renderMode) {
35733 return function (adaptive) {
35734 adaptive.renderMode = renderMode;
35738 .subscribe(this._adaptiveOperation$);
35740 Object.defineProperty(DOMRenderer.prototype, "element$", {
35742 return this._element$;
35747 Object.defineProperty(DOMRenderer.prototype, "render$", {
35749 return this._render$;
35754 Object.defineProperty(DOMRenderer.prototype, "renderAdaptive$", {
35756 return this._renderAdaptive$;
35761 DOMRenderer.prototype.clear = function (name) {
35762 this._renderAdaptive$.next({ name: name, vnode: null });
35763 this._render$.next({ name: name, vnode: null });
35765 return DOMRenderer;
35767 exports.DOMRenderer = DOMRenderer;
35768 exports.default = DOMRenderer;
35770 },{"../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}],326:[function(require,module,exports){
35772 Object.defineProperty(exports, "__esModule", { value: true });
35774 (function (GLRenderStage) {
35775 GLRenderStage[GLRenderStage["Background"] = 0] = "Background";
35776 GLRenderStage[GLRenderStage["Foreground"] = 1] = "Foreground";
35777 })(GLRenderStage = exports.GLRenderStage || (exports.GLRenderStage = {}));
35778 exports.default = GLRenderStage;
35780 },{}],327:[function(require,module,exports){
35782 /// <reference path="../../typings/index.d.ts" />
35783 Object.defineProperty(exports, "__esModule", { value: true });
35784 var THREE = require("three");
35785 var Observable_1 = require("rxjs/Observable");
35786 var Subject_1 = require("rxjs/Subject");
35787 require("rxjs/add/observable/combineLatest");
35788 require("rxjs/add/operator/distinctUntilChanged");
35789 require("rxjs/add/operator/filter");
35790 require("rxjs/add/operator/first");
35791 require("rxjs/add/operator/map");
35792 require("rxjs/add/operator/merge");
35793 require("rxjs/add/operator/mergeMap");
35794 require("rxjs/add/operator/scan");
35795 require("rxjs/add/operator/share");
35796 require("rxjs/add/operator/startWith");
35797 var Render_1 = require("../Render");
35798 var GLRenderer = (function () {
35799 function GLRenderer(canvasContainer, renderService) {
35801 this._renderFrame$ = new Subject_1.Subject();
35802 this._renderCameraOperation$ = new Subject_1.Subject();
35803 this._render$ = new Subject_1.Subject();
35804 this._clear$ = new Subject_1.Subject();
35805 this._renderOperation$ = new Subject_1.Subject();
35806 this._rendererOperation$ = new Subject_1.Subject();
35807 this._eraserOperation$ = new Subject_1.Subject();
35808 this._renderService = renderService;
35809 this._renderer$ = this._rendererOperation$
35810 .scan(function (renderer, operation) {
35811 return operation(renderer);
35812 }, { needsRender: false, renderer: null });
35813 this._renderCollection$ = this._renderOperation$
35814 .scan(function (hashes, operation) {
35815 return operation(hashes);
35818 this._renderCamera$ = this._renderCameraOperation$
35819 .scan(function (rc, operation) {
35820 return operation(rc);
35821 }, { frameId: -1, needsRender: false, perspective: null });
35822 this._eraser$ = this._eraserOperation$
35823 .startWith(function (eraser) {
35826 .scan(function (eraser, operation) {
35827 return operation(eraser);
35828 }, { needsRender: false });
35829 Observable_1.Observable
35830 .combineLatest([this._renderer$, this._renderCollection$, this._renderCamera$, this._eraser$], function (renderer, hashes, rc, eraser) {
35831 var renders = Object.keys(hashes)
35832 .map(function (key) {
35833 return hashes[key];
35835 return { camera: rc, eraser: eraser, renderer: renderer, renders: renders };
35837 .filter(function (co) {
35838 var needsRender = co.renderer.needsRender ||
35839 co.camera.needsRender ||
35840 co.eraser.needsRender;
35841 var frameId = co.camera.frameId;
35842 for (var _i = 0, _a = co.renders; _i < _a.length; _i++) {
35843 var render = _a[_i];
35844 if (render.frameId !== frameId) {
35847 needsRender = needsRender || render.needsRender;
35849 return needsRender;
35851 .distinctUntilChanged(function (n1, n2) {
35854 return co.eraser.needsRender ? -1 : co.camera.frameId;
35856 .subscribe(function (co) {
35857 co.renderer.needsRender = false;
35858 co.camera.needsRender = false;
35859 co.eraser.needsRender = false;
35860 var perspectiveCamera = co.camera.perspective;
35861 var backgroundRenders = [];
35862 var foregroundRenders = [];
35863 for (var _i = 0, _a = co.renders; _i < _a.length; _i++) {
35864 var render = _a[_i];
35865 if (render.stage === Render_1.GLRenderStage.Background) {
35866 backgroundRenders.push(render.render);
35868 else if (render.stage === Render_1.GLRenderStage.Foreground) {
35869 foregroundRenders.push(render.render);
35872 var renderer = co.renderer.renderer;
35874 for (var _b = 0, backgroundRenders_1 = backgroundRenders; _b < backgroundRenders_1.length; _b++) {
35875 var render = backgroundRenders_1[_b];
35876 render(perspectiveCamera, renderer);
35878 renderer.clearDepth();
35879 for (var _c = 0, foregroundRenders_1 = foregroundRenders; _c < foregroundRenders_1.length; _c++) {
35880 var render = foregroundRenders_1[_c];
35881 render(perspectiveCamera, renderer);
35885 .map(function (rc) {
35886 return function (irc) {
35887 irc.frameId = rc.frameId;
35888 irc.perspective = rc.perspective;
35889 if (rc.changed === true) {
35890 irc.needsRender = true;
35895 .subscribe(this._renderCameraOperation$);
35896 this._renderFrameSubscribe();
35897 var renderHash$ = this._render$
35898 .map(function (hash) {
35899 return function (hashes) {
35900 hashes[hash.name] = hash.render;
35904 var clearHash$ = this._clear$
35905 .map(function (name) {
35906 return function (hashes) {
35907 delete hashes[name];
35911 Observable_1.Observable
35912 .merge(renderHash$, clearHash$)
35913 .subscribe(this._renderOperation$);
35914 this._webGLRenderer$ = this._render$
35916 .map(function (hash) {
35917 var element = renderService.element;
35918 var webGLRenderer = new THREE.WebGLRenderer();
35919 webGLRenderer.setPixelRatio(window.devicePixelRatio);
35920 webGLRenderer.setSize(element.offsetWidth, element.offsetHeight);
35921 webGLRenderer.setClearColor(new THREE.Color(0x202020), 1.0);
35922 webGLRenderer.autoClear = false;
35923 webGLRenderer.domElement.style.position = "absolute";
35924 canvasContainer.appendChild(webGLRenderer.domElement);
35925 return webGLRenderer;
35929 this._webGLRenderer$.subscribe(function () { });
35930 var createRenderer$ = this._webGLRenderer$
35932 .map(function (webGLRenderer) {
35933 return function (renderer) {
35934 renderer.needsRender = true;
35935 renderer.renderer = webGLRenderer;
35939 var resizeRenderer$ = this._renderService.size$
35940 .map(function (size) {
35941 return function (renderer) {
35942 if (renderer.renderer == null) {
35945 renderer.renderer.setSize(size.width, size.height);
35946 renderer.needsRender = true;
35950 var clearRenderer$ = this._clear$
35951 .map(function (name) {
35952 return function (renderer) {
35953 if (renderer.renderer == null) {
35956 renderer.needsRender = true;
35960 Observable_1.Observable
35961 .merge(createRenderer$, resizeRenderer$, clearRenderer$)
35962 .subscribe(this._rendererOperation$);
35963 var renderCollectionEmpty$ = this._renderCollection$
35964 .filter(function (hashes) {
35965 return Object.keys(hashes).length === 0;
35968 renderCollectionEmpty$
35969 .subscribe(function (hashes) {
35970 if (_this._renderFrameSubscription == null) {
35973 _this._renderFrameSubscription.unsubscribe();
35974 _this._renderFrameSubscription = null;
35975 _this._renderFrameSubscribe();
35977 renderCollectionEmpty$
35978 .map(function (hashes) {
35979 return function (eraser) {
35980 eraser.needsRender = true;
35984 .subscribe(this._eraserOperation$);
35986 Object.defineProperty(GLRenderer.prototype, "render$", {
35988 return this._render$;
35993 Object.defineProperty(GLRenderer.prototype, "webGLRenderer$", {
35995 return this._webGLRenderer$;
36000 GLRenderer.prototype.clear = function (name) {
36001 this._clear$.next(name);
36003 GLRenderer.prototype._renderFrameSubscribe = function () {
36007 .map(function (renderHash) {
36008 return function (irc) {
36009 irc.needsRender = true;
36013 .subscribe(function (operation) {
36014 _this._renderCameraOperation$.next(operation);
36016 this._renderFrameSubscription = this._render$
36018 .mergeMap(function (hash) {
36019 return _this._renderService.renderCameraFrame$;
36021 .subscribe(this._renderFrame$);
36025 exports.GLRenderer = GLRenderer;
36026 exports.default = GLRenderer;
36028 },{"../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}],328:[function(require,module,exports){
36030 /// <reference path="../../typings/index.d.ts" />
36031 Object.defineProperty(exports, "__esModule", { value: true });
36032 var THREE = require("three");
36033 var Geo_1 = require("../Geo");
36034 var Render_1 = require("../Render");
36035 var RenderCamera = (function () {
36036 function RenderCamera(elementWidth, elementHeight, renderMode) {
36039 this._frameId = -1;
36040 this._changed = false;
36041 this._changedForFrame = -1;
36042 this.currentAspect = 1;
36043 this.currentPano = false;
36044 this.previousAspect = 1;
36045 this.previousPano = false;
36046 this.renderMode = renderMode;
36047 this._spatial = new Geo_1.Spatial();
36048 this._camera = new Geo_1.Camera();
36049 var perspectiveCameraAspect = this._getPerspectiveCameraAspect(elementWidth, elementHeight);
36050 this._perspective = new THREE.PerspectiveCamera(50, perspectiveCameraAspect, 0.4, 10000);
36051 this._perspective.matrixAutoUpdate = false;
36052 this._rotation = { phi: 0, theta: 0 };
36054 Object.defineProperty(RenderCamera.prototype, "camera", {
36056 return this._camera;
36061 Object.defineProperty(RenderCamera.prototype, "changed", {
36063 return this.frameId === this._changedForFrame;
36068 Object.defineProperty(RenderCamera.prototype, "frameId", {
36070 return this._frameId;
36072 set: function (value) {
36073 this._frameId = value;
36074 if (this._changed) {
36075 this._changed = false;
36076 this._changedForFrame = value;
36082 Object.defineProperty(RenderCamera.prototype, "perspective", {
36084 return this._perspective;
36089 Object.defineProperty(RenderCamera.prototype, "rotation", {
36091 return this._rotation;
36096 RenderCamera.prototype.updateAspect = function (elementWidth, elementHeight) {
36097 var perspectiveCameraAspect = this._getPerspectiveCameraAspect(elementWidth, elementHeight);
36098 this._perspective.aspect = perspectiveCameraAspect;
36099 this._changed = true;
36101 RenderCamera.prototype.updateProjection = function () {
36102 var currentAspect = this._getAspect(this.currentAspect, this.currentPano, this.perspective.aspect);
36103 var previousAspect = this._getAspect(this.previousAspect, this.previousPano, this.perspective.aspect);
36104 var aspect = (1 - this.alpha) * previousAspect + this.alpha * currentAspect;
36105 var verticalFov = this._getVerticalFov(aspect, this._camera.focal, this.zoom);
36106 this._perspective.fov = verticalFov;
36107 this._perspective.updateProjectionMatrix();
36108 this._changed = true;
36110 RenderCamera.prototype.updatePerspective = function (camera) {
36111 this._perspective.up.copy(camera.up);
36112 this._perspective.position.copy(camera.position);
36113 this._perspective.lookAt(camera.lookat);
36114 this._perspective.updateMatrix();
36115 this._perspective.updateMatrixWorld(false);
36116 this._changed = true;
36118 RenderCamera.prototype.updateRotation = function (camera) {
36119 this._rotation = this._getRotation(camera);
36121 RenderCamera.prototype._getVerticalFov = function (aspect, focal, zoom) {
36122 return 2 * Math.atan(0.5 / (Math.pow(2, zoom) * aspect * focal)) * 180 / Math.PI;
36124 RenderCamera.prototype._getAspect = function (nodeAspect, pano, perspectiveCameraAspect) {
36128 var coeff = Math.max(1, 1 / nodeAspect);
36129 var usePerspective = this.renderMode === Render_1.RenderMode.Letterbox ?
36130 nodeAspect > perspectiveCameraAspect :
36131 nodeAspect < perspectiveCameraAspect;
36132 var aspect = usePerspective ?
36133 coeff * perspectiveCameraAspect :
36134 coeff * nodeAspect;
36137 RenderCamera.prototype._getPerspectiveCameraAspect = function (elementWidth, elementHeight) {
36138 return elementWidth === 0 ? 0 : elementWidth / elementHeight;
36140 RenderCamera.prototype._getRotation = function (camera) {
36141 var direction = camera.lookat.clone().sub(camera.position);
36142 var up = camera.up.clone();
36143 var upProjection = direction.clone().dot(up);
36144 var planeProjection = direction.clone().sub(up.clone().multiplyScalar(upProjection));
36145 var phi = Math.atan2(planeProjection.y, planeProjection.x);
36146 var theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
36147 return { phi: phi, theta: theta };
36149 return RenderCamera;
36151 exports.RenderCamera = RenderCamera;
36152 exports.default = RenderCamera;
36154 },{"../Geo":229,"../Render":232,"three":176}],329:[function(require,module,exports){
36156 Object.defineProperty(exports, "__esModule", { value: true });
36158 * Enumeration for render mode
36161 * @description Modes for specifying how rendering is done
36162 * in the viewer. All modes preserves the original aspect
36163 * ratio of the images.
36166 (function (RenderMode) {
36168 * Displays all content within the viewer.
36170 * @description Black bars shown on both
36171 * sides of the content. Bars are shown
36172 * either below and above or to the left
36173 * and right of the content depending on
36174 * the aspect ratio relation between the
36175 * image and the viewer.
36177 RenderMode[RenderMode["Letterbox"] = 0] = "Letterbox";
36179 * Fills the viewer by cropping content.
36181 * @description Cropping is done either
36182 * in horizontal or vertical direction
36183 * depending on the aspect ratio relation
36184 * between the image and the viewer.
36186 RenderMode[RenderMode["Fill"] = 1] = "Fill";
36187 })(RenderMode = exports.RenderMode || (exports.RenderMode = {}));
36188 exports.default = RenderMode;
36190 },{}],330:[function(require,module,exports){
36192 /// <reference path="../../typings/index.d.ts" />
36193 Object.defineProperty(exports, "__esModule", { value: true });
36194 var Subject_1 = require("rxjs/Subject");
36195 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
36196 require("rxjs/add/observable/combineLatest");
36197 require("rxjs/add/operator/do");
36198 require("rxjs/add/operator/filter");
36199 require("rxjs/add/operator/map");
36200 require("rxjs/add/operator/publishReplay");
36201 require("rxjs/add/operator/scan");
36202 require("rxjs/add/operator/skip");
36203 require("rxjs/add/operator/startWith");
36204 require("rxjs/add/operator/withLatestFrom");
36205 var Geo_1 = require("../Geo");
36206 var Render_1 = require("../Render");
36207 var RenderService = (function () {
36208 function RenderService(element, currentFrame$, renderMode) {
36210 this._element = element;
36211 this._currentFrame$ = currentFrame$;
36212 this._spatial = new Geo_1.Spatial();
36213 renderMode = renderMode != null ? renderMode : Render_1.RenderMode.Fill;
36214 this._resize$ = new Subject_1.Subject();
36215 this._renderCameraOperation$ = new Subject_1.Subject();
36217 new BehaviorSubject_1.BehaviorSubject({
36218 height: this._element.offsetHeight,
36219 width: this._element.offsetWidth,
36223 return { height: _this._element.offsetHeight, width: _this._element.offsetWidth };
36225 .subscribe(this._size$);
36226 this._renderMode$ = new BehaviorSubject_1.BehaviorSubject(renderMode);
36227 this._renderCameraHolder$ = this._renderCameraOperation$
36228 .startWith(function (rc) {
36231 .scan(function (rc, operation) {
36232 return operation(rc);
36233 }, new Render_1.RenderCamera(this._element.offsetWidth, this._element.offsetHeight, renderMode))
36236 this._renderCameraFrame$ = this._currentFrame$
36237 .withLatestFrom(this._renderCameraHolder$, function (frame, renderCamera) {
36238 return [frame, renderCamera];
36240 .do(function (args) {
36241 var frame = args[0];
36243 var camera = frame.state.camera;
36244 if (rc.alpha !== frame.state.alpha ||
36245 rc.zoom !== frame.state.zoom ||
36246 rc.camera.diff(camera) > 1e-9) {
36247 var currentTransform = frame.state.currentTransform;
36248 var previousTransform = frame.state.previousTransform != null ?
36249 frame.state.previousTransform :
36250 frame.state.currentTransform;
36251 var previousNode = frame.state.previousNode != null ?
36252 frame.state.previousNode :
36253 frame.state.currentNode;
36254 rc.currentAspect = currentTransform.basicAspect;
36255 rc.currentPano = frame.state.currentNode.pano;
36256 rc.previousAspect = previousTransform.basicAspect;
36257 rc.previousPano = previousNode.pano;
36258 rc.alpha = frame.state.alpha;
36259 rc.zoom = frame.state.zoom;
36260 rc.camera.copy(camera);
36261 rc.updatePerspective(camera);
36262 rc.updateRotation(camera);
36263 rc.updateProjection();
36265 rc.frameId = frame.id;
36267 .map(function (args) {
36272 this._renderCamera$ = this._renderCameraFrame$
36273 .filter(function (rc) {
36278 this._bearing$ = this._renderCamera$
36279 .map(function (renderCamera) {
36280 var bearing = _this._spatial.radToDeg(_this._spatial.azimuthalToBearing(renderCamera.rotation.phi));
36281 return _this._spatial.wrap(bearing, 0, 360);
36287 .map(function (size) {
36288 return function (rc) {
36289 rc.updateAspect(size.width, size.height);
36290 rc.updateProjection();
36294 .subscribe(this._renderCameraOperation$);
36297 .map(function (rm) {
36298 return function (rc) {
36299 rc.renderMode = rm;
36300 rc.updateProjection();
36304 .subscribe(this._renderCameraOperation$);
36305 this._bearing$.subscribe(function () { });
36306 this._renderCameraHolder$.subscribe(function () { });
36307 this._size$.subscribe(function () { });
36308 this._renderMode$.subscribe(function () { });
36309 this._renderCamera$.subscribe(function () { });
36310 this._renderCameraFrame$.subscribe(function () { });
36312 Object.defineProperty(RenderService.prototype, "bearing$", {
36314 return this._bearing$;
36319 Object.defineProperty(RenderService.prototype, "element", {
36321 return this._element;
36326 Object.defineProperty(RenderService.prototype, "resize$", {
36328 return this._resize$;
36333 Object.defineProperty(RenderService.prototype, "size$", {
36335 return this._size$;
36340 Object.defineProperty(RenderService.prototype, "renderMode$", {
36342 return this._renderMode$;
36347 Object.defineProperty(RenderService.prototype, "renderCameraFrame$", {
36349 return this._renderCameraFrame$;
36354 Object.defineProperty(RenderService.prototype, "renderCamera$", {
36356 return this._renderCamera$;
36361 return RenderService;
36363 exports.RenderService = RenderService;
36364 exports.default = RenderService;
36366 },{"../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}],331:[function(require,module,exports){
36368 Object.defineProperty(exports, "__esModule", { value: true });
36370 (function (State) {
36371 State[State["Traversing"] = 0] = "Traversing";
36372 State[State["Waiting"] = 1] = "Waiting";
36373 })(State = exports.State || (exports.State = {}));
36374 exports.default = State;
36376 },{}],332:[function(require,module,exports){
36378 Object.defineProperty(exports, "__esModule", { value: true });
36379 var State_1 = require("../State");
36380 var Geo_1 = require("../Geo");
36381 var StateContext = (function () {
36382 function StateContext() {
36383 this._state = new State_1.TraversingState({
36385 camera: new Geo_1.Camera(),
36387 reference: { alt: 0, lat: 0, lon: 0 },
36392 StateContext.prototype.traverse = function () {
36393 this._state = this._state.traverse();
36395 StateContext.prototype.wait = function () {
36396 this._state = this._state.wait();
36398 Object.defineProperty(StateContext.prototype, "state", {
36400 if (this._state instanceof State_1.TraversingState) {
36401 return State_1.State.Traversing;
36403 else if (this._state instanceof State_1.WaitingState) {
36404 return State_1.State.Waiting;
36406 throw new Error("Invalid state");
36411 Object.defineProperty(StateContext.prototype, "reference", {
36413 return this._state.reference;
36418 Object.defineProperty(StateContext.prototype, "alpha", {
36420 return this._state.alpha;
36425 Object.defineProperty(StateContext.prototype, "camera", {
36427 return this._state.camera;
36432 Object.defineProperty(StateContext.prototype, "zoom", {
36434 return this._state.zoom;
36439 Object.defineProperty(StateContext.prototype, "currentNode", {
36441 return this._state.currentNode;
36446 Object.defineProperty(StateContext.prototype, "previousNode", {
36448 return this._state.previousNode;
36453 Object.defineProperty(StateContext.prototype, "currentCamera", {
36455 return this._state.currentCamera;
36460 Object.defineProperty(StateContext.prototype, "currentTransform", {
36462 return this._state.currentTransform;
36467 Object.defineProperty(StateContext.prototype, "previousTransform", {
36469 return this._state.previousTransform;
36474 Object.defineProperty(StateContext.prototype, "trajectory", {
36476 return this._state.trajectory;
36481 Object.defineProperty(StateContext.prototype, "currentIndex", {
36483 return this._state.currentIndex;
36488 Object.defineProperty(StateContext.prototype, "lastNode", {
36490 return this._state.trajectory[this._state.trajectory.length - 1];
36495 Object.defineProperty(StateContext.prototype, "nodesAhead", {
36497 return this._state.trajectory.length - 1 - this._state.currentIndex;
36502 Object.defineProperty(StateContext.prototype, "motionless", {
36504 return this._state.motionless;
36509 StateContext.prototype.getCenter = function () {
36510 return this._state.getCenter();
36512 StateContext.prototype.setCenter = function (center) {
36513 this._state.setCenter(center);
36515 StateContext.prototype.setZoom = function (zoom) {
36516 this._state.setZoom(zoom);
36518 StateContext.prototype.update = function (fps) {
36519 this._state.update(fps);
36521 StateContext.prototype.append = function (nodes) {
36522 this._state.append(nodes);
36524 StateContext.prototype.prepend = function (nodes) {
36525 this._state.prepend(nodes);
36527 StateContext.prototype.remove = function (n) {
36528 this._state.remove(n);
36530 StateContext.prototype.clear = function () {
36531 this._state.clear();
36533 StateContext.prototype.clearPrior = function () {
36534 this._state.clearPrior();
36536 StateContext.prototype.cut = function () {
36539 StateContext.prototype.set = function (nodes) {
36540 this._state.set(nodes);
36542 StateContext.prototype.rotate = function (delta) {
36543 this._state.rotate(delta);
36545 StateContext.prototype.rotateBasic = function (basicRotation) {
36546 this._state.rotateBasic(basicRotation);
36548 StateContext.prototype.rotateBasicUnbounded = function (basicRotation) {
36549 this._state.rotateBasicUnbounded(basicRotation);
36551 StateContext.prototype.rotateToBasic = function (basic) {
36552 this._state.rotateToBasic(basic);
36554 StateContext.prototype.move = function (delta) {
36555 this._state.move(delta);
36557 StateContext.prototype.moveTo = function (delta) {
36558 this._state.moveTo(delta);
36560 StateContext.prototype.zoomIn = function (delta, reference) {
36561 this._state.zoomIn(delta, reference);
36563 return StateContext;
36565 exports.StateContext = StateContext;
36567 },{"../Geo":229,"../State":233}],333:[function(require,module,exports){
36569 Object.defineProperty(exports, "__esModule", { value: true });
36570 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
36571 var Subject_1 = require("rxjs/Subject");
36572 var AnimationFrame_1 = require("rxjs/util/AnimationFrame");
36573 require("rxjs/add/operator/bufferCount");
36574 require("rxjs/add/operator/distinctUntilChanged");
36575 require("rxjs/add/operator/do");
36576 require("rxjs/add/operator/filter");
36577 require("rxjs/add/operator/first");
36578 require("rxjs/add/operator/map");
36579 require("rxjs/add/operator/pairwise");
36580 require("rxjs/add/operator/publishReplay");
36581 require("rxjs/add/operator/scan");
36582 require("rxjs/add/operator/startWith");
36583 require("rxjs/add/operator/switchMap");
36584 require("rxjs/add/operator/withLatestFrom");
36585 var State_1 = require("../State");
36586 var StateService = (function () {
36587 function StateService() {
36589 this._appendNode$ = new Subject_1.Subject();
36590 this._start$ = new Subject_1.Subject();
36591 this._frame$ = new Subject_1.Subject();
36592 this._fpsSampleRate = 30;
36593 this._contextOperation$ = new BehaviorSubject_1.BehaviorSubject(function (context) {
36596 this._context$ = this._contextOperation$
36597 .scan(function (context, operation) {
36598 return operation(context);
36599 }, new State_1.StateContext())
36602 this._state$ = this._context$
36603 .map(function (context) {
36604 return context.state;
36606 .distinctUntilChanged()
36609 this._fps$ = this._start$
36610 .switchMap(function () {
36611 return _this._frame$
36612 .bufferCount(1, _this._fpsSampleRate)
36613 .map(function (frameIds) {
36614 return new Date().getTime();
36617 .map(function (times) {
36618 return Math.max(20, 1000 * _this._fpsSampleRate / (times[1] - times[0]));
36623 this._currentState$ = this._frame$
36624 .withLatestFrom(this._fps$, this._context$, function (frameId, fps, context) {
36625 return [frameId, fps, context];
36627 .filter(function (fc) {
36628 return fc[2].currentNode != null;
36630 .do(function (fc) {
36631 fc[2].update(fc[1]);
36633 .map(function (fc) {
36634 return { fps: fc[1], id: fc[0], state: fc[2] };
36637 this._lastState$ = this._currentState$
36640 var nodeChanged$ = this._currentState$
36641 .distinctUntilChanged(undefined, function (f) {
36642 return f.state.currentNode.key;
36646 var nodeChangedSubject$ = new Subject_1.Subject();
36648 .subscribe(nodeChangedSubject$);
36649 this._currentKey$ = new BehaviorSubject_1.BehaviorSubject(null);
36650 nodeChangedSubject$
36651 .map(function (f) {
36652 return f.state.currentNode.key;
36654 .subscribe(this._currentKey$);
36655 this._currentNode$ = nodeChangedSubject$
36656 .map(function (f) {
36657 return f.state.currentNode;
36661 this._currentCamera$ = nodeChangedSubject$
36662 .map(function (f) {
36663 return f.state.currentCamera;
36667 this._currentTransform$ = nodeChangedSubject$
36668 .map(function (f) {
36669 return f.state.currentTransform;
36673 this._reference$ = nodeChangedSubject$
36674 .map(function (f) {
36675 return f.state.reference;
36677 .distinctUntilChanged(function (r1, r2) {
36678 return r1.lat === r2.lat && r1.lon === r2.lon;
36679 }, function (reference) {
36680 return { lat: reference.lat, lon: reference.lon };
36684 this._currentNodeExternal$ = nodeChanged$
36685 .map(function (f) {
36686 return f.state.currentNode;
36691 .map(function (node) {
36692 return function (context) {
36693 context.append([node]);
36697 .subscribe(this._contextOperation$);
36698 this._inMotionOperation$ = new Subject_1.Subject();
36700 .map(function (frame) {
36703 .subscribe(this._inMotionOperation$);
36704 this._inMotionOperation$
36705 .distinctUntilChanged()
36706 .filter(function (moving) {
36709 .switchMap(function (moving) {
36710 return _this._currentState$
36711 .filter(function (frame) {
36712 return frame.state.nodesAhead === 0;
36714 .map(function (frame) {
36715 return [frame.state.camera.clone(), frame.state.zoom];
36718 .map(function (pair) {
36719 var c1 = pair[0][0];
36720 var c2 = pair[1][0];
36721 var z1 = pair[0][1];
36722 var z2 = pair[1][1];
36723 return c1.diff(c2) > 1e-5 || Math.abs(z1 - z2) > 1e-5;
36725 .first(function (changed) {
36729 .subscribe(this._inMotionOperation$);
36730 this._inMotion$ = this._inMotionOperation$
36731 .distinctUntilChanged()
36734 this._inTranslationOperation$ = new Subject_1.Subject();
36736 .map(function (frame) {
36739 .subscribe(this._inTranslationOperation$);
36740 this._inTranslationOperation$
36741 .distinctUntilChanged()
36742 .filter(function (inTranslation) {
36743 return inTranslation;
36745 .switchMap(function (inTranslation) {
36746 return _this._currentState$
36747 .filter(function (frame) {
36748 return frame.state.nodesAhead === 0;
36750 .map(function (frame) {
36751 return frame.state.camera.position.clone();
36754 .map(function (pair) {
36755 return pair[0].distanceToSquared(pair[1]) !== 0;
36757 .first(function (changed) {
36761 .subscribe(this._inTranslationOperation$);
36762 this._inTranslation$ = this._inTranslationOperation$
36763 .distinctUntilChanged()
36766 this._state$.subscribe(function () { });
36767 this._currentNode$.subscribe(function () { });
36768 this._currentCamera$.subscribe(function () { });
36769 this._currentTransform$.subscribe(function () { });
36770 this._reference$.subscribe(function () { });
36771 this._currentNodeExternal$.subscribe(function () { });
36772 this._lastState$.subscribe(function () { });
36773 this._inMotion$.subscribe(function () { });
36774 this._inTranslation$.subscribe(function () { });
36775 this._frameId = null;
36776 this._frameGenerator = new AnimationFrame_1.RequestAnimationFrameDefinition(window);
36778 Object.defineProperty(StateService.prototype, "currentState$", {
36780 return this._currentState$;
36785 Object.defineProperty(StateService.prototype, "currentNode$", {
36787 return this._currentNode$;
36792 Object.defineProperty(StateService.prototype, "currentKey$", {
36794 return this._currentKey$;
36799 Object.defineProperty(StateService.prototype, "currentNodeExternal$", {
36801 return this._currentNodeExternal$;
36806 Object.defineProperty(StateService.prototype, "currentCamera$", {
36808 return this._currentCamera$;
36813 Object.defineProperty(StateService.prototype, "currentTransform$", {
36815 return this._currentTransform$;
36820 Object.defineProperty(StateService.prototype, "state$", {
36822 return this._state$;
36827 Object.defineProperty(StateService.prototype, "reference$", {
36829 return this._reference$;
36834 Object.defineProperty(StateService.prototype, "inMotion$", {
36836 return this._inMotion$;
36841 Object.defineProperty(StateService.prototype, "inTranslation$", {
36843 return this._inTranslation$;
36848 Object.defineProperty(StateService.prototype, "appendNode$", {
36850 return this._appendNode$;
36855 StateService.prototype.traverse = function () {
36856 this._inMotionOperation$.next(true);
36857 this._invokeContextOperation(function (context) { context.traverse(); });
36859 StateService.prototype.wait = function () {
36860 this._invokeContextOperation(function (context) { context.wait(); });
36862 StateService.prototype.appendNodes = function (nodes) {
36863 this._invokeContextOperation(function (context) { context.append(nodes); });
36865 StateService.prototype.prependNodes = function (nodes) {
36866 this._invokeContextOperation(function (context) { context.prepend(nodes); });
36868 StateService.prototype.removeNodes = function (n) {
36869 this._invokeContextOperation(function (context) { context.remove(n); });
36871 StateService.prototype.clearNodes = function () {
36872 this._invokeContextOperation(function (context) { context.clear(); });
36874 StateService.prototype.clearPriorNodes = function () {
36875 this._invokeContextOperation(function (context) { context.clearPrior(); });
36877 StateService.prototype.cutNodes = function () {
36878 this._invokeContextOperation(function (context) { context.cut(); });
36880 StateService.prototype.setNodes = function (nodes) {
36881 this._invokeContextOperation(function (context) { context.set(nodes); });
36883 StateService.prototype.rotate = function (delta) {
36884 this._inMotionOperation$.next(true);
36885 this._invokeContextOperation(function (context) { context.rotate(delta); });
36887 StateService.prototype.rotateBasic = function (basicRotation) {
36888 this._inMotionOperation$.next(true);
36889 this._invokeContextOperation(function (context) { context.rotateBasic(basicRotation); });
36891 StateService.prototype.rotateBasicUnbounded = function (basicRotation) {
36892 this._inMotionOperation$.next(true);
36893 this._invokeContextOperation(function (context) { context.rotateBasicUnbounded(basicRotation); });
36895 StateService.prototype.rotateToBasic = function (basic) {
36896 this._inMotionOperation$.next(true);
36897 this._invokeContextOperation(function (context) { context.rotateToBasic(basic); });
36899 StateService.prototype.move = function (delta) {
36900 this._inMotionOperation$.next(true);
36901 this._invokeContextOperation(function (context) { context.move(delta); });
36903 StateService.prototype.moveTo = function (position) {
36904 this._inMotionOperation$.next(true);
36905 this._invokeContextOperation(function (context) { context.moveTo(position); });
36908 * Change zoom level while keeping the reference point position approximately static.
36910 * @parameter {number} delta - Change in zoom level.
36911 * @parameter {Array<number>} reference - Reference point in basic coordinates.
36913 StateService.prototype.zoomIn = function (delta, reference) {
36914 this._inMotionOperation$.next(true);
36915 this._invokeContextOperation(function (context) { context.zoomIn(delta, reference); });
36917 StateService.prototype.getCenter = function () {
36918 return this._lastState$
36920 .map(function (frame) {
36921 return frame.state.getCenter();
36924 StateService.prototype.getZoom = function () {
36925 return this._lastState$
36927 .map(function (frame) {
36928 return frame.state.zoom;
36931 StateService.prototype.setCenter = function (center) {
36932 this._inMotionOperation$.next(true);
36933 this._invokeContextOperation(function (context) { context.setCenter(center); });
36935 StateService.prototype.setZoom = function (zoom) {
36936 this._inMotionOperation$.next(true);
36937 this._invokeContextOperation(function (context) { context.setZoom(zoom); });
36939 StateService.prototype.start = function () {
36940 if (this._frameId == null) {
36941 this._start$.next(null);
36942 this._frameId = this._frameGenerator.requestAnimationFrame(this._frame.bind(this));
36943 this._frame$.next(this._frameId);
36946 StateService.prototype.stop = function () {
36947 if (this._frameId != null) {
36948 this._frameGenerator.cancelAnimationFrame(this._frameId);
36949 this._frameId = null;
36952 StateService.prototype._invokeContextOperation = function (action) {
36953 this._contextOperation$
36954 .next(function (context) {
36959 StateService.prototype._frame = function (time) {
36960 this._frameId = this._frameGenerator.requestAnimationFrame(this._frame.bind(this));
36961 this._frame$.next(this._frameId);
36963 return StateService;
36965 exports.StateService = StateService;
36967 },{"../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}],334:[function(require,module,exports){
36969 /// <reference path="../../../typings/index.d.ts" />
36970 Object.defineProperty(exports, "__esModule", { value: true });
36971 var Error_1 = require("../../Error");
36972 var Geo_1 = require("../../Geo");
36973 var StateBase = (function () {
36974 function StateBase(state) {
36975 this._spatial = new Geo_1.Spatial();
36976 this._geoCoords = new Geo_1.GeoCoords();
36977 this._referenceThreshold = 0.01;
36978 this._reference = state.reference;
36979 this._alpha = state.alpha;
36980 this._camera = state.camera.clone();
36981 this._zoom = state.zoom;
36982 this._currentIndex = state.currentIndex;
36983 this._trajectory = state.trajectory.slice();
36984 this._trajectoryTransforms = [];
36985 this._trajectoryCameras = [];
36986 for (var _i = 0, _a = this._trajectory; _i < _a.length; _i++) {
36988 var translation = this._nodeToTranslation(node);
36989 var transform = new Geo_1.Transform(node, node.image, translation);
36990 this._trajectoryTransforms.push(transform);
36991 this._trajectoryCameras.push(new Geo_1.Camera(transform));
36993 this._currentNode = this._trajectory.length > 0 ?
36994 this._trajectory[this._currentIndex] :
36996 this._previousNode = this._trajectory.length > 1 && this.currentIndex > 0 ?
36997 this._trajectory[this._currentIndex - 1] :
36999 this._currentCamera = this._trajectoryCameras.length > 0 ?
37000 this._trajectoryCameras[this._currentIndex].clone() :
37001 new Geo_1.Camera();
37002 this._previousCamera = this._trajectoryCameras.length > 1 && this.currentIndex > 0 ?
37003 this._trajectoryCameras[this._currentIndex - 1].clone() :
37004 this._currentCamera.clone();
37006 Object.defineProperty(StateBase.prototype, "reference", {
37008 return this._reference;
37013 Object.defineProperty(StateBase.prototype, "alpha", {
37015 return this._getAlpha();
37020 Object.defineProperty(StateBase.prototype, "camera", {
37022 return this._camera;
37027 Object.defineProperty(StateBase.prototype, "zoom", {
37034 Object.defineProperty(StateBase.prototype, "trajectory", {
37036 return this._trajectory;
37041 Object.defineProperty(StateBase.prototype, "currentIndex", {
37043 return this._currentIndex;
37048 Object.defineProperty(StateBase.prototype, "currentNode", {
37050 return this._currentNode;
37055 Object.defineProperty(StateBase.prototype, "previousNode", {
37057 return this._previousNode;
37062 Object.defineProperty(StateBase.prototype, "currentCamera", {
37064 return this._currentCamera;
37069 Object.defineProperty(StateBase.prototype, "currentTransform", {
37071 return this._trajectoryTransforms.length > 0 ?
37072 this._trajectoryTransforms[this.currentIndex] : null;
37077 Object.defineProperty(StateBase.prototype, "previousTransform", {
37079 return this._trajectoryTransforms.length > 1 && this.currentIndex > 0 ?
37080 this._trajectoryTransforms[this.currentIndex - 1] : null;
37085 Object.defineProperty(StateBase.prototype, "motionless", {
37087 return this._motionless;
37092 StateBase.prototype.append = function (nodes) {
37093 if (nodes.length < 1) {
37094 throw Error("Trajectory can not be empty");
37096 if (this._currentIndex < 0) {
37100 this._trajectory = this._trajectory.concat(nodes);
37101 this._appendToTrajectories(nodes);
37104 StateBase.prototype.prepend = function (nodes) {
37105 if (nodes.length < 1) {
37106 throw Error("Trajectory can not be empty");
37108 this._trajectory = nodes.slice().concat(this._trajectory);
37109 this._currentIndex += nodes.length;
37110 this._setCurrentNode();
37111 var referenceReset = this._setReference(this._currentNode);
37112 if (referenceReset) {
37113 this._setTrajectories();
37116 this._prependToTrajectories(nodes);
37118 this._setCurrentCamera();
37120 StateBase.prototype.remove = function (n) {
37122 throw Error("n must be a positive integer");
37124 if (this._currentIndex - 1 < n) {
37125 throw Error("Current and previous nodes can not be removed");
37127 for (var i = 0; i < n; i++) {
37128 this._trajectory.shift();
37129 this._trajectoryTransforms.shift();
37130 this._trajectoryCameras.shift();
37131 this._currentIndex--;
37133 this._setCurrentNode();
37135 StateBase.prototype.clearPrior = function () {
37136 if (this._currentIndex > 0) {
37137 this.remove(this._currentIndex - 1);
37140 StateBase.prototype.clear = function () {
37142 if (this._currentIndex > 0) {
37143 this.remove(this._currentIndex - 1);
37146 StateBase.prototype.cut = function () {
37147 while (this._trajectory.length - 1 > this._currentIndex) {
37148 this._trajectory.pop();
37149 this._trajectoryTransforms.pop();
37150 this._trajectoryCameras.pop();
37153 StateBase.prototype.set = function (nodes) {
37154 this._setTrajectory(nodes);
37155 this._setCurrentNode();
37156 this._setReference(this._currentNode);
37157 this._setTrajectories();
37158 this._setCurrentCamera();
37160 StateBase.prototype.getCenter = function () {
37161 return this._currentNode != null ?
37162 this.currentTransform.projectBasic(this._camera.lookat.toArray()) :
37165 StateBase.prototype._setCurrent = function () {
37166 this._setCurrentNode();
37167 var referenceReset = this._setReference(this._currentNode);
37168 if (referenceReset) {
37169 this._setTrajectories();
37171 this._setCurrentCamera();
37173 StateBase.prototype._setCurrentCamera = function () {
37174 this._currentCamera = this._trajectoryCameras[this._currentIndex].clone();
37175 this._previousCamera = this._currentIndex > 0 ?
37176 this._trajectoryCameras[this._currentIndex - 1].clone() :
37177 this._currentCamera.clone();
37179 StateBase.prototype._motionlessTransition = function () {
37180 var nodesSet = this._currentNode != null && this._previousNode != null;
37181 return nodesSet && !(this._currentNode.merged &&
37182 this._previousNode.merged &&
37183 this._withinOriginalDistance() &&
37184 this._sameConnectedComponent());
37186 StateBase.prototype._setReference = function (node) {
37187 // do not reset reference if node is within threshold distance
37188 if (Math.abs(node.latLon.lat - this.reference.lat) < this._referenceThreshold &&
37189 Math.abs(node.latLon.lon - this.reference.lon) < this._referenceThreshold) {
37192 // do not reset reference if previous node exist and transition is with motion
37193 if (this._previousNode != null && !this._motionlessTransition()) {
37196 this._reference.lat = node.latLon.lat;
37197 this._reference.lon = node.latLon.lon;
37198 this._reference.alt = node.alt;
37201 StateBase.prototype._setCurrentNode = function () {
37202 this._currentNode = this._trajectory.length > 0 ?
37203 this._trajectory[this._currentIndex] :
37205 this._previousNode = this._currentIndex > 0 ?
37206 this._trajectory[this._currentIndex - 1] :
37209 StateBase.prototype._setTrajectory = function (nodes) {
37210 if (nodes.length < 1) {
37211 throw new Error_1.ArgumentMapillaryError("Trajectory can not be empty");
37213 if (this._currentNode != null) {
37214 this._trajectory = [this._currentNode].concat(nodes);
37215 this._currentIndex = 1;
37218 this._trajectory = nodes.slice();
37219 this._currentIndex = 0;
37222 StateBase.prototype._setTrajectories = function () {
37223 this._trajectoryTransforms.length = 0;
37224 this._trajectoryCameras.length = 0;
37225 this._appendToTrajectories(this._trajectory);
37227 StateBase.prototype._appendToTrajectories = function (nodes) {
37228 for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
37229 var node = nodes_1[_i];
37230 if (!node.assetsCached) {
37231 throw new Error_1.ArgumentMapillaryError("Assets must be cached when node is added to trajectory");
37233 var translation = this._nodeToTranslation(node);
37234 var transform = new Geo_1.Transform(node, node.image, translation);
37235 this._trajectoryTransforms.push(transform);
37236 this._trajectoryCameras.push(new Geo_1.Camera(transform));
37239 StateBase.prototype._prependToTrajectories = function (nodes) {
37240 for (var _i = 0, _a = nodes.reverse(); _i < _a.length; _i++) {
37242 if (!node.assetsCached) {
37243 throw new Error_1.ArgumentMapillaryError("Assets must be cached when added to trajectory");
37245 var translation = this._nodeToTranslation(node);
37246 var transform = new Geo_1.Transform(node, node.image, translation);
37247 this._trajectoryTransforms.unshift(transform);
37248 this._trajectoryCameras.unshift(new Geo_1.Camera(transform));
37251 StateBase.prototype._nodeToTranslation = function (node) {
37252 var C = this._geoCoords.geodeticToEnu(node.latLon.lat, node.latLon.lon, node.alt, this._reference.lat, this._reference.lon, this._reference.alt);
37253 var RC = this._spatial.rotate(C, node.rotation);
37254 return [-RC.x, -RC.y, -RC.z];
37256 StateBase.prototype._sameConnectedComponent = function () {
37257 var current = this._currentNode;
37258 var previous = this._previousNode;
37260 !current.mergeCC ||
37262 !previous.mergeCC) {
37265 return current.mergeCC === previous.mergeCC;
37267 StateBase.prototype._withinOriginalDistance = function () {
37268 var current = this._currentNode;
37269 var previous = this._previousNode;
37270 if (!current || !previous) {
37273 // 50 km/h moves 28m in 2s
37274 var distance = this._spatial.distanceFromLatLon(current.originalLatLon.lat, current.originalLatLon.lon, previous.originalLatLon.lat, previous.originalLatLon.lon);
37275 return distance < 25;
37279 exports.StateBase = StateBase;
37281 },{"../../Error":228,"../../Geo":229}],335:[function(require,module,exports){
37283 /// <reference path="../../../typings/index.d.ts" />
37284 var __extends = (this && this.__extends) || (function () {
37285 var extendStatics = Object.setPrototypeOf ||
37286 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
37287 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
37288 return function (d, b) {
37289 extendStatics(d, b);
37290 function __() { this.constructor = d; }
37291 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
37294 Object.defineProperty(exports, "__esModule", { value: true });
37295 var THREE = require("three");
37296 var UnitBezier = require("@mapbox/unitbezier");
37297 var State_1 = require("../../State");
37298 var RotationDelta = (function () {
37299 function RotationDelta(phi, theta) {
37301 this._theta = theta;
37303 Object.defineProperty(RotationDelta.prototype, "phi", {
37307 set: function (value) {
37313 Object.defineProperty(RotationDelta.prototype, "theta", {
37315 return this._theta;
37317 set: function (value) {
37318 this._theta = value;
37323 Object.defineProperty(RotationDelta.prototype, "isZero", {
37325 return this._phi === 0 && this._theta === 0;
37330 RotationDelta.prototype.copy = function (delta) {
37331 this._phi = delta.phi;
37332 this._theta = delta.theta;
37334 RotationDelta.prototype.lerp = function (other, alpha) {
37335 this._phi = (1 - alpha) * this._phi + alpha * other.phi;
37336 this._theta = (1 - alpha) * this._theta + alpha * other.theta;
37338 RotationDelta.prototype.multiply = function (value) {
37339 this._phi *= value;
37340 this._theta *= value;
37342 RotationDelta.prototype.threshold = function (value) {
37343 this._phi = Math.abs(this._phi) > value ? this._phi : 0;
37344 this._theta = Math.abs(this._theta) > value ? this._theta : 0;
37346 RotationDelta.prototype.lengthSquared = function () {
37347 return this._phi * this._phi + this._theta * this._theta;
37349 RotationDelta.prototype.reset = function () {
37353 return RotationDelta;
37355 var TraversingState = (function (_super) {
37356 __extends(TraversingState, _super);
37357 function TraversingState(state) {
37358 var _this = _super.call(this, state) || this;
37359 _this._adjustCameras();
37360 _this._motionless = _this._motionlessTransition();
37361 _this._baseAlpha = _this._alpha;
37362 _this._animationSpeed = 0.025;
37363 _this._unitBezier = new UnitBezier(0.74, 0.67, 0.38, 0.96);
37364 _this._useBezier = false;
37365 _this._rotationDelta = new RotationDelta(0, 0);
37366 _this._requestedRotationDelta = null;
37367 _this._basicRotation = [0, 0];
37368 _this._requestedBasicRotation = null;
37369 _this._requestedBasicRotationUnbounded = null;
37370 _this._rotationAcceleration = 0.86;
37371 _this._rotationIncreaseAlpha = 0.97;
37372 _this._rotationDecreaseAlpha = 0.9;
37373 _this._rotationThreshold = 1e-3;
37374 _this._unboundedRotationAlpha = 0.8;
37375 _this._desiredZoom = state.zoom;
37376 _this._minZoom = 0;
37377 _this._maxZoom = 3;
37378 _this._lookatDepth = 10;
37379 _this._desiredLookat = null;
37380 _this._desiredCenter = null;
37383 TraversingState.prototype.traverse = function () {
37384 throw new Error("Not implemented");
37386 TraversingState.prototype.wait = function () {
37387 return new State_1.WaitingState(this);
37389 TraversingState.prototype.append = function (nodes) {
37390 var emptyTrajectory = this._trajectory.length === 0;
37391 if (emptyTrajectory) {
37392 this._resetTransition();
37394 _super.prototype.append.call(this, nodes);
37395 if (emptyTrajectory) {
37396 this._setDesiredCenter();
37397 this._setDesiredZoom();
37400 TraversingState.prototype.prepend = function (nodes) {
37401 var emptyTrajectory = this._trajectory.length === 0;
37402 if (emptyTrajectory) {
37403 this._resetTransition();
37405 _super.prototype.prepend.call(this, nodes);
37406 if (emptyTrajectory) {
37407 this._setDesiredCenter();
37408 this._setDesiredZoom();
37411 TraversingState.prototype.set = function (nodes) {
37412 _super.prototype.set.call(this, nodes);
37413 this._desiredLookat = null;
37414 this._resetTransition();
37415 this._clearRotation();
37416 this._setDesiredCenter();
37417 this._setDesiredZoom();
37418 if (this._trajectory.length < 3) {
37419 this._useBezier = true;
37422 TraversingState.prototype.move = function (delta) {
37423 throw new Error("Not implemented");
37425 TraversingState.prototype.moveTo = function (delta) {
37426 throw new Error("Not implemented");
37428 TraversingState.prototype.rotate = function (rotationDelta) {
37429 if (this._currentNode == null) {
37432 this._desiredZoom = this._zoom;
37433 this._desiredLookat = null;
37434 this._requestedBasicRotation = null;
37435 if (this._requestedRotationDelta != null) {
37436 this._requestedRotationDelta.phi = this._requestedRotationDelta.phi + rotationDelta.phi;
37437 this._requestedRotationDelta.theta = this._requestedRotationDelta.theta + rotationDelta.theta;
37440 this._requestedRotationDelta = new RotationDelta(rotationDelta.phi, rotationDelta.theta);
37443 TraversingState.prototype.rotateBasic = function (basicRotation) {
37444 if (this._currentNode == null) {
37447 this._desiredZoom = this._zoom;
37448 this._desiredLookat = null;
37449 this._requestedRotationDelta = null;
37450 if (this._requestedBasicRotation != null) {
37451 this._requestedBasicRotation[0] += basicRotation[0];
37452 this._requestedBasicRotation[1] += basicRotation[1];
37453 var threshold = 0.05 / Math.pow(2, this._zoom);
37454 this._requestedBasicRotation[0] =
37455 this._spatial.clamp(this._requestedBasicRotation[0], -threshold, threshold);
37456 this._requestedBasicRotation[1] =
37457 this._spatial.clamp(this._requestedBasicRotation[1], -threshold, threshold);
37460 this._requestedBasicRotation = basicRotation.slice();
37463 TraversingState.prototype.rotateBasicUnbounded = function (basicRotation) {
37464 if (this._currentNode == null) {
37467 if (this._requestedBasicRotationUnbounded != null) {
37468 this._requestedBasicRotationUnbounded[0] += basicRotation[0];
37469 this._requestedBasicRotationUnbounded[1] += basicRotation[1];
37472 this._requestedBasicRotationUnbounded = basicRotation.slice();
37475 TraversingState.prototype.rotateToBasic = function (basic) {
37476 if (this._currentNode == null) {
37479 this._desiredZoom = this._zoom;
37480 this._desiredLookat = null;
37481 basic[0] = this._spatial.clamp(basic[0], 0, 1);
37482 basic[1] = this._spatial.clamp(basic[1], 0, 1);
37483 var lookat = this.currentTransform.unprojectBasic(basic, this._lookatDepth);
37484 this._currentCamera.lookat.fromArray(lookat);
37486 TraversingState.prototype.zoomIn = function (delta, reference) {
37487 if (this._currentNode == null) {
37490 this._desiredZoom = Math.max(this._minZoom, Math.min(this._maxZoom, this._desiredZoom + delta));
37491 var currentCenter = this.currentTransform.projectBasic(this._currentCamera.lookat.toArray());
37492 var currentCenterX = currentCenter[0];
37493 var currentCenterY = currentCenter[1];
37494 var zoom0 = Math.pow(2, this._zoom);
37495 var zoom1 = Math.pow(2, this._desiredZoom);
37496 var refX = reference[0];
37497 var refY = reference[1];
37498 if (this.currentTransform.gpano != null &&
37499 this.currentTransform.gpano.CroppedAreaImageWidthPixels === this.currentTransform.gpano.FullPanoWidthPixels) {
37500 if (refX - currentCenterX > 0.5) {
37503 else if (currentCenterX - refX > 0.5) {
37507 var newCenterX = refX - zoom0 / zoom1 * (refX - currentCenterX);
37508 var newCenterY = refY - zoom0 / zoom1 * (refY - currentCenterY);
37509 var gpano = this.currentTransform.gpano;
37510 if (this._currentNode.fullPano) {
37511 newCenterX = this._spatial.wrap(newCenterX + this._basicRotation[0], 0, 1);
37512 newCenterY = this._spatial.clamp(newCenterY + this._basicRotation[1], 0.05, 0.95);
37514 else if (gpano != null &&
37515 this.currentTransform.gpano.CroppedAreaImageWidthPixels === this.currentTransform.gpano.FullPanoWidthPixels) {
37516 newCenterX = this._spatial.wrap(newCenterX + this._basicRotation[0], 0, 1);
37517 newCenterY = this._spatial.clamp(newCenterY + this._basicRotation[1], 0, 1);
37520 newCenterX = this._spatial.clamp(newCenterX, 0, 1);
37521 newCenterY = this._spatial.clamp(newCenterY, 0, 1);
37523 this._desiredLookat = new THREE.Vector3()
37524 .fromArray(this.currentTransform.unprojectBasic([newCenterX, newCenterY], this._lookatDepth));
37526 TraversingState.prototype.setCenter = function (center) {
37527 this._desiredLookat = null;
37528 this._requestedRotationDelta = null;
37529 this._requestedBasicRotation = null;
37530 this._desiredZoom = this._zoom;
37532 this._spatial.clamp(center[0], 0, 1),
37533 this._spatial.clamp(center[1], 0, 1),
37535 if (this._currentNode == null) {
37536 this._desiredCenter = clamped;
37539 this._desiredCenter = null;
37540 var currentLookat = new THREE.Vector3()
37541 .fromArray(this.currentTransform.unprojectBasic(clamped, this._lookatDepth));
37542 var previousTransform = this.previousTransform != null ?
37543 this.previousTransform :
37544 this.currentTransform;
37545 var previousLookat = new THREE.Vector3()
37546 .fromArray(previousTransform.unprojectBasic(clamped, this._lookatDepth));
37547 this._currentCamera.lookat.copy(currentLookat);
37548 this._previousCamera.lookat.copy(previousLookat);
37550 TraversingState.prototype.setZoom = function (zoom) {
37551 this._desiredLookat = null;
37552 this._requestedRotationDelta = null;
37553 this._requestedBasicRotation = null;
37554 this._zoom = this._spatial.clamp(zoom, this._minZoom, this._maxZoom);
37555 this._desiredZoom = this._zoom;
37557 TraversingState.prototype.update = function (fps) {
37558 if (this._alpha === 1 && this._currentIndex + this._alpha < this._trajectory.length) {
37559 this._currentIndex += 1;
37560 this._useBezier = this._trajectory.length < 3 &&
37561 this._currentIndex + 1 === this._trajectory.length;
37562 this._setCurrent();
37563 this._resetTransition();
37564 this._clearRotation();
37565 this._desiredZoom = this._currentNode.fullPano ? this._zoom : 0;
37566 this._desiredLookat = null;
37568 var animationSpeed = this._animationSpeed * (60 / fps);
37569 this._baseAlpha = Math.min(1, this._baseAlpha + animationSpeed);
37570 if (this._useBezier) {
37571 this._alpha = this._unitBezier.solve(this._baseAlpha);
37574 this._alpha = this._baseAlpha;
37576 this._updateRotation();
37577 if (!this._rotationDelta.isZero) {
37578 this._applyRotation(this._previousCamera);
37579 this._applyRotation(this._currentCamera);
37581 this._updateRotationBasic();
37582 if (this._basicRotation[0] !== 0 || this._basicRotation[1] !== 0) {
37583 this._applyRotationBasic();
37585 this._updateZoom(animationSpeed);
37586 this._updateLookat(animationSpeed);
37587 this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha);
37589 TraversingState.prototype._getAlpha = function () {
37590 return this._motionless ? Math.ceil(this._alpha) : this._alpha;
37592 TraversingState.prototype._setCurrentCamera = function () {
37593 _super.prototype._setCurrentCamera.call(this);
37594 this._adjustCameras();
37596 TraversingState.prototype._adjustCameras = function () {
37597 if (this._previousNode == null) {
37600 var lookat = this._camera.lookat.clone().sub(this._camera.position);
37601 this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position));
37602 if (this._currentNode.fullPano) {
37603 this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position));
37606 TraversingState.prototype._resetTransition = function () {
37608 this._baseAlpha = 0;
37609 this._motionless = this._motionlessTransition();
37611 TraversingState.prototype._applyRotation = function (camera) {
37612 if (camera == null) {
37615 var q = new THREE.Quaternion().setFromUnitVectors(camera.up, new THREE.Vector3(0, 0, 1));
37616 var qInverse = q.clone().inverse();
37617 var offset = new THREE.Vector3();
37618 offset.copy(camera.lookat).sub(camera.position);
37619 offset.applyQuaternion(q);
37620 var length = offset.length();
37621 var phi = Math.atan2(offset.y, offset.x);
37622 phi += this._rotationDelta.phi;
37623 var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z);
37624 theta += this._rotationDelta.theta;
37625 theta = Math.max(0.1, Math.min(Math.PI - 0.1, theta));
37626 offset.x = Math.sin(theta) * Math.cos(phi);
37627 offset.y = Math.sin(theta) * Math.sin(phi);
37628 offset.z = Math.cos(theta);
37629 offset.applyQuaternion(qInverse);
37630 camera.lookat.copy(camera.position).add(offset.multiplyScalar(length));
37632 TraversingState.prototype._applyRotationBasic = function () {
37633 var currentNode = this._currentNode;
37634 var previousNode = this._previousNode != null ?
37635 this.previousNode :
37637 var currentCamera = this._currentCamera;
37638 var previousCamera = this._previousCamera;
37639 var currentTransform = this.currentTransform;
37640 var previousTransform = this.previousTransform != null ?
37641 this.previousTransform :
37642 this.currentTransform;
37643 var currentBasic = currentTransform.projectBasic(currentCamera.lookat.toArray());
37644 var previousBasic = previousTransform.projectBasic(previousCamera.lookat.toArray());
37645 var currentGPano = currentTransform.gpano;
37646 var previousGPano = previousTransform.gpano;
37647 if (currentNode.fullPano) {
37648 currentBasic[0] = this._spatial.wrap(currentBasic[0] + this._basicRotation[0], 0, 1);
37649 currentBasic[1] = this._spatial.clamp(currentBasic[1] + this._basicRotation[1], 0.05, 0.95);
37651 else if (currentGPano != null &&
37652 currentTransform.gpano.CroppedAreaImageWidthPixels === currentTransform.gpano.FullPanoWidthPixels) {
37653 currentBasic[0] = this._spatial.wrap(currentBasic[0] + this._basicRotation[0], 0, 1);
37654 currentBasic[1] = this._spatial.clamp(currentBasic[1] + this._basicRotation[1], 0, 1);
37657 currentBasic[0] = this._spatial.clamp(currentBasic[0] + this._basicRotation[0], 0, 1);
37658 currentBasic[1] = this._spatial.clamp(currentBasic[1] + this._basicRotation[1], 0, 1);
37660 if (previousNode.fullPano) {
37661 previousBasic[0] = this._spatial.wrap(previousBasic[0] + this._basicRotation[0], 0, 1);
37662 previousBasic[1] = this._spatial.clamp(previousBasic[1] + this._basicRotation[1], 0.05, 0.95);
37664 else if (previousGPano != null &&
37665 previousTransform.gpano.CroppedAreaImageWidthPixels === previousTransform.gpano.FullPanoWidthPixels) {
37666 previousBasic[0] = this._spatial.wrap(previousBasic[0] + this._basicRotation[0], 0, 1);
37667 previousBasic[1] = this._spatial.clamp(previousBasic[1] + this._basicRotation[1], 0, 1);
37670 previousBasic[0] = this._spatial.clamp(previousBasic[0] + this._basicRotation[0], 0, 1);
37671 previousBasic[1] = this._spatial.clamp(currentBasic[1] + this._basicRotation[1], 0, 1);
37673 var currentLookat = currentTransform.unprojectBasic(currentBasic, this._lookatDepth);
37674 currentCamera.lookat.fromArray(currentLookat);
37675 var previousLookat = previousTransform.unprojectBasic(previousBasic, this._lookatDepth);
37676 previousCamera.lookat.fromArray(previousLookat);
37678 TraversingState.prototype._updateZoom = function (animationSpeed) {
37679 var diff = this._desiredZoom - this._zoom;
37680 var sign = diff > 0 ? 1 : diff < 0 ? -1 : 0;
37684 else if (Math.abs(diff) < 2e-3) {
37685 this._zoom = this._desiredZoom;
37686 if (this._desiredLookat != null) {
37687 this._desiredLookat = null;
37691 this._zoom += sign * Math.max(Math.abs(5 * animationSpeed * diff), 2e-3);
37694 TraversingState.prototype._updateLookat = function (animationSpeed) {
37695 if (this._desiredLookat === null) {
37698 var diff = this._desiredLookat.distanceToSquared(this._currentCamera.lookat);
37699 if (Math.abs(diff) < 1e-6) {
37700 this._currentCamera.lookat.copy(this._desiredLookat);
37701 this._desiredLookat = null;
37704 this._currentCamera.lookat.lerp(this._desiredLookat, 5 * animationSpeed);
37707 TraversingState.prototype._updateRotation = function () {
37708 if (this._requestedRotationDelta != null) {
37709 var length_1 = this._rotationDelta.lengthSquared();
37710 var requestedLength = this._requestedRotationDelta.lengthSquared();
37711 if (requestedLength > length_1) {
37712 this._rotationDelta.lerp(this._requestedRotationDelta, this._rotationIncreaseAlpha);
37715 this._rotationDelta.lerp(this._requestedRotationDelta, this._rotationDecreaseAlpha);
37717 this._requestedRotationDelta = null;
37720 if (this._rotationDelta.isZero) {
37723 this._rotationDelta.multiply(this._rotationAcceleration);
37724 this._rotationDelta.threshold(this._rotationThreshold);
37726 TraversingState.prototype._updateRotationBasic = function () {
37727 if (this._requestedBasicRotation != null) {
37728 var x = this._basicRotation[0];
37729 var y = this._basicRotation[1];
37730 var reqX = this._requestedBasicRotation[0];
37731 var reqY = this._requestedBasicRotation[1];
37732 if (Math.abs(reqX) > Math.abs(x)) {
37733 this._basicRotation[0] = (1 - this._rotationIncreaseAlpha) * x + this._rotationIncreaseAlpha * reqX;
37736 this._basicRotation[0] = (1 - this._rotationDecreaseAlpha) * x + this._rotationDecreaseAlpha * reqX;
37738 if (Math.abs(reqY) > Math.abs(y)) {
37739 this._basicRotation[1] = (1 - this._rotationIncreaseAlpha) * y + this._rotationIncreaseAlpha * reqY;
37742 this._basicRotation[1] = (1 - this._rotationDecreaseAlpha) * y + this._rotationDecreaseAlpha * reqY;
37744 this._requestedBasicRotation = null;
37747 if (this._requestedBasicRotationUnbounded != null) {
37748 var reqX = this._requestedBasicRotationUnbounded[0];
37749 var reqY = this._requestedBasicRotationUnbounded[1];
37750 if (Math.abs(reqX) > 0) {
37751 this._basicRotation[0] = (1 - this._unboundedRotationAlpha) * this._basicRotation[0] + this._unboundedRotationAlpha * reqX;
37753 if (Math.abs(reqY) > 0) {
37754 this._basicRotation[1] = (1 - this._unboundedRotationAlpha) * this._basicRotation[1] + this._unboundedRotationAlpha * reqY;
37756 if (this._desiredLookat != null) {
37757 var desiredBasicLookat = this.currentTransform.projectBasic(this._desiredLookat.toArray());
37758 desiredBasicLookat[0] += reqX;
37759 desiredBasicLookat[1] += reqY;
37760 this._desiredLookat = new THREE.Vector3()
37761 .fromArray(this.currentTransform.unprojectBasic(desiredBasicLookat, this._lookatDepth));
37763 this._requestedBasicRotationUnbounded = null;
37765 if (this._basicRotation[0] === 0 && this._basicRotation[1] === 0) {
37768 this._basicRotation[0] = this._rotationAcceleration * this._basicRotation[0];
37769 this._basicRotation[1] = this._rotationAcceleration * this._basicRotation[1];
37770 if (Math.abs(this._basicRotation[0]) < this._rotationThreshold / Math.pow(2, this._zoom) &&
37771 Math.abs(this._basicRotation[1]) < this._rotationThreshold / Math.pow(2, this._zoom)) {
37772 this._basicRotation = [0, 0];
37775 TraversingState.prototype._clearRotation = function () {
37776 if (this._currentNode.fullPano) {
37779 if (this._requestedRotationDelta != null) {
37780 this._requestedRotationDelta = null;
37782 if (!this._rotationDelta.isZero) {
37783 this._rotationDelta.reset();
37785 if (this._requestedBasicRotation != null) {
37786 this._requestedBasicRotation = null;
37788 if (this._basicRotation[0] > 0 || this._basicRotation[1] > 0) {
37789 this._basicRotation = [0, 0];
37792 TraversingState.prototype._setDesiredCenter = function () {
37793 if (this._desiredCenter == null) {
37796 var lookatDirection = new THREE.Vector3()
37797 .fromArray(this.currentTransform.unprojectBasic(this._desiredCenter, this._lookatDepth))
37798 .sub(this._currentCamera.position);
37799 this._currentCamera.lookat.copy(this._currentCamera.position.clone().add(lookatDirection));
37800 this._previousCamera.lookat.copy(this._previousCamera.position.clone().add(lookatDirection));
37801 this._desiredCenter = null;
37803 TraversingState.prototype._setDesiredZoom = function () {
37804 this._desiredZoom =
37805 this._currentNode.fullPano || this._previousNode == null ?
37808 return TraversingState;
37809 }(State_1.StateBase));
37810 exports.TraversingState = TraversingState;
37812 },{"../../State":233,"@mapbox/unitbezier":2,"three":176}],336:[function(require,module,exports){
37814 var __extends = (this && this.__extends) || (function () {
37815 var extendStatics = Object.setPrototypeOf ||
37816 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
37817 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
37818 return function (d, b) {
37819 extendStatics(d, b);
37820 function __() { this.constructor = d; }
37821 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
37824 Object.defineProperty(exports, "__esModule", { value: true });
37825 var State_1 = require("../../State");
37826 var WaitingState = (function (_super) {
37827 __extends(WaitingState, _super);
37828 function WaitingState(state) {
37829 var _this = _super.call(this, state) || this;
37831 _this._adjustCameras();
37832 _this._motionless = _this._motionlessTransition();
37835 WaitingState.prototype.traverse = function () {
37836 return new State_1.TraversingState(this);
37838 WaitingState.prototype.wait = function () {
37839 throw new Error("Not implemented");
37841 WaitingState.prototype.prepend = function (nodes) {
37842 _super.prototype.prepend.call(this, nodes);
37843 this._motionless = this._motionlessTransition();
37845 WaitingState.prototype.set = function (nodes) {
37846 _super.prototype.set.call(this, nodes);
37847 this._motionless = this._motionlessTransition();
37849 WaitingState.prototype.rotate = function (delta) { return; };
37850 WaitingState.prototype.rotateBasic = function (basicRotation) { return; };
37851 WaitingState.prototype.rotateBasicUnbounded = function (basicRotation) { return; };
37852 WaitingState.prototype.rotateToBasic = function (basic) { return; };
37853 WaitingState.prototype.zoomIn = function (delta, reference) { return; };
37854 WaitingState.prototype.move = function (delta) {
37855 this._alpha = Math.max(0, Math.min(1, this._alpha + delta));
37857 WaitingState.prototype.moveTo = function (position) {
37858 this._alpha = Math.max(0, Math.min(1, position));
37860 WaitingState.prototype.update = function (fps) {
37861 this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha);
37863 WaitingState.prototype.setCenter = function (center) { return; };
37864 WaitingState.prototype.setZoom = function (zoom) { return; };
37865 WaitingState.prototype._getAlpha = function () {
37866 return this._motionless ? Math.round(this._alpha) : this._alpha;
37868 WaitingState.prototype._setCurrentCamera = function () {
37869 _super.prototype._setCurrentCamera.call(this);
37870 this._adjustCameras();
37872 WaitingState.prototype._adjustCameras = function () {
37873 if (this._previousNode == null) {
37876 if (this._currentNode.fullPano) {
37877 var lookat = this._camera.lookat.clone().sub(this._camera.position);
37878 this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position));
37880 if (this._previousNode.fullPano) {
37881 var lookat = this._currentCamera.lookat.clone().sub(this._currentCamera.position);
37882 this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position));
37885 return WaitingState;
37886 }(State_1.StateBase));
37887 exports.WaitingState = WaitingState;
37889 },{"../../State":233}],337:[function(require,module,exports){
37891 Object.defineProperty(exports, "__esModule", { value: true });
37892 var Observable_1 = require("rxjs/Observable");
37894 * @class ImageTileLoader
37896 * @classdesc Represents a loader of image tiles.
37898 var ImageTileLoader = (function () {
37900 * Create a new node image tile loader instance.
37902 * @param {string} scheme - The URI scheme.
37903 * @param {string} host - The URI host.
37904 * @param {string} [origin] - The origin query param.
37906 function ImageTileLoader(scheme, host, origin) {
37907 this._scheme = scheme;
37909 this._origin = origin != null ? "?origin=" + origin : "";
37912 * Retrieve an image tile.
37914 * @description Retrieve an image tile by specifying the area
37915 * as well as the scaled size.
37917 * @param {string} identifier - The identifier of the image.
37918 * @param {number} x - The top left x pixel coordinate for the tile
37919 * in the original image.
37920 * @param {number} y - The top left y pixel coordinate for the tile
37921 * in the original image.
37922 * @param {number} w - The pixel width of the tile in the original image.
37923 * @param {number} h - The pixel height of the tile in the original image.
37924 * @param {number} scaledW - The scaled width of the returned tile.
37925 * @param {number} scaledH - The scaled height of the returned tile.
37927 ImageTileLoader.prototype.getTile = function (identifier, x, y, w, h, scaledW, scaledH) {
37928 var characteristics = "/" + identifier + "/" + x + "," + y + "," + w + "," + h + "/" + scaledW + "," + scaledH + "/0/default.jpg";
37929 var url = this._scheme +
37934 var xmlHTTP = null;
37935 return [Observable_1.Observable.create(function (subscriber) {
37936 xmlHTTP = new XMLHttpRequest();
37937 xmlHTTP.open("GET", url, true);
37938 xmlHTTP.responseType = "arraybuffer";
37939 xmlHTTP.timeout = 15000;
37940 xmlHTTP.onload = function (event) {
37941 if (xmlHTTP.status !== 200) {
37942 subscriber.error(new Error("Failed to fetch tile (" + identifier + ": " + x + "," + y + "," + w + "," + h + "). " +
37943 ("Status: " + xmlHTTP.status + ", " + xmlHTTP.statusText)));
37946 var image = new Image();
37947 image.crossOrigin = "Anonymous";
37948 image.onload = function (e) {
37949 subscriber.next(image);
37950 subscriber.complete();
37952 image.onerror = function (error) {
37953 subscriber.error(new Error("Failed to load tile image (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
37955 var blob = new Blob([xmlHTTP.response]);
37956 image.src = window.URL.createObjectURL(blob);
37958 xmlHTTP.onerror = function (error) {
37959 subscriber.error(new Error("Failed to fetch tile (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
37961 xmlHTTP.ontimeout = function (error) {
37962 subscriber.error(new Error("Tile request timed out (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
37964 xmlHTTP.onabort = function (event) {
37965 subscriber.error(new Error("Tile request was aborted (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
37967 xmlHTTP.send(null);
37970 if (xmlHTTP != null) {
37976 return ImageTileLoader;
37978 exports.ImageTileLoader = ImageTileLoader;
37979 exports.default = ImageTileLoader;
37981 },{"rxjs/Observable":29}],338:[function(require,module,exports){
37983 Object.defineProperty(exports, "__esModule", { value: true });
37985 * @class ImageTileStore
37987 * @classdesc Represents a store for image tiles.
37989 var ImageTileStore = (function () {
37991 * Create a new node image tile store instance.
37993 function ImageTileStore() {
37997 * Add an image tile to the store.
37999 * @param {HTMLImageElement} image - The image tile.
38000 * @param {string} key - The identifier for the tile.
38001 * @param {number} level - The level of the tile.
38003 ImageTileStore.prototype.addImage = function (image, key, level) {
38004 if (!(level in this._images)) {
38005 this._images[level] = {};
38007 this._images[level][key] = image;
38010 * Dispose the store.
38012 * @description Disposes all cached assets.
38014 ImageTileStore.prototype.dispose = function () {
38015 for (var _i = 0, _a = Object.keys(this._images); _i < _a.length; _i++) {
38016 var level = _a[_i];
38017 var levelImages = this._images[level];
38018 for (var _b = 0, _c = Object.keys(levelImages); _b < _c.length; _b++) {
38020 window.URL.revokeObjectURL(levelImages[key].src);
38021 delete levelImages[key];
38023 delete this._images[level];
38027 * Get an image tile from the store.
38029 * @param {string} key - The identifier for the tile.
38030 * @param {number} level - The level of the tile.
38032 ImageTileStore.prototype.getImage = function (key, level) {
38033 return this._images[level][key];
38036 * Check if an image tile exist in the store.
38038 * @param {string} key - The identifier for the tile.
38039 * @param {number} level - The level of the tile.
38041 ImageTileStore.prototype.hasImage = function (key, level) {
38042 return level in this._images && key in this._images[level];
38044 return ImageTileStore;
38046 exports.ImageTileStore = ImageTileStore;
38047 exports.default = ImageTileStore;
38049 },{}],339:[function(require,module,exports){
38051 /// <reference path="../../typings/index.d.ts" />
38052 Object.defineProperty(exports, "__esModule", { value: true });
38053 var Geo_1 = require("../Geo");
38055 * @class RegionOfInterestCalculator
38057 * @classdesc Represents a calculator for regions of interest.
38059 var RegionOfInterestCalculator = (function () {
38060 function RegionOfInterestCalculator() {
38061 this._viewportCoords = new Geo_1.ViewportCoords();
38064 * Compute a region of interest based on the current render camera
38065 * and the viewport size.
38067 * @param {RenderCamera} renderCamera - Render camera used for unprojections.
38068 * @param {ISize} size - Viewport size in pixels.
38069 * @param {Transform} transform - Transform used for projections.
38071 * @returns {IRegionOfInterest} A region of interest.
38073 RegionOfInterestCalculator.prototype.computeRegionOfInterest = function (renderCamera, size, transform) {
38074 var viewportBoundaryPoints = this._viewportBoundaryPoints(4);
38075 var bbox = this._viewportPointsBoundingBox(viewportBoundaryPoints, renderCamera, transform);
38076 this._clipBoundingBox(bbox);
38077 var viewportPixelWidth = 2 / size.width;
38078 var viewportPixelHeight = 2 / size.height;
38079 var centralViewportPixel = [
38080 [-0.5 * viewportPixelWidth, 0.5 * viewportPixelHeight],
38081 [0.5 * viewportPixelWidth, 0.5 * viewportPixelHeight],
38082 [0.5 * viewportPixelWidth, -0.5 * viewportPixelHeight],
38083 [-0.5 * viewportPixelWidth, -0.5 * viewportPixelHeight],
38085 var cpbox = this._viewportPointsBoundingBox(centralViewportPixel, renderCamera, transform);
38088 pixelHeight: cpbox.maxY - cpbox.minY,
38089 pixelWidth: cpbox.maxX - cpbox.minX + (cpbox.minX < cpbox.maxX ? 0 : 1),
38092 RegionOfInterestCalculator.prototype._viewportBoundaryPoints = function (pointsPerSide) {
38094 var os = [[-1, 1], [1, 1], [1, -1], [-1, -1]];
38095 var ds = [[2, 0], [0, -2], [-2, 0], [0, 2]];
38096 for (var side = 0; side < 4; ++side) {
38099 for (var i = 0; i < pointsPerSide; ++i) {
38100 points.push([o[0] + d[0] * i / pointsPerSide,
38101 o[1] + d[1] * i / pointsPerSide]);
38106 RegionOfInterestCalculator.prototype._viewportPointsBoundingBox = function (viewportPoints, renderCamera, transform) {
38108 var basicPoints = viewportPoints
38109 .map(function (point) {
38110 return _this._viewportCoords
38111 .viewportToBasic(point[0], point[1], transform, renderCamera.perspective);
38113 if (transform.gpano != null) {
38114 return this._boundingBoxPano(basicPoints);
38117 return this._boundingBox(basicPoints);
38120 RegionOfInterestCalculator.prototype._boundingBox = function (points) {
38122 maxX: Number.NEGATIVE_INFINITY,
38123 maxY: Number.NEGATIVE_INFINITY,
38124 minX: Number.POSITIVE_INFINITY,
38125 minY: Number.POSITIVE_INFINITY,
38127 for (var i = 0; i < points.length; ++i) {
38128 bbox.minX = Math.min(bbox.minX, points[i][0]);
38129 bbox.maxX = Math.max(bbox.maxX, points[i][0]);
38130 bbox.minY = Math.min(bbox.minY, points[i][1]);
38131 bbox.maxY = Math.max(bbox.maxY, points[i][1]);
38135 RegionOfInterestCalculator.prototype._boundingBoxPano = function (points) {
38139 for (var i = 0; i < points.length; ++i) {
38140 xs.push(points[i][0]);
38141 ys.push(points[i][1]);
38143 xs.sort(function (a, b) { return _this._sign(a - b); });
38144 ys.sort(function (a, b) { return _this._sign(a - b); });
38145 var intervalX = this._intervalPano(xs);
38147 maxX: intervalX[1],
38148 maxY: ys[ys.length - 1],
38149 minX: intervalX[0],
38154 * Find the max interval between consecutive numbers.
38155 * Assumes numbers are between 0 and 1, sorted and that
38156 * x is equivalent to x + 1.
38158 RegionOfInterestCalculator.prototype._intervalPano = function (xs) {
38161 for (var i = 0; i < xs.length - 1; ++i) {
38162 var dx = xs[i + 1] - xs[i];
38168 var loopdx = xs[0] + 1 - xs[xs.length - 1];
38169 if (loopdx > maxdx) {
38170 return [xs[0], xs[xs.length - 1]];
38173 return [xs[maxi + 1], xs[maxi]];
38176 RegionOfInterestCalculator.prototype._clipBoundingBox = function (bbox) {
38177 bbox.minX = Math.max(0, Math.min(1, bbox.minX));
38178 bbox.maxX = Math.max(0, Math.min(1, bbox.maxX));
38179 bbox.minY = Math.max(0, Math.min(1, bbox.minY));
38180 bbox.maxY = Math.max(0, Math.min(1, bbox.maxY));
38182 RegionOfInterestCalculator.prototype._sign = function (n) {
38183 return n > 0 ? 1 : n < 0 ? -1 : 0;
38185 return RegionOfInterestCalculator;
38187 exports.RegionOfInterestCalculator = RegionOfInterestCalculator;
38188 exports.default = RegionOfInterestCalculator;
38190 },{"../Geo":229}],340:[function(require,module,exports){
38192 /// <reference path="../../typings/index.d.ts" />
38193 Object.defineProperty(exports, "__esModule", { value: true });
38194 var THREE = require("three");
38195 var Subject_1 = require("rxjs/Subject");
38197 * @class TextureProvider
38199 * @classdesc Represents a provider of textures.
38201 var TextureProvider = (function () {
38203 * Create a new node texture provider instance.
38205 * @param {string} key - The identifier of the image for which to request tiles.
38206 * @param {number} width - The full width of the original image.
38207 * @param {number} height - The full height of the original image.
38208 * @param {number} tileSize - The size used when requesting tiles.
38209 * @param {HTMLImageElement} background - Image to use as background.
38210 * @param {ImageTileLoader} imageTileLoader - Loader for retrieving tiles.
38211 * @param {ImageTileStore} imageTileStore - Store for saving tiles.
38212 * @param {THREE.WebGLRenderer} renderer - Renderer used for rendering tiles to texture.
38214 function TextureProvider(key, width, height, tileSize, background, imageTileLoader, imageTileStore, renderer) {
38215 this._disposed = false;
38217 if (width <= 0 || height <= 0) {
38218 console.warn("Original image size (" + width + ", " + height + ") is invalid (" + key + "). Tiles will not be loaded.");
38220 this._width = width;
38221 this._height = height;
38222 this._maxLevel = Math.ceil(Math.log(Math.max(height, width)) / Math.log(2));
38223 this._currentLevel = -1;
38224 this._tileSize = tileSize;
38225 this._updated$ = new Subject_1.Subject();
38226 this._createdSubject$ = new Subject_1.Subject();
38227 this._created$ = this._createdSubject$
38230 this._createdSubscription = this._created$.subscribe(function () { });
38231 this._hasSubject$ = new Subject_1.Subject();
38232 this._has$ = this._hasSubject$
38236 this._hasSubscription = this._has$.subscribe(function () { });
38237 this._abortFunctions = [];
38238 this._tileSubscriptions = {};
38239 this._renderedCurrentLevelTiles = {};
38240 this._renderedTiles = {};
38241 this._background = background;
38242 this._camera = null;
38243 this._imageTileLoader = imageTileLoader;
38244 this._imageTileStore = imageTileStore;
38245 this._renderer = renderer;
38246 this._renderTarget = null;
38249 Object.defineProperty(TextureProvider.prototype, "disposed", {
38253 * @returns {boolean} Value indicating whether provider has
38257 return this._disposed;
38262 Object.defineProperty(TextureProvider.prototype, "hasTexture$", {
38266 * @returns {Observable<boolean>} Observable emitting
38267 * values indicating when the existance of a texture
38276 Object.defineProperty(TextureProvider.prototype, "key", {
38280 * @returns {boolean} The identifier of the image for
38281 * which to render textures.
38289 Object.defineProperty(TextureProvider.prototype, "textureUpdated$", {
38291 * Get textureUpdated$.
38293 * @returns {Observable<boolean>} Observable emitting
38294 * values when an existing texture has been updated.
38297 return this._updated$;
38302 Object.defineProperty(TextureProvider.prototype, "textureCreated$", {
38304 * Get textureCreated$.
38306 * @returns {Observable<boolean>} Observable emitting
38307 * values when a new texture has been created.
38310 return this._created$;
38316 * Abort all outstanding image tile requests.
38318 TextureProvider.prototype.abort = function () {
38319 for (var key in this._tileSubscriptions) {
38320 if (!this._tileSubscriptions.hasOwnProperty(key)) {
38323 this._tileSubscriptions[key].unsubscribe();
38325 this._tileSubscriptions = {};
38326 for (var _i = 0, _a = this._abortFunctions; _i < _a.length; _i++) {
38327 var abort = _a[_i];
38330 this._abortFunctions = [];
38333 * Dispose the provider.
38335 * @description Disposes all cached assets and
38336 * aborts all outstanding image tile requests.
38338 TextureProvider.prototype.dispose = function () {
38339 if (this._disposed) {
38340 console.warn("Texture already disposed (" + this._key + ")");
38344 if (this._renderTarget != null) {
38345 this._renderTarget.dispose();
38346 this._renderTarget = null;
38348 this._imageTileStore.dispose();
38349 this._imageTileStore = null;
38350 this._background = null;
38351 this._camera = null;
38352 this._imageTileLoader = null;
38353 this._renderer = null;
38355 this._createdSubscription.unsubscribe();
38356 this._hasSubscription.unsubscribe();
38357 this._disposed = true;
38360 * Set the region of interest.
38362 * @description When the region of interest is set the
38363 * the tile level is determined and tiles for the region
38364 * are fetched from the store or the loader and renderedLevel
38367 * @param {IRegionOfInterest} roi - Spatial edges to cache.
38369 TextureProvider.prototype.setRegionOfInterest = function (roi) {
38370 if (this._width <= 0 || this._height <= 0) {
38374 var width = 1 / this._roi.pixelWidth;
38375 var height = 1 / this._roi.pixelHeight;
38376 var size = Math.max(height, width);
38377 var currentLevel = Math.max(0, Math.min(this._maxLevel, Math.round(Math.log(size) / Math.log(2) + 0.25)));
38378 if (currentLevel !== this._currentLevel) {
38380 this._currentLevel = currentLevel;
38381 if (!(this._currentLevel in this._renderedTiles)) {
38382 this._renderedTiles[this._currentLevel] = [];
38384 this._renderedCurrentLevelTiles = {};
38385 for (var _i = 0, _a = this._renderedTiles[this._currentLevel]; _i < _a.length; _i++) {
38387 this._renderedCurrentLevelTiles[this._tileKey(tile)] = true;
38390 var topLeft = this._getTileCoords([this._roi.bbox.minX, this._roi.bbox.minY]);
38391 var bottomRight = this._getTileCoords([this._roi.bbox.maxX, this._roi.bbox.maxY]);
38392 var tiles = this._getTiles(topLeft, bottomRight);
38393 if (this._camera == null) {
38394 this._camera = new THREE.OrthographicCamera(-this._width / 2, this._width / 2, this._height / 2, -this._height / 2, -1, 1);
38395 this._camera.position.z = 1;
38396 var gl = this._renderer.getContext();
38397 var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
38398 var backgroundSize = Math.max(this._width, this._height);
38399 var scale = maxTextureSize > backgroundSize ? 1 : maxTextureSize / backgroundSize;
38400 var targetWidth = Math.floor(scale * this._width);
38401 var targetHeight = Math.floor(scale * this._height);
38402 this._renderTarget = new THREE.WebGLRenderTarget(targetWidth, targetHeight, {
38403 depthBuffer: false,
38404 format: THREE.RGBFormat,
38405 magFilter: THREE.LinearFilter,
38406 minFilter: THREE.LinearFilter,
38407 stencilBuffer: false,
38409 this._renderToTarget(0, 0, this._width, this._height, this._background);
38410 this._createdSubject$.next(this._renderTarget.texture);
38411 this._hasSubject$.next(true);
38413 this._fetchTiles(tiles);
38416 * Update the image used as background for the texture.
38418 * @param {HTMLImageElement} background - The background image.
38420 TextureProvider.prototype.updateBackground = function (background) {
38421 this._background = background;
38424 * Retrieve an image tile.
38426 * @description Retrieve an image tile and render it to the
38427 * texture. Add the tile to the store and emit to the updated
38430 * @param {Array<number>} tile - The tile coordinates.
38431 * @param {number} level - The tile level.
38432 * @param {number} x - The top left x pixel coordinate of the tile.
38433 * @param {number} y - The top left y pixel coordinate of the tile.
38434 * @param {number} w - The pixel width of the tile.
38435 * @param {number} h - The pixel height of the tile.
38436 * @param {number} scaledW - The scaled width of the returned tile.
38437 * @param {number} scaledH - The scaled height of the returned tile.
38439 TextureProvider.prototype._fetchTile = function (tile, level, x, y, w, h, scaledX, scaledY) {
38441 var getTile = this._imageTileLoader.getTile(this._key, x, y, w, h, scaledX, scaledY);
38442 var tile$ = getTile[0];
38443 var abort = getTile[1];
38444 this._abortFunctions.push(abort);
38445 var tileKey = this._tileKey(tile);
38446 var subscription = tile$
38447 .subscribe(function (image) {
38448 _this._renderToTarget(x, y, w, h, image);
38449 _this._removeFromDictionary(tileKey, _this._tileSubscriptions);
38450 _this._removeFromArray(abort, _this._abortFunctions);
38451 _this._setTileRendered(tile, _this._currentLevel);
38452 _this._imageTileStore.addImage(image, tileKey, level);
38453 _this._updated$.next(true);
38454 }, function (error) {
38455 _this._removeFromDictionary(tileKey, _this._tileSubscriptions);
38456 _this._removeFromArray(abort, _this._abortFunctions);
38457 console.error(error);
38459 if (!subscription.closed) {
38460 this._tileSubscriptions[tileKey] = subscription;
38464 * Retrieve image tiles.
38466 * @description Retrieve a image tiles and render them to the
38467 * texture. Retrieve from store if it exists, otherwise Retrieve
38470 * @param {Array<Array<number>>} tiles - Array of tile coordinates to
38473 TextureProvider.prototype._fetchTiles = function (tiles) {
38474 var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
38475 for (var _i = 0, tiles_1 = tiles; _i < tiles_1.length; _i++) {
38476 var tile = tiles_1[_i];
38477 var tileKey = this._tileKey(tile);
38478 if (tileKey in this._renderedCurrentLevelTiles ||
38479 tileKey in this._tileSubscriptions) {
38482 var tileX = tileSize * tile[0];
38483 var tileY = tileSize * tile[1];
38484 var tileWidth = tileX + tileSize > this._width ? this._width - tileX : tileSize;
38485 var tileHeight = tileY + tileSize > this._height ? this._height - tileY : tileSize;
38486 if (this._imageTileStore.hasImage(tileKey, this._currentLevel)) {
38487 this._renderToTarget(tileX, tileY, tileWidth, tileHeight, this._imageTileStore.getImage(tileKey, this._currentLevel));
38488 this._setTileRendered(tile, this._currentLevel);
38489 this._updated$.next(true);
38492 var scaledX = Math.floor(tileWidth / tileSize * this._tileSize);
38493 var scaledY = Math.floor(tileHeight / tileSize * this._tileSize);
38494 this._fetchTile(tile, this._currentLevel, tileX, tileY, tileWidth, tileHeight, scaledX, scaledY);
38498 * Get tile coordinates for a point using the current level.
38500 * @param {Array<number>} point - Point in basic coordinates.
38502 * @returns {Array<number>} x and y tile coodinates.
38504 TextureProvider.prototype._getTileCoords = function (point) {
38505 var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
38506 var maxX = Math.ceil(this._width / tileSize) - 1;
38507 var maxY = Math.ceil(this._height / tileSize) - 1;
38509 Math.min(Math.floor(this._width * point[0] / tileSize), maxX),
38510 Math.min(Math.floor(this._height * point[1] / tileSize), maxY),
38514 * Get tile coordinates for all tiles contained in a bounding
38517 * @param {Array<number>} topLeft - Top left tile coordinate of bounding box.
38518 * @param {Array<number>} bottomRight - Bottom right tile coordinate of bounding box.
38520 * @returns {Array<Array<number>>} Array of x, y tile coodinates.
38522 TextureProvider.prototype._getTiles = function (topLeft, bottomRight) {
38524 if (topLeft[0] > bottomRight[0]) {
38525 var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
38526 var maxX = Math.ceil(this._width / tileSize) - 1;
38527 for (var x = topLeft[0]; x <= maxX; x++) {
38530 for (var x = 0; x <= bottomRight[0]; x++) {
38535 for (var x = topLeft[0]; x <= bottomRight[0]; x++) {
38540 for (var _i = 0, xs_1 = xs; _i < xs_1.length; _i++) {
38542 for (var y = topLeft[1]; y <= bottomRight[1]; y++) {
38543 tiles.push([x, y]);
38549 * Remove an item from an array if it exists in array.
38551 * @param {T} item - Item to remove.
38552 * @param {Array<T>} array - Array from which item should be removed.
38554 TextureProvider.prototype._removeFromArray = function (item, array) {
38555 var index = array.indexOf(item);
38556 if (index !== -1) {
38557 array.splice(index, 1);
38561 * Remove an item from a dictionary.
38563 * @param {string} key - Key of the item to remove.
38564 * @param {Object} dict - Dictionary from which item should be removed.
38566 TextureProvider.prototype._removeFromDictionary = function (key, dict) {
38572 * Render an image tile to the target texture.
38574 * @param {number} x - The top left x pixel coordinate of the tile.
38575 * @param {number} y - The top left y pixel coordinate of the tile.
38576 * @param {number} w - The pixel width of the tile.
38577 * @param {number} h - The pixel height of the tile.
38578 * @param {HTMLImageElement} background - The image tile to render.
38580 TextureProvider.prototype._renderToTarget = function (x, y, w, h, image) {
38581 var texture = new THREE.Texture(image);
38582 texture.minFilter = THREE.LinearFilter;
38583 texture.needsUpdate = true;
38584 var geometry = new THREE.PlaneGeometry(w, h);
38585 var material = new THREE.MeshBasicMaterial({ map: texture, side: THREE.FrontSide });
38586 var mesh = new THREE.Mesh(geometry, material);
38587 mesh.position.x = -this._width / 2 + x + w / 2;
38588 mesh.position.y = this._height / 2 - y - h / 2;
38589 var scene = new THREE.Scene();
38591 this._renderer.render(scene, this._camera, this._renderTarget);
38592 this._renderer.setRenderTarget(undefined);
38593 scene.remove(mesh);
38594 geometry.dispose();
38595 material.dispose();
38599 * Mark a tile as rendered.
38601 * @description Clears tiles marked as rendered in other
38602 * levels of the tile pyramid if they were rendered on
38603 * top of or below the tile.
38605 * @param {Arrary<number>} tile - The tile coordinates.
38606 * @param {number} level - Tile level of the tile coordinates.
38608 TextureProvider.prototype._setTileRendered = function (tile, level) {
38609 var otherLevels = Object.keys(this._renderedTiles)
38610 .map(function (key) {
38611 return parseInt(key, 10);
38613 .filter(function (renderedLevel) {
38614 return renderedLevel !== level;
38616 for (var _i = 0, otherLevels_1 = otherLevels; _i < otherLevels_1.length; _i++) {
38617 var otherLevel = otherLevels_1[_i];
38618 var scale = Math.pow(2, otherLevel - level);
38619 if (otherLevel < level) {
38620 var x = Math.floor(scale * tile[0]);
38621 var y = Math.floor(scale * tile[1]);
38622 for (var _a = 0, _b = this._renderedTiles[otherLevel].slice(); _a < _b.length; _a++) {
38623 var otherTile = _b[_a];
38624 if (otherTile[0] === x && otherTile[1] === y) {
38625 var index = this._renderedTiles[otherLevel].indexOf(otherTile);
38626 this._renderedTiles[otherLevel].splice(index, 1);
38631 var startX = scale * tile[0];
38632 var endX = startX + scale - 1;
38633 var startY = scale * tile[1];
38634 var endY = startY + scale - 1;
38635 for (var _c = 0, _d = this._renderedTiles[otherLevel].slice(); _c < _d.length; _c++) {
38636 var otherTile = _d[_c];
38637 if (otherTile[0] >= startX && otherTile[0] <= endX &&
38638 otherTile[1] >= startY && otherTile[1] <= endY) {
38639 var index = this._renderedTiles[otherLevel].indexOf(otherTile);
38640 this._renderedTiles[otherLevel].splice(index, 1);
38644 if (this._renderedTiles[otherLevel].length === 0) {
38645 delete this._renderedTiles[otherLevel];
38648 this._renderedTiles[level].push(tile);
38649 this._renderedCurrentLevelTiles[this._tileKey(tile)] = true;
38652 * Create a tile key from a tile coordinates.
38654 * @description Tile keys are used as a hash for
38655 * storing the tile in a dictionary.
38657 * @param {Arrary<number>} tile - The tile coordinates.
38659 TextureProvider.prototype._tileKey = function (tile) {
38660 return tile[0] + "-" + tile[1];
38662 return TextureProvider;
38664 exports.TextureProvider = TextureProvider;
38665 exports.default = TextureProvider;
38667 },{"rxjs/Subject":34,"three":176}],341:[function(require,module,exports){
38669 Object.defineProperty(exports, "__esModule", { value: true });
38670 var EventEmitter = (function () {
38671 function EventEmitter() {
38675 * Subscribe to an event by its name.
38676 * @param {string }eventType - The name of the event to subscribe to.
38677 * @param {any} fn - The handler called when the event occurs.
38679 EventEmitter.prototype.on = function (eventType, fn) {
38680 this._events[eventType] = this._events[eventType] || [];
38681 this._events[eventType].push(fn);
38685 * Unsubscribe from an event by its name.
38686 * @param {string} eventType - The name of the event to subscribe to.
38687 * @param {any} fn - The handler to remove.
38689 EventEmitter.prototype.off = function (eventType, fn) {
38694 if (!this._listens(eventType)) {
38695 var idx = this._events[eventType].indexOf(fn);
38697 this._events[eventType].splice(idx, 1);
38699 if (this._events[eventType].length) {
38700 delete this._events[eventType];
38704 delete this._events[eventType];
38708 EventEmitter.prototype.fire = function (eventType, data) {
38709 if (!this._listens(eventType)) {
38712 for (var _i = 0, _a = this._events[eventType]; _i < _a.length; _i++) {
38714 fn.call(this, data);
38718 EventEmitter.prototype._listens = function (eventType) {
38719 return !!(this._events && this._events[eventType]);
38721 return EventEmitter;
38723 exports.EventEmitter = EventEmitter;
38724 exports.default = EventEmitter;
38726 },{}],342:[function(require,module,exports){
38728 Object.defineProperty(exports, "__esModule", { value: true });
38729 var Viewer_1 = require("../Viewer");
38730 var Settings = (function () {
38731 function Settings() {
38733 Settings.setOptions = function (options) {
38734 Settings._baseImageSize = options.baseImageSize != null ?
38735 options.baseImageSize :
38736 Viewer_1.ImageSize.Size640;
38737 Settings._basePanoramaSize = options.basePanoramaSize != null ?
38738 options.basePanoramaSize :
38739 Viewer_1.ImageSize.Size2048;
38740 Settings._maxImageSize = options.maxImageSize != null ?
38741 options.maxImageSize :
38742 Viewer_1.ImageSize.Size2048;
38744 Object.defineProperty(Settings, "baseImageSize", {
38746 return Settings._baseImageSize;
38751 Object.defineProperty(Settings, "basePanoramaSize", {
38753 return Settings._basePanoramaSize;
38758 Object.defineProperty(Settings, "maxImageSize", {
38760 return Settings._maxImageSize;
38767 exports.Settings = Settings;
38768 exports.default = Settings;
38770 },{"../Viewer":236}],343:[function(require,module,exports){
38772 Object.defineProperty(exports, "__esModule", { value: true });
38773 var Urls = (function () {
38776 Object.defineProperty(Urls, "tileScheme", {
38783 Object.defineProperty(Urls, "tileDomain", {
38785 return "d2qb1440i7l50o.cloudfront.net";
38790 Object.defineProperty(Urls, "origin", {
38792 return "mapillary.webgl";
38797 Urls.thumbnail = function (key, size) {
38798 return "https://d1cuyjsrcm0gby.cloudfront.net/" + key + "/thumb-" + size + ".jpg?origin=" + this.origin;
38800 Urls.falcorModel = function (clientId) {
38801 return "https://a.mapillary.com/v3/model.json?client_id=" + clientId;
38803 Urls.protoMesh = function (key) {
38804 return "https://d1brzeo354iq2l.cloudfront.net/v2/mesh/" + key;
38808 exports.Urls = Urls;
38809 exports.default = Urls;
38811 },{}],344:[function(require,module,exports){
38813 Object.defineProperty(exports, "__esModule", { value: true });
38815 * Enumeration for alignments
38820 (function (Alignment) {
38824 Alignment[Alignment["Bottom"] = 0] = "Bottom";
38826 * Align to bottom left
38828 Alignment[Alignment["BottomLeft"] = 1] = "BottomLeft";
38830 * Align to bottom right
38832 Alignment[Alignment["BottomRight"] = 2] = "BottomRight";
38836 Alignment[Alignment["Center"] = 3] = "Center";
38840 Alignment[Alignment["Left"] = 4] = "Left";
38844 Alignment[Alignment["Right"] = 5] = "Right";
38848 Alignment[Alignment["Top"] = 6] = "Top";
38850 * Align to top left
38852 Alignment[Alignment["TopLeft"] = 7] = "TopLeft";
38854 * Align to top right
38856 Alignment[Alignment["TopRight"] = 8] = "TopRight";
38857 })(Alignment = exports.Alignment || (exports.Alignment = {}));
38858 exports.default = Alignment;
38860 },{}],345:[function(require,module,exports){
38862 Object.defineProperty(exports, "__esModule", { value: true });
38863 require("rxjs/add/operator/bufferCount");
38864 require("rxjs/add/operator/delay");
38865 require("rxjs/add/operator/distinctUntilChanged");
38866 require("rxjs/add/operator/map");
38867 require("rxjs/add/operator/switchMap");
38868 var CacheService = (function () {
38869 function CacheService(graphService, stateService) {
38870 this._graphService = graphService;
38871 this._stateService = stateService;
38872 this._started = false;
38874 Object.defineProperty(CacheService.prototype, "started", {
38876 return this._started;
38881 CacheService.prototype.start = function () {
38883 if (this._started) {
38886 this._uncacheSubscription = this._stateService.currentState$
38887 .distinctUntilChanged(undefined, function (frame) {
38888 return frame.state.currentNode.key;
38890 .map(function (frame) {
38891 return frame.state.trajectory
38892 .map(function (n) {
38897 .switchMap(function (keepKeysBuffer) {
38898 var keepKeys = keepKeysBuffer[0];
38899 return _this._graphService.uncache$(keepKeys);
38901 .subscribe(function () { });
38902 this._started = true;
38904 CacheService.prototype.stop = function () {
38905 if (!this._started) {
38908 this._uncacheSubscription.unsubscribe();
38909 this._uncacheSubscription = null;
38910 this._started = false;
38912 return CacheService;
38914 exports.CacheService = CacheService;
38915 exports.default = CacheService;
38917 },{"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}],346:[function(require,module,exports){
38919 Object.defineProperty(exports, "__esModule", { value: true });
38920 var Component_1 = require("../Component");
38921 var ComponentController = (function () {
38922 function ComponentController(container, navigator, observer, key, options) {
38924 this._container = container;
38925 this._observer = observer;
38926 this._navigator = navigator;
38927 this._options = options != null ? options : {};
38929 this._componentService = new Component_1.ComponentService(this._container, this._navigator);
38930 this._coverComponent = this._componentService.getCover();
38931 this._initializeComponents();
38933 this._initilizeCoverComponent();
38934 this._subscribeCoverComponent();
38937 this._navigator.movedToKey$
38938 .first(function (k) {
38941 .subscribe(function (k) {
38943 _this._componentService.deactivateCover();
38944 _this._coverComponent.configure({ key: _this._key, loading: false, visible: false });
38945 _this._subscribeCoverComponent();
38946 _this._navigator.stateService.start();
38947 _this._observer.startEmit();
38951 ComponentController.prototype.get = function (name) {
38952 return this._componentService.get(name);
38954 ComponentController.prototype.activate = function (name) {
38955 this._componentService.activate(name);
38957 ComponentController.prototype.activateCover = function () {
38958 this._coverComponent.configure({ loading: false, visible: true });
38960 ComponentController.prototype.deactivate = function (name) {
38961 this._componentService.deactivate(name);
38963 ComponentController.prototype.deactivateCover = function () {
38964 this._coverComponent.configure({ loading: true, visible: true });
38966 ComponentController.prototype.resize = function () {
38967 this._componentService.resize();
38969 ComponentController.prototype._initializeComponents = function () {
38970 var options = this._options;
38971 this._uFalse(options.background, "background");
38972 this._uFalse(options.debug, "debug");
38973 this._uFalse(options.image, "image");
38974 this._uFalse(options.marker, "marker");
38975 this._uFalse(options.navigation, "navigation");
38976 this._uFalse(options.popup, "popup");
38977 this._uFalse(options.route, "route");
38978 this._uFalse(options.slider, "slider");
38979 this._uFalse(options.tag, "tag");
38980 this._uTrue(options.attribution, "attribution");
38981 this._uTrue(options.bearing, "bearing");
38982 this._uTrue(options.cache, "cache");
38983 this._uTrue(options.direction, "direction");
38984 this._uTrue(options.imagePlane, "imagePlane");
38985 this._uTrue(options.keyboard, "keyboard");
38986 this._uTrue(options.loading, "loading");
38987 this._uTrue(options.mouse, "mouse");
38988 this._uTrue(options.sequence, "sequence");
38989 this._uTrue(options.stats, "stats");
38991 ComponentController.prototype._initilizeCoverComponent = function () {
38992 var options = this._options;
38993 this._coverComponent.configure({ key: this._key });
38994 if (options.cover === undefined || options.cover) {
38995 this.activateCover();
38998 this.deactivateCover();
39001 ComponentController.prototype._subscribeCoverComponent = function () {
39003 this._coverComponent.configuration$.subscribe(function (conf) {
39004 if (conf.loading) {
39005 _this._navigator.stateService.currentKey$
39007 .switchMap(function (key) {
39008 return key == null || key !== conf.key ?
39009 _this._navigator.moveToKey$(conf.key) :
39010 _this._navigator.stateService.currentNode$
39013 .subscribe(function (node) {
39014 _this._navigator.stateService.start();
39015 _this._observer.startEmit();
39016 _this._coverComponent.configure({ loading: false, visible: false });
39017 _this._componentService.deactivateCover();
39018 }, function (error) {
39019 console.error("Failed to deactivate cover.", error);
39020 _this._coverComponent.configure({ loading: false, visible: true });
39023 else if (conf.visible) {
39024 _this._observer.stopEmit();
39025 _this._navigator.stateService.stop();
39026 _this._componentService.activateCover();
39030 ComponentController.prototype._uFalse = function (option, name) {
39031 if (option === undefined) {
39032 this._componentService.deactivate(name);
39035 if (typeof option === "boolean") {
39037 this._componentService.activate(name);
39040 this._componentService.deactivate(name);
39044 this._componentService.configure(name, option);
39045 this._componentService.activate(name);
39047 ComponentController.prototype._uTrue = function (option, name) {
39048 if (option === undefined) {
39049 this._componentService.activate(name);
39052 if (typeof option === "boolean") {
39054 this._componentService.activate(name);
39057 this._componentService.deactivate(name);
39061 this._componentService.configure(name, option);
39062 this._componentService.activate(name);
39064 return ComponentController;
39066 exports.ComponentController = ComponentController;
39068 },{"../Component":226}],347:[function(require,module,exports){
39070 Object.defineProperty(exports, "__esModule", { value: true });
39071 var Render_1 = require("../Render");
39072 var Viewer_1 = require("../Viewer");
39073 var Container = (function () {
39074 function Container(id, stateService, options) {
39076 this._container = document.getElementById(id);
39077 if (!this._container) {
39078 throw new Error("Container '" + id + "' not found.");
39080 this._container.classList.add("mapillary-js");
39081 this._canvasContainer = document.createElement("div");
39082 this._canvasContainer.className = "mapillary-js-interactive";
39083 this._domContainer = document.createElement("div");
39084 this._domContainer.className = "mapillary-js-dom";
39085 this._container.appendChild(this._canvasContainer);
39086 this._container.appendChild(this._domContainer);
39087 this.renderService = new Render_1.RenderService(this._container, stateService.currentState$, options.renderMode);
39088 this.glRenderer = new Render_1.GLRenderer(this._canvasContainer, this.renderService);
39089 this.domRenderer = new Render_1.DOMRenderer(this._domContainer, this.renderService, stateService.currentState$);
39090 this.mouseService = new Viewer_1.MouseService(this._container, this._canvasContainer, this._domContainer);
39091 this.touchService = new Viewer_1.TouchService(this._canvasContainer, this._domContainer);
39092 this.spriteService = new Viewer_1.SpriteService(options.sprite);
39094 Object.defineProperty(Container.prototype, "element", {
39096 return this._container;
39101 Object.defineProperty(Container.prototype, "canvasContainer", {
39103 return this.canvasContainer;
39110 exports.Container = Container;
39111 exports.default = Container;
39113 },{"../Render":232,"../Viewer":236}],348:[function(require,module,exports){
39115 Object.defineProperty(exports, "__esModule", { value: true });
39117 * Enumeration for image sizes
39120 * @description Image sizes in pixels for the long side of the image.
39123 (function (ImageSize) {
39125 * 320 pixels image size
39127 ImageSize[ImageSize["Size320"] = 320] = "Size320";
39129 * 640 pixels image size
39131 ImageSize[ImageSize["Size640"] = 640] = "Size640";
39133 * 1024 pixels image size
39135 ImageSize[ImageSize["Size1024"] = 1024] = "Size1024";
39137 * 2048 pixels image size
39139 ImageSize[ImageSize["Size2048"] = 2048] = "Size2048";
39140 })(ImageSize = exports.ImageSize || (exports.ImageSize = {}));
39142 },{}],349:[function(require,module,exports){
39144 /// <reference path="../../typings/index.d.ts" />
39145 Object.defineProperty(exports, "__esModule", { value: true });
39146 var _ = require("underscore");
39147 var Subject_1 = require("rxjs/Subject");
39148 require("rxjs/add/operator/debounceTime");
39149 require("rxjs/add/operator/distinctUntilChanged");
39150 require("rxjs/add/operator/map");
39151 require("rxjs/add/operator/publishReplay");
39152 require("rxjs/add/operator/scan");
39153 require("rxjs/add/operator/startWith");
39154 var LoadingService = (function () {
39155 function LoadingService() {
39156 this._loadersSubject$ = new Subject_1.Subject();
39157 this._loaders$ = this._loadersSubject$
39158 .scan(function (loaders, loader) {
39159 if (loader.task !== undefined) {
39160 loaders[loader.task] = loader.loading;
39168 Object.defineProperty(LoadingService.prototype, "loading$", {
39170 return this._loaders$
39171 .map(function (loaders) {
39172 return _.reduce(loaders, function (loader, acc) {
39173 return (loader || acc);
39177 .distinctUntilChanged();
39182 LoadingService.prototype.taskLoading$ = function (task) {
39183 return this._loaders$
39184 .map(function (loaders) {
39185 return !!loaders[task];
39188 .distinctUntilChanged();
39190 LoadingService.prototype.startLoading = function (task) {
39191 this._loadersSubject$.next({ loading: true, task: task });
39193 LoadingService.prototype.stopLoading = function (task) {
39194 this._loadersSubject$.next({ loading: false, task: task });
39196 return LoadingService;
39198 exports.LoadingService = LoadingService;
39199 exports.default = LoadingService;
39201 },{"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}],350:[function(require,module,exports){
39203 Object.defineProperty(exports, "__esModule", { value: true });
39204 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
39205 var Observable_1 = require("rxjs/Observable");
39206 var Subject_1 = require("rxjs/Subject");
39207 require("rxjs/add/observable/fromEvent");
39208 require("rxjs/add/operator/distinctUntilChanged");
39209 require("rxjs/add/operator/filter");
39210 require("rxjs/add/operator/map");
39211 require("rxjs/add/operator/merge");
39212 require("rxjs/add/operator/mergeMap");
39213 require("rxjs/add/operator/publishReplay");
39214 require("rxjs/add/operator/scan");
39215 require("rxjs/add/operator/switchMap");
39216 require("rxjs/add/operator/withLatestFrom");
39217 var Geo_1 = require("../Geo");
39218 var MouseService = (function () {
39219 function MouseService(container, canvasContainer, domContainer, viewportCoords) {
39221 this._canvasContainer = canvasContainer;
39222 this._domContainer = domContainer;
39223 this._viewportCoords = viewportCoords != null ? viewportCoords : new Geo_1.ViewportCoords();
39224 this._activeSubject$ = new BehaviorSubject_1.BehaviorSubject(false);
39225 this._active$ = this._activeSubject$
39226 .distinctUntilChanged()
39229 this._claimMouse$ = new Subject_1.Subject();
39230 this._documentMouseMove$ = Observable_1.Observable.fromEvent(document, "mousemove");
39231 this._documentMouseUp$ = Observable_1.Observable.fromEvent(document, "mouseup");
39232 this._mouseDown$ = Observable_1.Observable.fromEvent(canvasContainer, "mousedown");
39233 this._mouseLeave$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseleave");
39234 this._mouseMove$ = Observable_1.Observable.fromEvent(canvasContainer, "mousemove");
39235 this._mouseUp$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseup");
39236 this._mouseOut$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseout");
39237 this._mouseOver$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseover");
39238 this._domMouseDown$ = Observable_1.Observable.fromEvent(domContainer, "mousedown");
39239 this._domMouseMove$ = Observable_1.Observable.fromEvent(domContainer, "mousemove");
39240 this._click$ = Observable_1.Observable.fromEvent(canvasContainer, "click");
39241 this._contextMenu$ = Observable_1.Observable.fromEvent(canvasContainer, "contextmenu");
39242 this._dblClick$ = Observable_1.Observable
39243 .merge(Observable_1.Observable.fromEvent(container, "click"), Observable_1.Observable.fromEvent(canvasContainer, "dblclick"))
39245 .filter(function (events) {
39246 var event1 = events[0];
39247 var event2 = events[1];
39248 var event3 = events[2];
39249 return event1.type === "click" &&
39250 event2.type === "click" &&
39251 event3.type === "dblclick" &&
39252 event1.target.parentNode === canvasContainer &&
39253 event2.target.parentNode === canvasContainer;
39255 .map(function (events) {
39259 Observable_1.Observable
39260 .merge(this._domMouseDown$, this._domMouseMove$, this._dblClick$, this._contextMenu$)
39261 .subscribe(function (event) {
39262 event.preventDefault();
39264 this._mouseWheel$ = Observable_1.Observable
39265 .merge(Observable_1.Observable.fromEvent(canvasContainer, "wheel"), Observable_1.Observable.fromEvent(domContainer, "wheel"));
39266 this._consistentContextMenu$ = Observable_1.Observable
39267 .merge(this._mouseDown$, this._mouseMove$, this._mouseOut$, this._mouseUp$, this._contextMenu$)
39269 .filter(function (events) {
39270 // fire context menu on mouse up both on mac and windows
39271 return events[0].type === "mousedown" &&
39272 events[1].type === "contextmenu" &&
39273 events[2].type === "mouseup";
39275 .map(function (events) {
39279 var dragStop$ = Observable_1.Observable
39280 .merge(Observable_1.Observable.fromEvent(window, "blur"), this._documentMouseUp$
39281 .filter(function (e) {
39282 return e.button === 0;
39285 var leftButtonDown$ = this._mouseDown$
39286 .filter(function (e) {
39287 return e.button === 0;
39290 this._mouseDragStart$ = leftButtonDown$
39291 .mergeMap(function (e) {
39292 return _this._documentMouseMove$
39293 .takeUntil(dragStop$)
39296 this._mouseDrag$ = leftButtonDown$
39297 .mergeMap(function (e) {
39298 return _this._documentMouseMove$
39300 .takeUntil(dragStop$);
39302 this._mouseDragEnd$ = this._mouseDragStart$
39303 .mergeMap(function (e) {
39304 return dragStop$.first();
39306 var containerLeftButtonDown$ = this._domMouseDown$
39307 .filter(function (e) {
39308 return e.button === 0;
39311 this._domMouseDragStart$ = containerLeftButtonDown$
39312 .mergeMap(function (e) {
39313 return _this._documentMouseMove$
39314 .takeUntil(dragStop$)
39317 this._domMouseDrag$ = containerLeftButtonDown$
39318 .mergeMap(function (e) {
39319 return _this._documentMouseMove$
39321 .takeUntil(dragStop$);
39323 this._domMouseDragEnd$ = this._domMouseDragStart$
39324 .mergeMap(function (e) {
39325 return dragStop$.first();
39327 this._staticClick$ = this._mouseDown$
39328 .switchMap(function (e) {
39329 return _this._click$
39330 .takeUntil(_this._mouseMove$)
39333 this._mouseOwner$ = this._claimMouse$
39334 .scan(function (claims, mouseClaim) {
39335 if (mouseClaim.zindex == null) {
39336 delete claims[mouseClaim.name];
39339 claims[mouseClaim.name] = mouseClaim.zindex;
39343 .map(function (claims) {
39346 for (var name_1 in claims) {
39347 if (claims.hasOwnProperty(name_1)) {
39348 if (claims[name_1] > curZ) {
39349 curZ = claims[name_1];
39358 this._mouseOwner$.subscribe(function () { });
39360 Object.defineProperty(MouseService.prototype, "active$", {
39362 return this._active$;
39367 Object.defineProperty(MouseService.prototype, "activate$", {
39369 return this._activeSubject$;
39374 Object.defineProperty(MouseService.prototype, "documentMouseMove$", {
39376 return this._documentMouseMove$;
39381 Object.defineProperty(MouseService.prototype, "documentMouseUp$", {
39383 return this._documentMouseUp$;
39388 Object.defineProperty(MouseService.prototype, "domMouseDragStart$", {
39390 return this._domMouseDragStart$;
39395 Object.defineProperty(MouseService.prototype, "domMouseDrag$", {
39397 return this._domMouseDrag$;
39402 Object.defineProperty(MouseService.prototype, "domMouseDragEnd$", {
39404 return this._domMouseDragEnd$;
39409 Object.defineProperty(MouseService.prototype, "domMouseDown$", {
39411 return this._domMouseDown$;
39416 Object.defineProperty(MouseService.prototype, "domMouseMove$", {
39418 return this._domMouseMove$;
39423 Object.defineProperty(MouseService.prototype, "mouseOwner$", {
39425 return this._mouseOwner$;
39430 Object.defineProperty(MouseService.prototype, "mouseDown$", {
39432 return this._mouseDown$;
39437 Object.defineProperty(MouseService.prototype, "mouseMove$", {
39439 return this._mouseMove$;
39444 Object.defineProperty(MouseService.prototype, "mouseLeave$", {
39446 return this._mouseLeave$;
39451 Object.defineProperty(MouseService.prototype, "mouseOut$", {
39453 return this._mouseOut$;
39458 Object.defineProperty(MouseService.prototype, "mouseOver$", {
39460 return this._mouseOver$;
39465 Object.defineProperty(MouseService.prototype, "mouseUp$", {
39467 return this._mouseUp$;
39472 Object.defineProperty(MouseService.prototype, "click$", {
39474 return this._click$;
39479 Object.defineProperty(MouseService.prototype, "dblClick$", {
39481 return this._dblClick$;
39486 Object.defineProperty(MouseService.prototype, "contextMenu$", {
39488 return this._consistentContextMenu$;
39493 Object.defineProperty(MouseService.prototype, "mouseWheel$", {
39495 return this._mouseWheel$;
39500 Object.defineProperty(MouseService.prototype, "mouseDragStart$", {
39502 return this._mouseDragStart$;
39507 Object.defineProperty(MouseService.prototype, "mouseDrag$", {
39509 return this._mouseDrag$;
39514 Object.defineProperty(MouseService.prototype, "mouseDragEnd$", {
39516 return this._mouseDragEnd$;
39521 Object.defineProperty(MouseService.prototype, "staticClick$", {
39523 return this._staticClick$;
39528 MouseService.prototype.claimMouse = function (name, zindex) {
39529 this._claimMouse$.next({ name: name, zindex: zindex });
39531 MouseService.prototype.unclaimMouse = function (name) {
39532 this._claimMouse$.next({ name: name, zindex: null });
39534 MouseService.prototype.filtered$ = function (name, observable$) {
39536 .withLatestFrom(this.mouseOwner$, function (event, owner) {
39537 return [event, owner];
39539 .filter(function (eo) {
39540 return eo[1] === name;
39542 .map(function (eo) {
39546 return MouseService;
39548 exports.MouseService = MouseService;
39549 exports.default = MouseService;
39551 },{"../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}],351:[function(require,module,exports){
39553 /// <reference path="../../typings/index.d.ts" />
39554 Object.defineProperty(exports, "__esModule", { value: true });
39555 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
39556 var Observable_1 = require("rxjs/Observable");
39557 var ReplaySubject_1 = require("rxjs/ReplaySubject");
39558 require("rxjs/add/observable/throw");
39559 require("rxjs/add/operator/do");
39560 require("rxjs/add/operator/finally");
39561 require("rxjs/add/operator/first");
39562 require("rxjs/add/operator/map");
39563 require("rxjs/add/operator/mergeMap");
39564 var API_1 = require("../API");
39565 var Graph_1 = require("../Graph");
39566 var Edge_1 = require("../Edge");
39567 var State_1 = require("../State");
39568 var Viewer_1 = require("../Viewer");
39569 var Navigator = (function () {
39570 function Navigator(clientId, token, apiV3, graphService, imageLoadingService, loadingService, stateService, cacheService) {
39571 this._apiV3 = apiV3 != null ? apiV3 : new API_1.APIv3(clientId, token);
39572 this._imageLoadingService = imageLoadingService != null ? imageLoadingService : new Graph_1.ImageLoadingService();
39573 this._graphService = graphService != null ?
39575 new Graph_1.GraphService(new Graph_1.Graph(this.apiV3), this._imageLoadingService);
39576 this._loadingService = loadingService != null ? loadingService : new Viewer_1.LoadingService();
39577 this._loadingName = "navigator";
39578 this._stateService = stateService != null ? stateService : new State_1.StateService();
39579 this._cacheService = cacheService != null ?
39581 new Viewer_1.CacheService(this._graphService, this._stateService);
39582 this._cacheService.start();
39583 this._keyRequested$ = new BehaviorSubject_1.BehaviorSubject(null);
39584 this._movedToKey$ = new BehaviorSubject_1.BehaviorSubject(null);
39585 this._request$ = null;
39586 this._requestSubscription = null;
39587 this._nodeRequestSubscription = null;
39589 Object.defineProperty(Navigator.prototype, "apiV3", {
39591 return this._apiV3;
39596 Object.defineProperty(Navigator.prototype, "graphService", {
39598 return this._graphService;
39603 Object.defineProperty(Navigator.prototype, "imageLoadingService", {
39605 return this._imageLoadingService;
39610 Object.defineProperty(Navigator.prototype, "loadingService", {
39612 return this._loadingService;
39617 Object.defineProperty(Navigator.prototype, "movedToKey$", {
39619 return this._movedToKey$;
39624 Object.defineProperty(Navigator.prototype, "stateService", {
39626 return this._stateService;
39631 Navigator.prototype.moveToKey$ = function (key) {
39632 this._abortRequest("to key " + key);
39633 this._loadingService.startLoading(this._loadingName);
39634 var node$ = this._moveToKey$(key);
39635 return this._makeRequest$(node$);
39637 Navigator.prototype.moveDir$ = function (direction) {
39639 this._abortRequest("in dir " + Edge_1.EdgeDirection[direction]);
39640 this._loadingService.startLoading(this._loadingName);
39641 var node$ = this.stateService.currentNode$
39643 .mergeMap(function (node) {
39644 return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
39645 node.sequenceEdges$ :
39646 node.spatialEdges$)
39648 .map(function (status) {
39649 for (var _i = 0, _a = status.edges; _i < _a.length; _i++) {
39651 if (edge.data.direction === direction) {
39658 .mergeMap(function (directionKey) {
39659 if (directionKey == null) {
39660 _this._loadingService.stopLoading(_this._loadingName);
39661 return Observable_1.Observable
39662 .throw(new Error("Direction (" + direction + ") does not exist for current node."));
39664 return _this._moveToKey$(directionKey);
39666 return this._makeRequest$(node$);
39668 Navigator.prototype.moveCloseTo$ = function (lat, lon) {
39670 this._abortRequest("to lat " + lat + ", lon " + lon);
39671 this._loadingService.startLoading(this._loadingName);
39672 var node$ = this.apiV3.imageCloseTo$(lat, lon)
39673 .mergeMap(function (fullNode) {
39674 if (fullNode == null) {
39675 _this._loadingService.stopLoading(_this._loadingName);
39676 return Observable_1.Observable
39677 .throw(new Error("No image found close to lat " + lat + ", lon " + lon + "."));
39679 return _this._moveToKey$(fullNode.key);
39681 return this._makeRequest$(node$);
39683 Navigator.prototype.setFilter$ = function (filter) {
39685 this._stateService.clearNodes();
39686 return this._movedToKey$
39688 .mergeMap(function (key) {
39690 return _this._trajectoryKeys$()
39691 .mergeMap(function (keys) {
39692 return _this._graphService.setFilter$(filter)
39693 .mergeMap(function (graph) {
39694 return _this._cacheKeys$(keys);
39699 return _this._keyRequested$
39700 .mergeMap(function (requestedKey) {
39701 if (requestedKey != null) {
39702 return _this._graphService.setFilter$(filter)
39703 .mergeMap(function (graph) {
39704 return _this._graphService.cacheNode$(requestedKey);
39707 return _this._graphService.setFilter$(filter)
39708 .map(function (graph) {
39713 .map(function (node) {
39717 Navigator.prototype.setToken$ = function (token) {
39719 this._abortRequest("to set token");
39720 this._stateService.clearNodes();
39721 return this._movedToKey$
39723 .do(function (key) {
39724 _this._apiV3.setToken(token);
39726 .mergeMap(function (key) {
39727 return key == null ?
39728 _this._graphService.reset$([])
39729 .map(function (graph) {
39732 _this._trajectoryKeys$()
39733 .mergeMap(function (keys) {
39734 return _this._graphService.reset$(keys)
39735 .mergeMap(function (graph) {
39736 return _this._cacheKeys$(keys);
39740 .map(function (node) {
39745 Navigator.prototype._cacheKeys$ = function (keys) {
39747 var cacheNodes$ = keys
39748 .map(function (key) {
39749 return _this._graphService.cacheNode$(key);
39751 return Observable_1.Observable
39755 Navigator.prototype._abortRequest = function (reason) {
39756 if (this._requestSubscription != null) {
39757 this._requestSubscription.unsubscribe();
39758 this._requestSubscription = null;
39760 if (this._nodeRequestSubscription != null) {
39761 this._nodeRequestSubscription.unsubscribe();
39762 this._nodeRequestSubscription = null;
39764 if (this._request$ != null) {
39765 this._request$.error(new Error("Request aborted by a subsequent request " + reason + "."));
39766 this._request$ = null;
39769 Navigator.prototype._makeRequest$ = function (node$) {
39771 this._request$ = new ReplaySubject_1.ReplaySubject(1);
39772 this._requestSubscription = this._request$
39773 .subscribe(undefined, function (e) { });
39774 this._nodeRequestSubscription = node$
39775 .subscribe(function (node) {
39776 _this._request$.next(node);
39777 _this._request$.complete();
39778 }, function (error) {
39779 _this._request$.error(error);
39781 return this._request$;
39783 Navigator.prototype._moveToKey$ = function (key) {
39785 this._keyRequested$.next(key);
39786 return this._graphService.cacheNode$(key)
39787 .do(function (node) {
39788 _this._stateService.setNodes([node]);
39789 _this._movedToKey$.next(node.key);
39791 .finally(function () {
39792 _this._loadingService.stopLoading(_this._loadingName);
39795 Navigator.prototype._trajectoryKeys$ = function () {
39796 return this._stateService.currentState$
39798 .map(function (frame) {
39799 return frame.state.trajectory
39800 .map(function (node) {
39807 exports.Navigator = Navigator;
39808 exports.default = Navigator;
39810 },{"../API":225,"../Edge":227,"../Graph":230,"../State":233,"../Viewer":236,"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}],352:[function(require,module,exports){
39812 Object.defineProperty(exports, "__esModule", { value: true });
39813 var Observable_1 = require("rxjs/Observable");
39814 require("rxjs/add/observable/combineLatest");
39815 require("rxjs/add/operator/distinctUntilChanged");
39816 require("rxjs/add/operator/map");
39817 require("rxjs/add/operator/throttleTime");
39818 var Viewer_1 = require("../Viewer");
39819 var Observer = (function () {
39820 function Observer(eventEmitter, navigator, container) {
39822 this._container = container;
39823 this._eventEmitter = eventEmitter;
39824 this._navigator = navigator;
39825 this._projection = new Viewer_1.Projection();
39826 this._started = false;
39827 // loading should always emit, also when cover is activated
39828 this._navigator.loadingService.loading$
39829 .subscribe(function (loading) {
39830 _this._eventEmitter.fire(Viewer_1.Viewer.loadingchanged, loading);
39833 Object.defineProperty(Observer.prototype, "started", {
39835 return this._started;
39840 Observer.prototype.projectBasic$ = function (basicPoint) {
39842 return Observable_1.Observable
39843 .combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
39845 .map(function (_a) {
39846 var render = _a[0], transform = _a[1];
39847 var canvasPoint = _this._projection.basicToCanvas(basicPoint, _this._container.element, render, transform);
39848 return [Math.round(canvasPoint[0]), Math.round(canvasPoint[1])];
39851 Observer.prototype.startEmit = function () {
39853 if (this._started) {
39856 this._started = true;
39857 this._currentNodeSubscription = this._navigator.stateService.currentNodeExternal$
39858 .subscribe(function (node) {
39859 _this._eventEmitter.fire(Viewer_1.Viewer.nodechanged, node);
39861 this._sequenceEdgesSubscription = this._navigator.stateService.currentNodeExternal$
39862 .switchMap(function (node) {
39863 return node.sequenceEdges$;
39865 .subscribe(function (status) {
39866 _this._eventEmitter.fire(Viewer_1.Viewer.sequenceedgeschanged, status);
39868 this._spatialEdgesSubscription = this._navigator.stateService.currentNodeExternal$
39869 .switchMap(function (node) {
39870 return node.spatialEdges$;
39872 .subscribe(function (status) {
39873 _this._eventEmitter.fire(Viewer_1.Viewer.spatialedgeschanged, status);
39875 this._moveSubscription = Observable_1.Observable
39876 .combineLatest(this._navigator.stateService.inMotion$, this._container.mouseService.active$, this._container.touchService.active$)
39877 .map(function (values) {
39878 return values[0] || values[1] || values[2];
39880 .distinctUntilChanged()
39881 .subscribe(function (started) {
39883 _this._eventEmitter.fire(Viewer_1.Viewer.movestart, null);
39886 _this._eventEmitter.fire(Viewer_1.Viewer.moveend, null);
39889 this._bearingSubscription = this._container.renderService.bearing$
39891 .distinctUntilChanged(function (b1, b2) {
39892 return Math.abs(b2 - b1) < 1;
39894 .subscribe(function (bearing) {
39895 _this._eventEmitter.fire(Viewer_1.Viewer.bearingchanged, bearing);
39897 var mouseMove$ = this._container.mouseService.active$
39898 .switchMap(function (active) {
39900 Observable_1.Observable.empty() :
39901 _this._container.mouseService.mouseMove$;
39903 this._viewerMouseEventSubscription = Observable_1.Observable
39904 .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$))
39905 .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.reference$, this._navigator.stateService.currentTransform$)
39906 .map(function (_a) {
39907 var _b = _a[0], type = _b[0], event = _b[1], render = _a[1], reference = _a[2], transform = _a[3];
39908 var unprojection = _this._projection.eventToUnprojection(event, _this._container.element, render, reference, transform);
39910 basicPoint: unprojection.basicPoint,
39911 latLon: unprojection.latLon,
39912 originalEvent: event,
39913 pixelPoint: unprojection.pixelPoint,
39914 target: _this._eventEmitter,
39918 .subscribe(function (event) {
39919 _this._eventEmitter.fire(event.type, event);
39922 Observer.prototype.stopEmit = function () {
39923 if (!this.started) {
39926 this._started = false;
39927 this._bearingSubscription.unsubscribe();
39928 this._currentNodeSubscription.unsubscribe();
39929 this._moveSubscription.unsubscribe();
39930 this._sequenceEdgesSubscription.unsubscribe();
39931 this._spatialEdgesSubscription.unsubscribe();
39932 this._viewerMouseEventSubscription.unsubscribe();
39933 this._bearingSubscription = null;
39934 this._currentNodeSubscription = null;
39935 this._moveSubscription = null;
39936 this._sequenceEdgesSubscription = null;
39937 this._spatialEdgesSubscription = null;
39938 this._viewerMouseEventSubscription = null;
39940 Observer.prototype.unproject$ = function (canvasPoint) {
39942 return Observable_1.Observable
39943 .combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.reference$, this._navigator.stateService.currentTransform$)
39945 .map(function (_a) {
39946 var render = _a[0], reference = _a[1], transform = _a[2];
39947 var unprojection = _this._projection.canvasToUnprojection(canvasPoint, _this._container.element, render, reference, transform);
39948 return unprojection.latLon;
39951 Observer.prototype.unprojectBasic$ = function (canvasPoint) {
39953 return Observable_1.Observable
39954 .combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
39956 .map(function (_a) {
39957 var render = _a[0], transform = _a[1];
39958 return _this._projection.canvasToBasic(canvasPoint, _this._container.element, render, transform);
39961 Observer.prototype._mapMouseEvent$ = function (type, mouseEvent$) {
39962 return mouseEvent$.map(function (event) {
39963 return [type, event];
39968 exports.Observer = Observer;
39969 exports.default = Observer;
39971 },{"../Viewer":236,"rxjs/Observable":29,"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/distinctUntilChanged":58,"rxjs/add/operator/map":65,"rxjs/add/operator/throttleTime":82}],353:[function(require,module,exports){
39973 /// <reference path="../../typings/index.d.ts" />
39974 Object.defineProperty(exports, "__esModule", { value: true });
39975 var THREE = require("three");
39976 var Geo_1 = require("../Geo");
39977 var Projection = (function () {
39978 function Projection(geoCoords, viewportCoords) {
39979 this._geoCoords = !!geoCoords ? geoCoords : new Geo_1.GeoCoords();
39980 this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
39982 Projection.prototype.basicToCanvas = function (basicPoint, container, render, transform) {
39983 return this._viewportCoords
39984 .basicToCanvas(basicPoint[0], basicPoint[1], container, transform, render.perspective);
39986 Projection.prototype.canvasToBasic = function (canvasPoint, container, render, transform) {
39987 var basicPoint = this._viewportCoords
39988 .canvasToBasic(canvasPoint[0], canvasPoint[1], container, transform, render.perspective);
39989 if (basicPoint[0] < 0 || basicPoint[0] > 1 || basicPoint[1] < 0 || basicPoint[1] > 1) {
39994 Projection.prototype.eventToUnprojection = function (event, container, render, reference, transform) {
39995 var pixelPoint = this._viewportCoords.canvasPosition(event, container);
39996 return this.canvasToUnprojection(pixelPoint, container, render, reference, transform);
39998 Projection.prototype.canvasToUnprojection = function (canvasPoint, container, render, reference, transform) {
39999 var canvasX = canvasPoint[0];
40000 var canvasY = canvasPoint[1];
40001 var _a = this._viewportCoords.canvasToViewport(canvasX, canvasY, container), viewportX = _a[0], viewportY = _a[1];
40002 var point3d = new THREE.Vector3(viewportX, viewportY, 1)
40003 .unproject(render.perspective);
40004 var basicPoint = transform.projectBasic(point3d.toArray());
40005 if (basicPoint[0] < 0 || basicPoint[0] > 1 || basicPoint[1] < 0 || basicPoint[1] > 1) {
40008 var direction3d = point3d.clone().sub(render.camera.position).normalize();
40009 var dist = -2 / direction3d.z;
40011 if (dist > 0 && dist < 100 && !!basicPoint) {
40012 var point = direction3d.clone().multiplyScalar(dist).add(render.camera.position);
40013 var latLonArray = this._geoCoords
40014 .enuToGeodetic(point.x, point.y, point.z, reference.lat, reference.lon, reference.alt)
40016 latLon = { lat: latLonArray[0], lon: latLonArray[1] };
40018 var unprojection = {
40019 basicPoint: basicPoint,
40021 pixelPoint: [canvasX, canvasY],
40023 return unprojection;
40027 exports.Projection = Projection;
40028 exports.default = Projection;
40030 },{"../Geo":229,"three":176}],354:[function(require,module,exports){
40032 /// <reference path="../../typings/index.d.ts" />
40033 Object.defineProperty(exports, "__esModule", { value: true });
40034 var THREE = require("three");
40035 var vd = require("virtual-dom");
40036 var Subject_1 = require("rxjs/Subject");
40037 require("rxjs/add/operator/publishReplay");
40038 require("rxjs/add/operator/scan");
40039 require("rxjs/add/operator/startWith");
40040 var Viewer_1 = require("../Viewer");
40041 var SpriteAtlas = (function () {
40042 function SpriteAtlas() {
40044 Object.defineProperty(SpriteAtlas.prototype, "json", {
40045 set: function (value) {
40046 this._json = value;
40051 Object.defineProperty(SpriteAtlas.prototype, "image", {
40052 set: function (value) {
40053 this._image = value;
40054 this._texture = new THREE.Texture(this._image);
40055 this._texture.minFilter = THREE.NearestFilter;
40060 Object.defineProperty(SpriteAtlas.prototype, "loaded", {
40062 return !!(this._image && this._json);
40067 SpriteAtlas.prototype.getGLSprite = function (name) {
40068 if (!this.loaded) {
40069 throw new Error("Sprites cannot be retrieved before the atlas is loaded.");
40071 var definition = this._json[name];
40073 console.warn("Sprite with key" + name + "does not exist in sprite definition.");
40074 return new THREE.Object3D();
40076 var texture = this._texture.clone();
40077 texture.needsUpdate = true;
40078 var width = this._image.width;
40079 var height = this._image.height;
40080 texture.offset.x = definition.x / width;
40081 texture.offset.y = (height - definition.y - definition.height) / height;
40082 texture.repeat.x = definition.width / width;
40083 texture.repeat.y = definition.height / height;
40084 var material = new THREE.SpriteMaterial({ map: texture });
40085 return new THREE.Sprite(material);
40087 SpriteAtlas.prototype.getDOMSprite = function (name, float) {
40088 if (!this.loaded) {
40089 throw new Error("Sprites cannot be retrieved before the atlas is loaded.");
40091 if (float == null) {
40092 float = Viewer_1.Alignment.Center;
40094 var definition = this._json[name];
40096 console.warn("Sprite with key" + name + "does not exist in sprite definition.");
40097 return vd.h("div", {}, []);
40099 var clipTop = definition.y;
40100 var clipRigth = definition.x + definition.width;
40101 var clipBottom = definition.y + definition.height;
40102 var clipLeft = definition.x;
40103 var left = -definition.x;
40104 var top = -definition.y;
40105 var height = this._image.height;
40106 var width = this._image.width;
40108 case Viewer_1.Alignment.Bottom:
40109 case Viewer_1.Alignment.Center:
40110 case Viewer_1.Alignment.Top:
40111 left -= definition.width / 2;
40113 case Viewer_1.Alignment.BottomLeft:
40114 case Viewer_1.Alignment.Left:
40115 case Viewer_1.Alignment.TopLeft:
40116 left -= definition.width;
40118 case Viewer_1.Alignment.BottomRight:
40119 case Viewer_1.Alignment.Right:
40120 case Viewer_1.Alignment.BottomRight:
40125 case Viewer_1.Alignment.Center:
40126 case Viewer_1.Alignment.Left:
40127 case Viewer_1.Alignment.Right:
40128 top -= definition.height / 2;
40130 case Viewer_1.Alignment.Top:
40131 case Viewer_1.Alignment.TopLeft:
40132 case Viewer_1.Alignment.TopRight:
40133 top -= definition.height;
40135 case Viewer_1.Alignment.Bottom:
40136 case Viewer_1.Alignment.BottomLeft:
40137 case Viewer_1.Alignment.BottomRight:
40141 var pixelRatioInverse = 1 / definition.pixelRatio;
40142 clipTop *= pixelRatioInverse;
40143 clipRigth *= pixelRatioInverse;
40144 clipBottom *= pixelRatioInverse;
40145 clipLeft *= pixelRatioInverse;
40146 left *= pixelRatioInverse;
40147 top *= pixelRatioInverse;
40148 height *= pixelRatioInverse;
40149 width *= pixelRatioInverse;
40151 src: this._image.src,
40153 clip: "rect(" + clipTop + "px, " + clipRigth + "px, " + clipBottom + "px, " + clipLeft + "px)",
40154 height: height + "px",
40156 position: "absolute",
40158 width: width + "px",
40161 return vd.h("img", properties, []);
40163 return SpriteAtlas;
40165 var SpriteService = (function () {
40166 function SpriteService(sprite) {
40168 this._retina = window.devicePixelRatio > 1;
40169 this._spriteAtlasOperation$ = new Subject_1.Subject();
40170 this._spriteAtlas$ = this._spriteAtlasOperation$
40171 .startWith(function (atlas) {
40174 .scan(function (atlas, operation) {
40175 return operation(atlas);
40176 }, new SpriteAtlas())
40179 this._spriteAtlas$.subscribe(function () { });
40180 if (sprite == null) {
40183 var format = this._retina ? "@2x" : "";
40184 var imageXmlHTTP = new XMLHttpRequest();
40185 imageXmlHTTP.open("GET", sprite + format + ".png", true);
40186 imageXmlHTTP.responseType = "arraybuffer";
40187 imageXmlHTTP.onload = function () {
40188 var image = new Image();
40189 image.onload = function () {
40190 _this._spriteAtlasOperation$.next(function (atlas) {
40191 atlas.image = image;
40195 var blob = new Blob([imageXmlHTTP.response]);
40196 image.src = window.URL.createObjectURL(blob);
40198 imageXmlHTTP.onerror = function (error) {
40199 console.error(new Error("Failed to fetch sprite sheet (" + sprite + format + ".png)"));
40201 imageXmlHTTP.send();
40202 var jsonXmlHTTP = new XMLHttpRequest();
40203 jsonXmlHTTP.open("GET", sprite + format + ".json", true);
40204 jsonXmlHTTP.responseType = "text";
40205 jsonXmlHTTP.onload = function () {
40206 var json = JSON.parse(jsonXmlHTTP.response);
40207 _this._spriteAtlasOperation$.next(function (atlas) {
40212 jsonXmlHTTP.onerror = function (error) {
40213 console.error(new Error("Failed to fetch sheet (" + sprite + format + ".json)"));
40215 jsonXmlHTTP.send();
40217 Object.defineProperty(SpriteService.prototype, "spriteAtlas$", {
40219 return this._spriteAtlas$;
40224 return SpriteService;
40226 exports.SpriteService = SpriteService;
40227 exports.default = SpriteService;
40229 },{"../Viewer":236,"rxjs/Subject":34,"rxjs/add/operator/publishReplay":72,"rxjs/add/operator/scan":73,"rxjs/add/operator/startWith":78,"three":176,"virtual-dom":182}],355:[function(require,module,exports){
40231 Object.defineProperty(exports, "__esModule", { value: true });
40232 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
40233 var Observable_1 = require("rxjs/Observable");
40234 var Subject_1 = require("rxjs/Subject");
40235 require("rxjs/add/observable/timer");
40236 require("rxjs/add/operator/bufferWhen");
40237 require("rxjs/add/operator/filter");
40238 require("rxjs/add/operator/map");
40239 require("rxjs/add/operator/merge");
40240 require("rxjs/add/operator/scan");
40241 require("rxjs/add/operator/switchMap");
40242 var TouchService = (function () {
40243 function TouchService(canvasContainer, domContainer) {
40245 this._canvasContainer = canvasContainer;
40246 this._domContainer = domContainer;
40247 this._activeSubject$ = new BehaviorSubject_1.BehaviorSubject(false);
40248 this._active$ = this._activeSubject$
40249 .distinctUntilChanged()
40252 Observable_1.Observable.fromEvent(domContainer, "touchmove")
40253 .subscribe(function (event) {
40254 event.preventDefault();
40256 this._touchStart$ = Observable_1.Observable.fromEvent(canvasContainer, "touchstart");
40257 this._touchMove$ = Observable_1.Observable.fromEvent(canvasContainer, "touchmove");
40258 this._touchEnd$ = Observable_1.Observable.fromEvent(canvasContainer, "touchend");
40259 this._touchCancel$ = Observable_1.Observable.fromEvent(canvasContainer, "touchcancel");
40260 var tapStart$ = this._touchStart$
40261 .filter(function (te) {
40262 return te.touches.length === 1 && te.targetTouches.length === 1;
40265 this._doubleTap$ = tapStart$
40266 .bufferWhen(function () {
40269 .switchMap(function (event) {
40270 return Observable_1.Observable
40276 .filter(function (events) {
40277 return events.length === 2;
40279 .map(function (events) {
40280 return events[events.length - 1];
40284 .subscribe(function (event) {
40285 event.preventDefault();
40287 this._singleTouchMove$ = this._touchMove$
40288 .filter(function (te) {
40289 return te.touches.length === 1 && te.targetTouches.length === 1;
40292 var singleTouchStart$ = Observable_1.Observable
40293 .merge(this._touchStart$, this._touchEnd$, this._touchCancel$)
40294 .filter(function (te) {
40295 return te.touches.length === 1 && te.targetTouches.length === 1;
40297 var multipleTouchStart$ = Observable_1.Observable
40298 .merge(this._touchStart$, this._touchEnd$, this._touchCancel$)
40299 .filter(function (te) {
40300 return te.touches.length >= 1;
40302 var touchStop$ = Observable_1.Observable
40303 .merge(this._touchEnd$, this._touchCancel$)
40304 .filter(function (te) {
40305 return te.touches.length === 0;
40307 this._singleTouchDragStart$ = singleTouchStart$
40308 .mergeMap(function (e) {
40309 return _this._singleTouchMove$
40310 .takeUntil(Observable_1.Observable.merge(touchStop$, multipleTouchStart$))
40313 this._singleTouchDragEnd$ = singleTouchStart$
40314 .mergeMap(function (e) {
40315 return Observable_1.Observable
40316 .merge(touchStop$, multipleTouchStart$)
40319 this._singleTouchDrag$ = singleTouchStart$
40320 .switchMap(function (te) {
40321 return _this._singleTouchMove$
40323 .takeUntil(Observable_1.Observable
40324 .merge(multipleTouchStart$, touchStop$));
40326 var touchesChanged$ = Observable_1.Observable
40327 .merge(this._touchStart$, this._touchEnd$, this._touchCancel$);
40328 this._pinchStart$ = touchesChanged$
40329 .filter(function (te) {
40330 return te.touches.length === 2 && te.targetTouches.length === 2;
40332 this._pinchEnd$ = touchesChanged$
40333 .filter(function (te) {
40334 return te.touches.length !== 2 || te.targetTouches.length !== 2;
40336 this._pinchOperation$ = new Subject_1.Subject();
40337 this._pinch$ = this._pinchOperation$
40338 .scan(function (pinch, operation) {
40339 return operation(pinch);
40349 originalEvent: null,
40358 .filter(function (te) {
40359 return te.touches.length === 2 && te.targetTouches.length === 2;
40361 .map(function (te) {
40362 return function (previous) {
40363 var touch1 = te.touches[0];
40364 var touch2 = te.touches[1];
40365 var minX = Math.min(touch1.clientX, touch2.clientX);
40366 var maxX = Math.max(touch1.clientX, touch2.clientX);
40367 var minY = Math.min(touch1.clientY, touch2.clientY);
40368 var maxY = Math.max(touch1.clientY, touch2.clientY);
40369 var centerClientX = minX + (maxX - minX) / 2;
40370 var centerClientY = minY + (maxY - minY) / 2;
40371 var centerPageX = centerClientX + touch1.pageX - touch1.clientX;
40372 var centerPageY = centerClientY + touch1.pageY - touch1.clientY;
40373 var centerScreenX = centerClientX + touch1.screenX - touch1.clientX;
40374 var centerScreenY = centerClientY + touch1.screenY - touch1.clientY;
40375 var distanceX = Math.abs(touch1.clientX - touch2.clientX);
40376 var distanceY = Math.abs(touch1.clientY - touch2.clientY);
40377 var distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
40378 var distanceChange = distance - previous.distance;
40379 var changeX = distanceX - previous.distanceX;
40380 var changeY = distanceY - previous.distanceY;
40384 clientX: centerClientX,
40385 clientY: centerClientY,
40386 distance: distance,
40387 distanceChange: distanceChange,
40388 distanceX: distanceX,
40389 distanceY: distanceY,
40391 pageX: centerPageX,
40392 pageY: centerPageY,
40393 screenX: centerScreenX,
40394 screenY: centerScreenY,
40401 .subscribe(this._pinchOperation$);
40402 this._pinchChange$ = this._pinchStart$
40403 .switchMap(function (te) {
40404 return _this._pinch$
40406 .takeUntil(_this._pinchEnd$);
40409 Object.defineProperty(TouchService.prototype, "active$", {
40411 return this._active$;
40416 Object.defineProperty(TouchService.prototype, "activate$", {
40418 return this._activeSubject$;
40423 Object.defineProperty(TouchService.prototype, "doubleTap$", {
40425 return this._doubleTap$;
40430 Object.defineProperty(TouchService.prototype, "touchStart$", {
40432 return this._touchStart$;
40437 Object.defineProperty(TouchService.prototype, "touchMove$", {
40439 return this._touchMove$;
40444 Object.defineProperty(TouchService.prototype, "touchEnd$", {
40446 return this._touchEnd$;
40451 Object.defineProperty(TouchService.prototype, "touchCancel$", {
40453 return this._touchCancel$;
40458 Object.defineProperty(TouchService.prototype, "singleTouchDragStart$", {
40460 return this._singleTouchDragStart$;
40465 Object.defineProperty(TouchService.prototype, "singleTouchDrag$", {
40467 return this._singleTouchDrag$;
40472 Object.defineProperty(TouchService.prototype, "singleTouchDragEnd$", {
40474 return this._singleTouchDragEnd$;
40479 Object.defineProperty(TouchService.prototype, "pinch$", {
40481 return this._pinchChange$;
40486 Object.defineProperty(TouchService.prototype, "pinchStart$", {
40488 return this._pinchStart$;
40493 Object.defineProperty(TouchService.prototype, "pinchEnd$", {
40495 return this._pinchEnd$;
40500 return TouchService;
40502 exports.TouchService = TouchService;
40504 },{"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}],356:[function(require,module,exports){
40506 /// <reference path="../../typings/index.d.ts" />
40507 var __extends = (this && this.__extends) || (function () {
40508 var extendStatics = Object.setPrototypeOf ||
40509 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
40510 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
40511 return function (d, b) {
40512 extendStatics(d, b);
40513 function __() { this.constructor = d; }
40514 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
40517 Object.defineProperty(exports, "__esModule", { value: true });
40518 var when = require("when");
40519 var Viewer_1 = require("../Viewer");
40520 var Utils_1 = require("../Utils");
40524 * @classdesc The Viewer object represents the navigable photo viewer.
40525 * Create a Viewer by specifying a container, client ID, photo key and
40526 * other options. The viewer exposes methods and events for programmatic
40529 * The viewer works with a few different coordinate systems.
40531 * Container pixel coordinates
40533 * Pixel coordinates are coordinates on the viewer container. The origin is
40534 * in the top left corner of the container. The axes are
40535 * directed according to the following for a viewer container with a width
40536 * of 640 pixels and height of 480 pixels.
40540 * +------------------------>
40545 * (0, 480) (640, 480)
40548 * Basic image coordinates
40550 * Basic image coordinates represents points in the original image adjusted for
40551 * orientation. They range from 0 to 1 on both axes. The origin is in the top left
40552 * corner of the image and the axes are directed
40553 * according to the following for all image types.
40557 * +------------------------>
40565 * For every camera viewing direction it is possible to convert between these
40566 * two coordinate systems for the current node. The image can be panned and
40567 * zoomed independently of the size of the viewer container resulting in
40568 * different conversion results for different viewing directions.
40570 var Viewer = (function (_super) {
40571 __extends(Viewer, _super);
40573 * Create a new viewer instance.
40575 * @param {string} id - Required `id` of a DOM element which will
40576 * be transformed into the viewer.
40577 * @param {string} clientId - Required `Mapillary API ClientID`. Can
40578 * be obtained from https://www.mapillary.com/app/settings/developers.
40579 * @param {string} [key] - Optional `photoId` to start from, can be any
40580 * Mapillary photo, if null no image is loaded.
40581 * @param {IViewerOptions} [options] - Optional configuration object
40582 * specifing Viewer's initial setup.
40583 * @param {string} [token] - Optional bearer token for API requests of
40584 * protected resources.
40588 * var viewer = new Mapillary.Viewer("<element-id>", "<client-id>", "<my key>");
40591 function Viewer(id, clientId, key, options, token) {
40592 var _this = _super.call(this) || this;
40593 options = options != null ? options : {};
40594 Utils_1.Settings.setOptions(options);
40595 _this._navigator = new Viewer_1.Navigator(clientId, token);
40596 _this._container = new Viewer_1.Container(id, _this._navigator.stateService, options);
40597 _this._observer = new Viewer_1.Observer(_this, _this._navigator, _this._container);
40598 _this._componentController = new Viewer_1.ComponentController(_this._container, _this._navigator, _this._observer, key, options.component);
40602 * Activate a component.
40604 * @param {string} name - Name of the component which will become active.
40608 * viewer.activateComponent("marker");
40611 Viewer.prototype.activateComponent = function (name) {
40612 this._componentController.activate(name);
40615 * Activate the cover (deactivates all other components).
40617 Viewer.prototype.activateCover = function () {
40618 this._componentController.activateCover();
40621 * Deactivate a component.
40623 * @param {string} name - Name of component which become inactive.
40627 * viewer.deactivateComponent("mouse");
40630 Viewer.prototype.deactivateComponent = function (name) {
40631 this._componentController.deactivate(name);
40634 * Deactivate the cover (activates all components marked as active).
40636 Viewer.prototype.deactivateCover = function () {
40637 this._componentController.deactivateCover();
40640 * Get the bearing of the current viewer camera.
40642 * @description The bearing depends on how the camera
40643 * is currently rotated and does not correspond
40644 * to the compass angle of the current node if the view
40647 * Bearing is measured in degrees clockwise with respect to
40650 * @returns {Promise<number>} Promise to the bearing
40651 * of the current viewer camera.
40655 * viewer.getBearing().then((b) => { console.log(b); });
40658 Viewer.prototype.getBearing = function () {
40660 return when.promise(function (resolve, reject) {
40661 _this._container.renderService.bearing$
40663 .subscribe(function (bearing) {
40665 }, function (error) {
40671 * Get the basic coordinates of the current photo that is
40672 * at the center of the viewport.
40674 * @description Basic coordinates are 2D coordinates on the [0, 1] interval
40675 * and have the origin point, (0, 0), at the top left corner and the
40676 * maximum value, (1, 1), at the bottom right corner of the original
40679 * @returns {Promise<number[]>} Promise to the basic coordinates
40680 * of the current photo at the center for the viewport.
40684 * viewer.getCenter().then((c) => { console.log(c); });
40687 Viewer.prototype.getCenter = function () {
40689 return when.promise(function (resolve, reject) {
40690 _this._navigator.stateService.getCenter()
40691 .subscribe(function (center) {
40693 }, function (error) {
40701 * @param {string} name - Name of component.
40702 * @returns {Component} The requested component.
40706 * var mouseComponent = viewer.getComponent("mouse");
40709 Viewer.prototype.getComponent = function (name) {
40710 return this._componentController.get(name);
40713 * Returns the viewer's containing HTML element.
40715 * @returns {HTMLElement} The viewer's container.
40717 Viewer.prototype.getContainer = function () {
40718 return this._container.element;
40721 * Get the photo's current zoom level.
40723 * @returns {Promise<number>} Promise to the viewers's current
40728 * viewer.getZoom().then((z) => { console.log(z); });
40731 Viewer.prototype.getZoom = function () {
40733 return when.promise(function (resolve, reject) {
40734 _this._navigator.stateService.getZoom()
40735 .subscribe(function (zoom) {
40737 }, function (error) {
40743 * Move close to given latitude and longitude.
40745 * @description Because the method propagates IO errors, these potential errors
40746 * need to be handled by the method caller (see example).
40748 * @param {Number} lat - Latitude, in degrees.
40749 * @param {Number} lon - Longitude, in degrees.
40750 * @returns {Promise<Node>} Promise to the node that was navigated to.
40751 * @throws {Error} If no nodes exist close to provided latitude
40753 * @throws {Error} Propagates any IO errors to the caller.
40757 * viewer.moveCloseTo(0, 0).then(
40758 * (n) => { console.log(n); },
40759 * (e) => { console.error(e); });
40762 Viewer.prototype.moveCloseTo = function (lat, lon) {
40764 return when.promise(function (resolve, reject) {
40765 _this._navigator.moveCloseTo$(lat, lon).subscribe(function (node) {
40767 }, function (error) {
40773 * Navigate in a given direction.
40775 * @description This method has to be called through EdgeDirection enumeration as in the example.
40777 * @param {EdgeDirection} dir - Direction in which which to move.
40778 * @returns {Promise<Node>} Promise to the node that was navigated to.
40779 * @throws {Error} If the current node does not have the edge direction
40780 * or the edges has not yet been cached.
40781 * @throws {Error} Propagates any IO errors to the caller.
40785 * viewer.moveDir(Mapillary.EdgeDirection.Next).then(
40786 * (n) => { console.log(n); },
40787 * (e) => { console.error(e); });
40790 Viewer.prototype.moveDir = function (dir) {
40792 return when.promise(function (resolve, reject) {
40793 _this._navigator.moveDir$(dir).subscribe(function (node) {
40795 }, function (error) {
40801 * Navigate to a given photo key.
40803 * @param {string} key - A valid Mapillary photo key.
40804 * @returns {Promise<Node>} Promise to the node that was navigated to.
40805 * @throws {Error} Propagates any IO errors to the caller.
40809 * viewer.moveToKey("<my key>").then(
40810 * (n) => { console.log(n); },
40811 * (e) => { console.error(e); });
40814 Viewer.prototype.moveToKey = function (key) {
40816 return when.promise(function (resolve, reject) {
40817 _this._navigator.moveToKey$(key).subscribe(function (node) {
40819 }, function (error) {
40825 * Project basic image coordinates for the current node to canvas pixel
40828 * @description The basic image coordinates may not always correspond to a
40829 * pixel point that lies in the visible area of the viewer container.
40831 * @param {Array<number>} basicPoint - Basic images coordinates to project.
40832 * @returns {Promise<ILatLon>} Promise to the pixel coordinates corresponding
40833 * to the basic image point.
40837 * viewer.projectFromBasic([0.3, 0.7])
40838 * .then((pixelPoint) => { console.log(pixelPoint); });
40841 Viewer.prototype.projectFromBasic = function (basicPoint) {
40843 return when.promise(function (resolve, reject) {
40844 _this._observer.projectBasic$(basicPoint)
40845 .subscribe(function (pixelPoint) {
40846 resolve(pixelPoint);
40847 }, function (error) {
40853 * Detect the viewer's new width and height and resize it.
40855 * @description The components will also detect the viewer's
40856 * new size and resize their rendered elements if needed.
40863 Viewer.prototype.resize = function () {
40864 this._container.renderService.resize$.next(null);
40865 this._componentController.resize();
40868 * Set a bearer token for authenticated API requests of
40869 * protected resources.
40871 * @description When the supplied token is null or undefined,
40872 * any previously set bearer token will be cleared and the
40873 * viewer will make unauthenticated requests.
40875 * Calling setAuthToken aborts all outstanding move requests.
40876 * The promises of those move requests will be rejected and
40877 * the rejections need to be caught.
40879 * @param {string} [token] token - Bearer token.
40880 * @returns {Promise<void>} Promise that resolves after token
40885 * viewer.setAuthToken("<my token>")
40886 * .then(() => { console.log("token set"); });
40889 Viewer.prototype.setAuthToken = function (token) {
40891 return when.promise(function (resolve, reject) {
40892 _this._navigator.setToken$(token)
40893 .subscribe(function () {
40894 resolve(undefined);
40895 }, function (error) {
40901 * Set the basic coordinates of the current photo to be in the
40902 * center of the viewport.
40904 * @description Basic coordinates are 2D coordinates on the [0, 1] interval
40905 * and has the origin point, (0, 0), at the top left corner and the
40906 * maximum value, (1, 1), at the bottom right corner of the original
40909 * @param {number[]} The basic coordinates of the current
40910 * photo to be at the center for the viewport.
40914 * viewer.setCenter([0.5, 0.5]);
40917 Viewer.prototype.setCenter = function (center) {
40918 this._navigator.stateService.setCenter(center);
40921 * Set the filter selecting nodes to use when calculating
40922 * the spatial edges.
40924 * @description The following filter types are supported:
40928 * `["==", key, value]` equality: `node[key] = value`
40930 * `["!=", key, value]` inequality: `node[key] ≠ value`
40932 * `["<", key, value]` less than: `node[key] < value`
40934 * `["<=", key, value]` less than or equal: `node[key] ≤ value`
40936 * `[">", key, value]` greater than: `node[key] > value`
40938 * `[">=", key, value]` greater than or equal: `node[key] ≥ value`
40942 * `["in", key, v0, ..., vn]` set inclusion: `node[key] ∈ {v0, ..., vn}`
40944 * `["!in", key, v0, ..., vn]` set exclusion: `node[key] ∉ {v0, ..., vn}`
40948 * `["all", f0, ..., fn]` logical `AND`: `f0 ∧ ... ∧ fn`
40950 * A key must be a string that identifies a node property name. A value must be
40951 * a string, number, or boolean. Strictly-typed comparisons are used. The values
40952 * `f0, ..., fn` of the combining filter must be filter expressions.
40954 * Clear the filter by setting it to null or empty array.
40956 * @param {FilterExpression} filter - The filter expression.
40957 * @returns {Promise<void>} Promise that resolves after filter is applied.
40961 * viewer.setFilter(["==", "sequenceKey", "<my sequence key>"]);
40964 Viewer.prototype.setFilter = function (filter) {
40966 return when.promise(function (resolve, reject) {
40967 _this._navigator.setFilter$(filter)
40968 .subscribe(function () {
40969 resolve(undefined);
40970 }, function (error) {
40976 * Set the viewer's render mode.
40978 * @param {RenderMode} renderMode - Render mode.
40982 * viewer.setRenderMode(Mapillary.RenderMode.Letterbox);
40985 Viewer.prototype.setRenderMode = function (renderMode) {
40986 this._container.renderService.renderMode$.next(renderMode);
40989 * Set the photo's current zoom level.
40991 * @description Possible zoom level values are on the [0, 3] interval.
40992 * Zero means zooming out to fit the photo to the view whereas three
40993 * shows the highest level of detail.
40995 * @param {number} The photo's current zoom level.
40999 * viewer.setZoom(2);
41002 Viewer.prototype.setZoom = function (zoom) {
41003 this._navigator.stateService.setZoom(zoom);
41006 * Unproject canvas pixel coordinates to an ILatLon representing geographical
41009 * @description The pixel point may not always correspond to geographical
41010 * coordinates. In the case of no correspondence the returned value will
41013 * @param {Array<number>} pixelPoint - Pixel coordinates to unproject.
41014 * @returns {Promise<ILatLon>} Promise to the latLon corresponding to the pixel point.
41018 * viewer.unproject([100, 100])
41019 * .then((latLon) => { console.log(latLon); });
41022 Viewer.prototype.unproject = function (pixelPoint) {
41024 return when.promise(function (resolve, reject) {
41025 _this._observer.unproject$(pixelPoint)
41026 .subscribe(function (latLon) {
41028 }, function (error) {
41034 * Unproject canvas pixel coordinates to basic image coordinates for the
41037 * @description The pixel point may not always correspond to basic image
41038 * coordinates. In the case of no correspondence the returned value will
41041 * @param {Array<number>} pixelPoint - Pixel coordinates to unproject.
41042 * @returns {Promise<ILatLon>} Promise to the basic coordinates corresponding
41043 * to the pixel point.
41047 * viewer.unprojectToBasic([100, 100])
41048 * .then((basicPoint) => { console.log(basicPoint); });
41051 Viewer.prototype.unprojectToBasic = function (pixelPoint) {
41053 return when.promise(function (resolve, reject) {
41054 _this._observer.unprojectBasic$(pixelPoint)
41055 .subscribe(function (basicPoint) {
41056 resolve(basicPoint);
41057 }, function (error) {
41063 * Fired when the viewing direction of the camera changes.
41065 * @type {number} bearing - Value indicating the current bearing
41066 * measured in degrees clockwise with respect to north.
41068 Viewer.bearingchanged = "bearingchanged";
41070 * Fired when a pointing device (usually a mouse) is pressed and released at
41071 * the same point in the viewer.
41073 * @type {IViewerMouseEvent} event - Viewer mouse event data.
41075 Viewer.click = "click";
41077 * Fired when the right button of the mouse is clicked within the viewer.
41079 * @type {IViewerMouseEvent} event - Viewer mouse event data.
41081 Viewer.contextmenu = "contextmenu";
41083 * Fired when a pointing device (usually a mouse) is clicked twice at
41084 * the same point in the viewer.
41086 * @type {IViewerMouseEvent} event - Viewer mouse event data.
41088 Viewer.dblclick = "dblclick";
41090 * Fired when the viewer is loading more data.
41092 * @type {boolean} loading - Value indicating whether the viewer is loading.
41094 Viewer.loadingchanged = "loadingchanged";
41096 * Fired when a pointing device (usually a mouse) is pressed within the viewer.
41098 * @type {IViewerMouseEvent} event - Viewer mouse event data.
41100 Viewer.mousedown = "mousedown";
41102 * Fired when a pointing device (usually a mouse) is moved within the viewer.
41103 * @description Will not fire when the mouse is actively used, e.g. for drag pan.
41105 * @type {IViewerMouseEvent} event - Viewer mouse event data.
41107 Viewer.mousemove = "mousemove";
41109 * Fired when a pointing device (usually a mouse) leaves the viewer's canvas.
41111 * @type {IViewerMouseEvent} event - Viewer mouse event data.
41113 Viewer.mouseout = "mouseout";
41115 * Fired when a pointing device (usually a mouse) is moved onto the viewer's canvas.
41117 * @type {IViewerMouseEvent} event - Viewer mouse event data.
41119 Viewer.mouseover = "mouseover";
41121 * Fired when a pointing device (usually a mouse) is released within the viewer.
41123 * @type {IViewerMouseEvent} event - Viewer mouse event data.
41125 Viewer.mouseup = "mouseup";
41127 * Fired when the viewer motion stops and it is in a fixed
41128 * position with a fixed point of view.
41131 Viewer.moveend = "moveend";
41133 * Fired when the motion from one view to another start,
41134 * either by changing the position (e.g. when changing node) or
41135 * when changing point of view (e.g. by interaction such as pan and zoom).
41138 Viewer.movestart = "movestart";
41140 * Fired every time the viewer navigates to a new node.
41142 * @type {Node} node - Current node.
41144 Viewer.nodechanged = "nodechanged";
41146 * Fired every time the sequence edges of the current node changes.
41148 * @type {IEdgeStatus} status - The edge status object.
41150 Viewer.sequenceedgeschanged = "sequenceedgeschanged";
41152 * Fired every time the spatial edges of the current node changes.
41154 * @type {IEdgeStatus} status - The edge status object.
41156 Viewer.spatialedgeschanged = "spatialedgeschanged";
41158 }(Utils_1.EventEmitter));
41159 exports.Viewer = Viewer;
41161 },{"../Utils":235,"../Viewer":236,"when":223}]},{},[231])(231)
41163 //# sourceMappingURL=mapillary.js.map