]> git.openstreetmap.org Git - rails.git/blob - vendor/assets/iD/iD/mapillary-js/mapillary.js
Merge branch 'master' into moderation
[rails.git] / vendor / assets / iD / iD / mapillary-js / mapillary.js
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){
2 'use strict';
3
4 var Queue = require('tinyqueue');
5
6 module.exports = polylabel;
7 module.exports.default = polylabel;
8
9 function polylabel(polygon, precision, debug) {
10     precision = precision || 1.0;
11
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];
20     }
21
22     var width = maxX - minX;
23     var height = maxY - minY;
24     var cellSize = Math.min(width, height);
25     var h = cellSize / 2;
26
27     // a priority queue of cells in order of their "potential" (max distance to polygon)
28     var cellQueue = new Queue(null, compareMax);
29
30     if (cellSize === 0) return [minX, minY];
31
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));
36         }
37     }
38
39     // take centroid as the first best guess
40     var bestCell = getCentroidCell(polygon);
41
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;
45
46     var numProbes = cellQueue.length;
47
48     while (cellQueue.length) {
49         // pick the most promising cell from the queue
50         var cell = cellQueue.pop();
51
52         // update the best cell if we found a better one
53         if (cell.d > bestCell.d) {
54             bestCell = cell;
55             if (debug) console.log('found best %d after %d probes', Math.round(1e4 * cell.d) / 1e4, numProbes);
56         }
57
58         // do not drill down further if there's no chance of a better solution
59         if (cell.max - bestCell.d <= precision) continue;
60
61         // split the cell into four cells
62         h = cell.h / 2;
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));
67         numProbes += 4;
68     }
69
70     if (debug) {
71         console.log('num probes: ' + numProbes);
72         console.log('best distance: ' + bestCell.d);
73     }
74
75     return [bestCell.x, bestCell.y];
76 }
77
78 function compareMax(a, b) {
79     return b.max - a.max;
80 }
81
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
88 }
89
90 // signed distance from point to polygon outline (negative if point is outside)
91 function pointToPolygonDist(x, y, polygon) {
92     var inside = false;
93     var minDistSq = Infinity;
94
95     for (var k = 0; k < polygon.length; k++) {
96         var ring = polygon[k];
97
98         for (var i = 0, len = ring.length, j = len - 1; i < len; j = i++) {
99             var a = ring[i];
100             var b = ring[j];
101
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;
104
105             minDistSq = Math.min(minDistSq, getSegDistSq(x, y, a, b));
106         }
107     }
108
109     return (inside ? 1 : -1) * Math.sqrt(minDistSq);
110 }
111
112 // get polygon centroid
113 function getCentroidCell(polygon) {
114     var area = 0;
115     var x = 0;
116     var y = 0;
117     var points = polygon[0];
118
119     for (var i = 0, len = points.length, j = len - 1; i < len; j = i++) {
120         var a = points[i];
121         var b = points[j];
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;
125         area += f * 3;
126     }
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);
129 }
130
131 // get squared distance from a point to a segment
132 function getSegDistSq(px, py, a, b) {
133
134     var x = a[0];
135     var y = a[1];
136     var dx = b[0] - x;
137     var dy = b[1] - y;
138
139     if (dx !== 0 || dy !== 0) {
140
141         var t = ((px - x) * dx + (py - y) * dy) / (dx * dx + dy * dy);
142
143         if (t > 1) {
144             x = b[0];
145             y = b[1];
146
147         } else if (t > 0) {
148             x += dx * t;
149             y += dy * t;
150         }
151     }
152
153     dx = px - x;
154     dy = py - y;
155
156     return dx * dx + dy * dy;
157 }
158
159 },{"tinyqueue":242}],2:[function(require,module,exports){
160 /*
161  * Copyright (C) 2008 Apple Inc. All Rights Reserved.
162  *
163  * Redistribution and use in source and binary forms, with or without
164  * modification, are permitted provided that the following conditions
165  * are met:
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.
171  *
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.
183  *
184  * Ported from Webkit
185  * http://svn.webkit.org/repository/webkit/trunk/Source/WebCore/platform/graphics/UnitBezier.h
186  */
187
188 module.exports = UnitBezier;
189
190 function UnitBezier(p1x, p1y, p2x, p2y) {
191     // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1).
192     this.cx = 3.0 * p1x;
193     this.bx = 3.0 * (p2x - p1x) - this.cx;
194     this.ax = 1.0 - this.cx - this.bx;
195
196     this.cy = 3.0 * p1y;
197     this.by = 3.0 * (p2y - p1y) - this.cy;
198     this.ay = 1.0 - this.cy - this.by;
199
200     this.p1x = p1x;
201     this.p1y = p2y;
202     this.p2x = p2x;
203     this.p2y = p2y;
204 }
205
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;
209 };
210
211 UnitBezier.prototype.sampleCurveY = function(t) {
212     return ((this.ay * t + this.by) * t + this.cy) * t;
213 };
214
215 UnitBezier.prototype.sampleCurveDerivativeX = function(t) {
216     return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx;
217 };
218
219 UnitBezier.prototype.solveCurveX = function(x, epsilon) {
220     if (typeof epsilon === 'undefined') epsilon = 1e-6;
221
222     var t0, t1, t2, x2, i;
223
224     // First try a few iterations of Newton's method -- normally very fast.
225     for (t2 = x, i = 0; i < 8; i++) {
226
227         x2 = this.sampleCurveX(t2) - x;
228         if (Math.abs(x2) < epsilon) return t2;
229
230         var d2 = this.sampleCurveDerivativeX(t2);
231         if (Math.abs(d2) < 1e-6) break;
232
233         t2 = t2 - x2 / d2;
234     }
235
236     // Fall back to the bisection method for reliability.
237     t0 = 0.0;
238     t1 = 1.0;
239     t2 = x;
240
241     if (t2 < t0) return t0;
242     if (t2 > t1) return t1;
243
244     while (t0 < t1) {
245
246         x2 = this.sampleCurveX(t2);
247         if (Math.abs(x2 - x) < epsilon) return t2;
248
249         if (x > x2) {
250             t0 = t2;
251         } else {
252             t1 = t2;
253         }
254
255         t2 = (t1 - t0) * 0.5 + t0;
256     }
257
258     // Failure.
259     return t2;
260 };
261
262 UnitBezier.prototype.solve = function(x, epsilon) {
263     return this.sampleCurveY(this.solveCurveX(x, epsilon));
264 };
265
266 },{}],3:[function(require,module,exports){
267 'use strict'
268
269 exports.byteLength = byteLength
270 exports.toByteArray = toByteArray
271 exports.fromByteArray = fromByteArray
272
273 var lookup = []
274 var revLookup = []
275 var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
276
277 var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
278 for (var i = 0, len = code.length; i < len; ++i) {
279   lookup[i] = code[i]
280   revLookup[code.charCodeAt(i)] = i
281 }
282
283 revLookup['-'.charCodeAt(0)] = 62
284 revLookup['_'.charCodeAt(0)] = 63
285
286 function placeHoldersCount (b64) {
287   var len = b64.length
288   if (len % 4 > 0) {
289     throw new Error('Invalid string. Length must be a multiple of 4')
290   }
291
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
298 }
299
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)
303 }
304
305 function toByteArray (b64) {
306   var i, l, tmp, placeHolders, arr
307   var len = b64.length
308   placeHolders = placeHoldersCount(b64)
309
310   arr = new Arr((len * 3 / 4) - placeHolders)
311
312   // if there are placeholders, only get up to the last complete 4 chars
313   l = placeHolders > 0 ? len - 4 : len
314
315   var L = 0
316
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
322   }
323
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
331   }
332
333   return arr
334 }
335
336 function tripletToBase64 (num) {
337   return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
338 }
339
340 function encodeChunk (uint8, start, end) {
341   var tmp
342   var output = []
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))
346   }
347   return output.join('')
348 }
349
350 function fromByteArray (uint8) {
351   var tmp
352   var len = uint8.length
353   var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
354   var output = ''
355   var parts = []
356   var maxChunkLength = 16383 // must be multiple of 3
357
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)))
361   }
362
363   // pad the end with zeros, but make sure to not forget the extra bytes
364   if (extraBytes === 1) {
365     tmp = uint8[len - 1]
366     output += lookup[tmp >> 2]
367     output += lookup[(tmp << 4) & 0x3F]
368     output += '=='
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]
374     output += '='
375   }
376
377   parts.push(output)
378
379   return parts.join('')
380 }
381
382 },{}],4:[function(require,module,exports){
383
384 },{}],5:[function(require,module,exports){
385 /*!
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
390  */
391
392 /**
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
397  * cross-browser.
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.
402  * @example
403  *
404  * // Basic use
405  * split('a b c d', ' ');
406  * // -> ['a', 'b', 'c', 'd']
407  *
408  * // With limit
409  * split('a b c d', ' ', 2);
410  * // -> ['a', 'b']
411  *
412  * // Backreferences in result array
413  * split('..word1 word2..', /([a-z]+)(\d+)/i);
414  * // -> ['..', 'word', '1', ' ', 'word', '2', '..']
415  */
416 module.exports = (function split(undef) {
417
418   var nativeSplit = String.prototype.split,
419     compliantExecNpcg = /()??/.exec("")[1] === undef,
420     // NPCG: nonparticipating capturing group
421     self;
422
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);
427     }
428     var output = [],
429       flags = (separator.ignoreCase ? "i" : "") + (separator.multiline ? "m" : "") + (separator.extended ? "x" : "") + // Proposed for ES6
430       (separator.sticky ? "y" : ""),
431       // Firefox 3+
432       lastLastIndex = 0,
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);
440     }
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
447      */
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) {
461                 match[i] = undef;
462               }
463             }
464           });
465         }
466         if (match.length > 1 && match.index < str.length) {
467           Array.prototype.push.apply(output, match.slice(1));
468         }
469         lastLength = match[0].length;
470         lastLastIndex = lastIndex;
471         if (output.length >= limit) {
472           break;
473         }
474       }
475       if (separator.lastIndex === match.index) {
476         separator.lastIndex++; // Avoid an infinite loop
477       }
478     }
479     if (lastLastIndex === str.length) {
480       if (lastLength || !separator.test("")) {
481         output.push("");
482       }
483     } else {
484       output.push(str.slice(lastLastIndex));
485     }
486     return output.length > limit ? output.slice(0, limit) : output;
487   };
488
489   return self;
490 })();
491
492 },{}],6:[function(require,module,exports){
493 // shim for using process in browser
494 var process = module.exports = {};
495
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.
500
501 var cachedSetTimeout;
502 var cachedClearTimeout;
503
504 function defaultSetTimout() {
505     throw new Error('setTimeout has not been defined');
506 }
507 function defaultClearTimeout () {
508     throw new Error('clearTimeout has not been defined');
509 }
510 (function () {
511     try {
512         if (typeof setTimeout === 'function') {
513             cachedSetTimeout = setTimeout;
514         } else {
515             cachedSetTimeout = defaultSetTimout;
516         }
517     } catch (e) {
518         cachedSetTimeout = defaultSetTimout;
519     }
520     try {
521         if (typeof clearTimeout === 'function') {
522             cachedClearTimeout = clearTimeout;
523         } else {
524             cachedClearTimeout = defaultClearTimeout;
525         }
526     } catch (e) {
527         cachedClearTimeout = defaultClearTimeout;
528     }
529 } ())
530 function runTimeout(fun) {
531     if (cachedSetTimeout === setTimeout) {
532         //normal enviroments in sane situations
533         return setTimeout(fun, 0);
534     }
535     // if setTimeout wasn't available but was latter defined
536     if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
537         cachedSetTimeout = setTimeout;
538         return setTimeout(fun, 0);
539     }
540     try {
541         // when when somebody has screwed with setTimeout but no I.E. maddness
542         return cachedSetTimeout(fun, 0);
543     } catch(e){
544         try {
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);
547         } catch(e){
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);
550         }
551     }
552
553
554 }
555 function runClearTimeout(marker) {
556     if (cachedClearTimeout === clearTimeout) {
557         //normal enviroments in sane situations
558         return clearTimeout(marker);
559     }
560     // if clearTimeout wasn't available but was latter defined
561     if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
562         cachedClearTimeout = clearTimeout;
563         return clearTimeout(marker);
564     }
565     try {
566         // when when somebody has screwed with setTimeout but no I.E. maddness
567         return cachedClearTimeout(marker);
568     } catch (e){
569         try {
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);
572         } catch (e){
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);
576         }
577     }
578
579
580
581 }
582 var queue = [];
583 var draining = false;
584 var currentQueue;
585 var queueIndex = -1;
586
587 function cleanUpNextTick() {
588     if (!draining || !currentQueue) {
589         return;
590     }
591     draining = false;
592     if (currentQueue.length) {
593         queue = currentQueue.concat(queue);
594     } else {
595         queueIndex = -1;
596     }
597     if (queue.length) {
598         drainQueue();
599     }
600 }
601
602 function drainQueue() {
603     if (draining) {
604         return;
605     }
606     var timeout = runTimeout(cleanUpNextTick);
607     draining = true;
608
609     var len = queue.length;
610     while(len) {
611         currentQueue = queue;
612         queue = [];
613         while (++queueIndex < len) {
614             if (currentQueue) {
615                 currentQueue[queueIndex].run();
616             }
617         }
618         queueIndex = -1;
619         len = queue.length;
620     }
621     currentQueue = null;
622     draining = false;
623     runClearTimeout(timeout);
624 }
625
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];
631         }
632     }
633     queue.push(new Item(fun, args));
634     if (queue.length === 1 && !draining) {
635         runTimeout(drainQueue);
636     }
637 };
638
639 // v8 likes predictible objects
640 function Item(fun, array) {
641     this.fun = fun;
642     this.array = array;
643 }
644 Item.prototype.run = function () {
645     this.fun.apply(null, this.array);
646 };
647 process.title = 'browser';
648 process.browser = true;
649 process.env = {};
650 process.argv = [];
651 process.version = ''; // empty string to avoid regexp issues
652 process.versions = {};
653
654 function noop() {}
655
656 process.on = noop;
657 process.addListener = noop;
658 process.once = noop;
659 process.off = noop;
660 process.removeListener = noop;
661 process.removeAllListeners = noop;
662 process.emit = noop;
663 process.prependListener = noop;
664 process.prependOnceListener = noop;
665
666 process.listeners = function (name) { return [] }
667
668 process.binding = function (name) {
669     throw new Error('process.binding is not supported');
670 };
671
672 process.cwd = function () { return '/' };
673 process.chdir = function (dir) {
674     throw new Error('process.chdir is not supported');
675 };
676 process.umask = function() { return 0; };
677
678 },{}],7:[function(require,module,exports){
679 /*!
680  * The buffer module from node.js, for the browser.
681  *
682  * @author   Feross Aboukhadijeh <https://feross.org>
683  * @license  MIT
684  */
685 /* eslint-disable no-proto */
686
687 'use strict'
688
689 var base64 = require('base64-js')
690 var ieee754 = require('ieee754')
691
692 exports.Buffer = Buffer
693 exports.SlowBuffer = SlowBuffer
694 exports.INSPECT_MAX_BYTES = 50
695
696 var K_MAX_LENGTH = 0x7fffffff
697 exports.kMaxLength = K_MAX_LENGTH
698
699 /**
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)
704  *
705  * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
706  * Opera 11.6+, iOS 4.2+.
707  *
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.
712  */
713 Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
714
715 if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
716     typeof console.error === 'function') {
717   console.error(
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.'
720   )
721 }
722
723 function typedArraySupport () {
724   // Can typed array instances can be augmented?
725   try {
726     var arr = new Uint8Array(1)
727     arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
728     return arr.foo() === 42
729   } catch (e) {
730     return false
731   }
732 }
733
734 function createBuffer (length) {
735   if (length > K_MAX_LENGTH) {
736     throw new RangeError('Invalid typed array length')
737   }
738   // Return an augmented `Uint8Array` instance
739   var buf = new Uint8Array(length)
740   buf.__proto__ = Buffer.prototype
741   return buf
742 }
743
744 /**
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.
750  *
751  * The `Uint8Array` prototype remains unmodified.
752  */
753
754 function Buffer (arg, encodingOrOffset, length) {
755   // Common case.
756   if (typeof arg === 'number') {
757     if (typeof encodingOrOffset === 'string') {
758       throw new Error(
759         'If encoding is specified then the first argument must be a string'
760       )
761     }
762     return allocUnsafe(arg)
763   }
764   return from(arg, encodingOrOffset, length)
765 }
766
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, {
771     value: null,
772     configurable: true,
773     enumerable: false,
774     writable: false
775   })
776 }
777
778 Buffer.poolSize = 8192 // not used by this implementation
779
780 function from (value, encodingOrOffset, length) {
781   if (typeof value === 'number') {
782     throw new TypeError('"value" argument must not be a number')
783   }
784
785   if (isArrayBuffer(value)) {
786     return fromArrayBuffer(value, encodingOrOffset, length)
787   }
788
789   if (typeof value === 'string') {
790     return fromString(value, encodingOrOffset)
791   }
792
793   return fromObject(value)
794 }
795
796 /**
797  * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
798  * if value is a number.
799  * Buffer.from(str[, encoding])
800  * Buffer.from(array)
801  * Buffer.from(buffer)
802  * Buffer.from(arrayBuffer[, byteOffset[, length]])
803  **/
804 Buffer.from = function (value, encodingOrOffset, length) {
805   return from(value, encodingOrOffset, length)
806 }
807
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
812
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')
818   }
819 }
820
821 function alloc (size, fill, encoding) {
822   assertSize(size)
823   if (size <= 0) {
824     return createBuffer(size)
825   }
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)
833   }
834   return createBuffer(size)
835 }
836
837 /**
838  * Creates a new filled Buffer instance.
839  * alloc(size[, fill[, encoding]])
840  **/
841 Buffer.alloc = function (size, fill, encoding) {
842   return alloc(size, fill, encoding)
843 }
844
845 function allocUnsafe (size) {
846   assertSize(size)
847   return createBuffer(size < 0 ? 0 : checked(size) | 0)
848 }
849
850 /**
851  * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
852  * */
853 Buffer.allocUnsafe = function (size) {
854   return allocUnsafe(size)
855 }
856 /**
857  * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
858  */
859 Buffer.allocUnsafeSlow = function (size) {
860   return allocUnsafe(size)
861 }
862
863 function fromString (string, encoding) {
864   if (typeof encoding !== 'string' || encoding === '') {
865     encoding = 'utf8'
866   }
867
868   if (!Buffer.isEncoding(encoding)) {
869     throw new TypeError('"encoding" must be a valid string encoding')
870   }
871
872   var length = byteLength(string, encoding) | 0
873   var buf = createBuffer(length)
874
875   var actual = buf.write(string, encoding)
876
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)
882   }
883
884   return buf
885 }
886
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
892   }
893   return buf
894 }
895
896 function fromArrayBuffer (array, byteOffset, length) {
897   if (byteOffset < 0 || array.byteLength < byteOffset) {
898     throw new RangeError('\'offset\' is out of bounds')
899   }
900
901   if (array.byteLength < byteOffset + (length || 0)) {
902     throw new RangeError('\'length\' is out of bounds')
903   }
904
905   var buf
906   if (byteOffset === undefined && length === undefined) {
907     buf = new Uint8Array(array)
908   } else if (length === undefined) {
909     buf = new Uint8Array(array, byteOffset)
910   } else {
911     buf = new Uint8Array(array, byteOffset, length)
912   }
913
914   // Return an augmented `Uint8Array` instance
915   buf.__proto__ = Buffer.prototype
916   return buf
917 }
918
919 function fromObject (obj) {
920   if (Buffer.isBuffer(obj)) {
921     var len = checked(obj.length) | 0
922     var buf = createBuffer(len)
923
924     if (buf.length === 0) {
925       return buf
926     }
927
928     obj.copy(buf, 0, 0, len)
929     return buf
930   }
931
932   if (obj) {
933     if (isArrayBufferView(obj) || 'length' in obj) {
934       if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
935         return createBuffer(0)
936       }
937       return fromArrayLike(obj)
938     }
939
940     if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
941       return fromArrayLike(obj.data)
942     }
943   }
944
945   throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
946 }
947
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')
954   }
955   return length | 0
956 }
957
958 function SlowBuffer (length) {
959   if (+length != length) { // eslint-disable-line eqeqeq
960     length = 0
961   }
962   return Buffer.alloc(+length)
963 }
964
965 Buffer.isBuffer = function isBuffer (b) {
966   return b != null && b._isBuffer === true
967 }
968
969 Buffer.compare = function compare (a, b) {
970   if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
971     throw new TypeError('Arguments must be Buffers')
972   }
973
974   if (a === b) return 0
975
976   var x = a.length
977   var y = b.length
978
979   for (var i = 0, len = Math.min(x, y); i < len; ++i) {
980     if (a[i] !== b[i]) {
981       x = a[i]
982       y = b[i]
983       break
984     }
985   }
986
987   if (x < y) return -1
988   if (y < x) return 1
989   return 0
990 }
991
992 Buffer.isEncoding = function isEncoding (encoding) {
993   switch (String(encoding).toLowerCase()) {
994     case 'hex':
995     case 'utf8':
996     case 'utf-8':
997     case 'ascii':
998     case 'latin1':
999     case 'binary':
1000     case 'base64':
1001     case 'ucs2':
1002     case 'ucs-2':
1003     case 'utf16le':
1004     case 'utf-16le':
1005       return true
1006     default:
1007       return false
1008   }
1009 }
1010
1011 Buffer.concat = function concat (list, length) {
1012   if (!Array.isArray(list)) {
1013     throw new TypeError('"list" argument must be an Array of Buffers')
1014   }
1015
1016   if (list.length === 0) {
1017     return Buffer.alloc(0)
1018   }
1019
1020   var i
1021   if (length === undefined) {
1022     length = 0
1023     for (i = 0; i < list.length; ++i) {
1024       length += list[i].length
1025     }
1026   }
1027
1028   var buffer = Buffer.allocUnsafe(length)
1029   var pos = 0
1030   for (i = 0; i < list.length; ++i) {
1031     var buf = list[i]
1032     if (!Buffer.isBuffer(buf)) {
1033       throw new TypeError('"list" argument must be an Array of Buffers')
1034     }
1035     buf.copy(buffer, pos)
1036     pos += buf.length
1037   }
1038   return buffer
1039 }
1040
1041 function byteLength (string, encoding) {
1042   if (Buffer.isBuffer(string)) {
1043     return string.length
1044   }
1045   if (isArrayBufferView(string) || isArrayBuffer(string)) {
1046     return string.byteLength
1047   }
1048   if (typeof string !== 'string') {
1049     string = '' + string
1050   }
1051
1052   var len = string.length
1053   if (len === 0) return 0
1054
1055   // Use a for loop to avoid recursion
1056   var loweredCase = false
1057   for (;;) {
1058     switch (encoding) {
1059       case 'ascii':
1060       case 'latin1':
1061       case 'binary':
1062         return len
1063       case 'utf8':
1064       case 'utf-8':
1065       case undefined:
1066         return utf8ToBytes(string).length
1067       case 'ucs2':
1068       case 'ucs-2':
1069       case 'utf16le':
1070       case 'utf-16le':
1071         return len * 2
1072       case 'hex':
1073         return len >>> 1
1074       case 'base64':
1075         return base64ToBytes(string).length
1076       default:
1077         if (loweredCase) return utf8ToBytes(string).length // assume utf8
1078         encoding = ('' + encoding).toLowerCase()
1079         loweredCase = true
1080     }
1081   }
1082 }
1083 Buffer.byteLength = byteLength
1084
1085 function slowToString (encoding, start, end) {
1086   var loweredCase = false
1087
1088   // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
1089   // property of a typed array.
1090
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) {
1096     start = 0
1097   }
1098   // Return early if start > this.length. Done here to prevent potential uint32
1099   // coercion fail below.
1100   if (start > this.length) {
1101     return ''
1102   }
1103
1104   if (end === undefined || end > this.length) {
1105     end = this.length
1106   }
1107
1108   if (end <= 0) {
1109     return ''
1110   }
1111
1112   // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
1113   end >>>= 0
1114   start >>>= 0
1115
1116   if (end <= start) {
1117     return ''
1118   }
1119
1120   if (!encoding) encoding = 'utf8'
1121
1122   while (true) {
1123     switch (encoding) {
1124       case 'hex':
1125         return hexSlice(this, start, end)
1126
1127       case 'utf8':
1128       case 'utf-8':
1129         return utf8Slice(this, start, end)
1130
1131       case 'ascii':
1132         return asciiSlice(this, start, end)
1133
1134       case 'latin1':
1135       case 'binary':
1136         return latin1Slice(this, start, end)
1137
1138       case 'base64':
1139         return base64Slice(this, start, end)
1140
1141       case 'ucs2':
1142       case 'ucs-2':
1143       case 'utf16le':
1144       case 'utf-16le':
1145         return utf16leSlice(this, start, end)
1146
1147       default:
1148         if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1149         encoding = (encoding + '').toLowerCase()
1150         loweredCase = true
1151     }
1152   }
1153 }
1154
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
1162
1163 function swap (b, n, m) {
1164   var i = b[n]
1165   b[n] = b[m]
1166   b[m] = i
1167 }
1168
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')
1173   }
1174   for (var i = 0; i < len; i += 2) {
1175     swap(this, i, i + 1)
1176   }
1177   return this
1178 }
1179
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')
1184   }
1185   for (var i = 0; i < len; i += 4) {
1186     swap(this, i, i + 3)
1187     swap(this, i + 1, i + 2)
1188   }
1189   return this
1190 }
1191
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')
1196   }
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)
1202   }
1203   return this
1204 }
1205
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)
1211 }
1212
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
1217 }
1218
1219 Buffer.prototype.inspect = function inspect () {
1220   var str = ''
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 += ' ... '
1225   }
1226   return '<Buffer ' + str + '>'
1227 }
1228
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')
1232   }
1233
1234   if (start === undefined) {
1235     start = 0
1236   }
1237   if (end === undefined) {
1238     end = target ? target.length : 0
1239   }
1240   if (thisStart === undefined) {
1241     thisStart = 0
1242   }
1243   if (thisEnd === undefined) {
1244     thisEnd = this.length
1245   }
1246
1247   if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
1248     throw new RangeError('out of range index')
1249   }
1250
1251   if (thisStart >= thisEnd && start >= end) {
1252     return 0
1253   }
1254   if (thisStart >= thisEnd) {
1255     return -1
1256   }
1257   if (start >= end) {
1258     return 1
1259   }
1260
1261   start >>>= 0
1262   end >>>= 0
1263   thisStart >>>= 0
1264   thisEnd >>>= 0
1265
1266   if (this === target) return 0
1267
1268   var x = thisEnd - thisStart
1269   var y = end - start
1270   var len = Math.min(x, y)
1271
1272   var thisCopy = this.slice(thisStart, thisEnd)
1273   var targetCopy = target.slice(start, end)
1274
1275   for (var i = 0; i < len; ++i) {
1276     if (thisCopy[i] !== targetCopy[i]) {
1277       x = thisCopy[i]
1278       y = targetCopy[i]
1279       break
1280     }
1281   }
1282
1283   if (x < y) return -1
1284   if (y < x) return 1
1285   return 0
1286 }
1287
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`.
1290 //
1291 // Arguments:
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
1300
1301   // Normalize byteOffset
1302   if (typeof byteOffset === 'string') {
1303     encoding = byteOffset
1304     byteOffset = 0
1305   } else if (byteOffset > 0x7fffffff) {
1306     byteOffset = 0x7fffffff
1307   } else if (byteOffset < -0x80000000) {
1308     byteOffset = -0x80000000
1309   }
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)
1314   }
1315
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) {
1319     if (dir) return -1
1320     else byteOffset = buffer.length - 1
1321   } else if (byteOffset < 0) {
1322     if (dir) byteOffset = 0
1323     else return -1
1324   }
1325
1326   // Normalize val
1327   if (typeof val === 'string') {
1328     val = Buffer.from(val, encoding)
1329   }
1330
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) {
1335       return -1
1336     }
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') {
1341       if (dir) {
1342         return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
1343       } else {
1344         return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
1345       }
1346     }
1347     return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
1348   }
1349
1350   throw new TypeError('val must be string, number or Buffer')
1351 }
1352
1353 function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
1354   var indexSize = 1
1355   var arrLength = arr.length
1356   var valLength = val.length
1357
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) {
1363         return -1
1364       }
1365       indexSize = 2
1366       arrLength /= 2
1367       valLength /= 2
1368       byteOffset /= 2
1369     }
1370   }
1371
1372   function read (buf, i) {
1373     if (indexSize === 1) {
1374       return buf[i]
1375     } else {
1376       return buf.readUInt16BE(i * indexSize)
1377     }
1378   }
1379
1380   var i
1381   if (dir) {
1382     var foundIndex = -1
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
1387       } else {
1388         if (foundIndex !== -1) i -= i - foundIndex
1389         foundIndex = -1
1390       }
1391     }
1392   } else {
1393     if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
1394     for (i = byteOffset; i >= 0; i--) {
1395       var found = true
1396       for (var j = 0; j < valLength; j++) {
1397         if (read(arr, i + j) !== read(val, j)) {
1398           found = false
1399           break
1400         }
1401       }
1402       if (found) return i
1403     }
1404   }
1405
1406   return -1
1407 }
1408
1409 Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
1410   return this.indexOf(val, byteOffset, encoding) !== -1
1411 }
1412
1413 Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
1414   return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
1415 }
1416
1417 Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
1418   return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
1419 }
1420
1421 function hexWrite (buf, string, offset, length) {
1422   offset = Number(offset) || 0
1423   var remaining = buf.length - offset
1424   if (!length) {
1425     length = remaining
1426   } else {
1427     length = Number(length)
1428     if (length > remaining) {
1429       length = remaining
1430     }
1431   }
1432
1433   // must be an even number of digits
1434   var strLen = string.length
1435   if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
1436
1437   if (length > strLen / 2) {
1438     length = strLen / 2
1439   }
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
1444   }
1445   return i
1446 }
1447
1448 function utf8Write (buf, string, offset, length) {
1449   return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
1450 }
1451
1452 function asciiWrite (buf, string, offset, length) {
1453   return blitBuffer(asciiToBytes(string), buf, offset, length)
1454 }
1455
1456 function latin1Write (buf, string, offset, length) {
1457   return asciiWrite(buf, string, offset, length)
1458 }
1459
1460 function base64Write (buf, string, offset, length) {
1461   return blitBuffer(base64ToBytes(string), buf, offset, length)
1462 }
1463
1464 function ucs2Write (buf, string, offset, length) {
1465   return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
1466 }
1467
1468 Buffer.prototype.write = function write (string, offset, length, encoding) {
1469   // Buffer#write(string)
1470   if (offset === undefined) {
1471     encoding = 'utf8'
1472     length = this.length
1473     offset = 0
1474   // Buffer#write(string, encoding)
1475   } else if (length === undefined && typeof offset === 'string') {
1476     encoding = offset
1477     length = this.length
1478     offset = 0
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'
1485     } else {
1486       encoding = length
1487       length = undefined
1488     }
1489   } else {
1490     throw new Error(
1491       'Buffer.write(string, encoding, offset[, length]) is no longer supported'
1492     )
1493   }
1494
1495   var remaining = this.length - offset
1496   if (length === undefined || length > remaining) length = remaining
1497
1498   if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
1499     throw new RangeError('Attempt to write outside buffer bounds')
1500   }
1501
1502   if (!encoding) encoding = 'utf8'
1503
1504   var loweredCase = false
1505   for (;;) {
1506     switch (encoding) {
1507       case 'hex':
1508         return hexWrite(this, string, offset, length)
1509
1510       case 'utf8':
1511       case 'utf-8':
1512         return utf8Write(this, string, offset, length)
1513
1514       case 'ascii':
1515         return asciiWrite(this, string, offset, length)
1516
1517       case 'latin1':
1518       case 'binary':
1519         return latin1Write(this, string, offset, length)
1520
1521       case 'base64':
1522         // Warning: maxLength not taken into account in base64Write
1523         return base64Write(this, string, offset, length)
1524
1525       case 'ucs2':
1526       case 'ucs-2':
1527       case 'utf16le':
1528       case 'utf-16le':
1529         return ucs2Write(this, string, offset, length)
1530
1531       default:
1532         if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1533         encoding = ('' + encoding).toLowerCase()
1534         loweredCase = true
1535     }
1536   }
1537 }
1538
1539 Buffer.prototype.toJSON = function toJSON () {
1540   return {
1541     type: 'Buffer',
1542     data: Array.prototype.slice.call(this._arr || this, 0)
1543   }
1544 }
1545
1546 function base64Slice (buf, start, end) {
1547   if (start === 0 && end === buf.length) {
1548     return base64.fromByteArray(buf)
1549   } else {
1550     return base64.fromByteArray(buf.slice(start, end))
1551   }
1552 }
1553
1554 function utf8Slice (buf, start, end) {
1555   end = Math.min(buf.length, end)
1556   var res = []
1557
1558   var i = start
1559   while (i < end) {
1560     var firstByte = buf[i]
1561     var codePoint = null
1562     var bytesPerSequence = (firstByte > 0xEF) ? 4
1563       : (firstByte > 0xDF) ? 3
1564       : (firstByte > 0xBF) ? 2
1565       : 1
1566
1567     if (i + bytesPerSequence <= end) {
1568       var secondByte, thirdByte, fourthByte, tempCodePoint
1569
1570       switch (bytesPerSequence) {
1571         case 1:
1572           if (firstByte < 0x80) {
1573             codePoint = firstByte
1574           }
1575           break
1576         case 2:
1577           secondByte = buf[i + 1]
1578           if ((secondByte & 0xC0) === 0x80) {
1579             tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
1580             if (tempCodePoint > 0x7F) {
1581               codePoint = tempCodePoint
1582             }
1583           }
1584           break
1585         case 3:
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
1592             }
1593           }
1594           break
1595         case 4:
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
1603             }
1604           }
1605       }
1606     }
1607
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
1611       codePoint = 0xFFFD
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
1618     }
1619
1620     res.push(codePoint)
1621     i += bytesPerSequence
1622   }
1623
1624   return decodeCodePointsArray(res)
1625 }
1626
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
1631
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()
1636   }
1637
1638   // Decode in chunks to avoid "call stack size exceeded".
1639   var res = ''
1640   var i = 0
1641   while (i < len) {
1642     res += String.fromCharCode.apply(
1643       String,
1644       codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
1645     )
1646   }
1647   return res
1648 }
1649
1650 function asciiSlice (buf, start, end) {
1651   var ret = ''
1652   end = Math.min(buf.length, end)
1653
1654   for (var i = start; i < end; ++i) {
1655     ret += String.fromCharCode(buf[i] & 0x7F)
1656   }
1657   return ret
1658 }
1659
1660 function latin1Slice (buf, start, end) {
1661   var ret = ''
1662   end = Math.min(buf.length, end)
1663
1664   for (var i = start; i < end; ++i) {
1665     ret += String.fromCharCode(buf[i])
1666   }
1667   return ret
1668 }
1669
1670 function hexSlice (buf, start, end) {
1671   var len = buf.length
1672
1673   if (!start || start < 0) start = 0
1674   if (!end || end < 0 || end > len) end = len
1675
1676   var out = ''
1677   for (var i = start; i < end; ++i) {
1678     out += toHex(buf[i])
1679   }
1680   return out
1681 }
1682
1683 function utf16leSlice (buf, start, end) {
1684   var bytes = buf.slice(start, end)
1685   var res = ''
1686   for (var i = 0; i < bytes.length; i += 2) {
1687     res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
1688   }
1689   return res
1690 }
1691
1692 Buffer.prototype.slice = function slice (start, end) {
1693   var len = this.length
1694   start = ~~start
1695   end = end === undefined ? len : ~~end
1696
1697   if (start < 0) {
1698     start += len
1699     if (start < 0) start = 0
1700   } else if (start > len) {
1701     start = len
1702   }
1703
1704   if (end < 0) {
1705     end += len
1706     if (end < 0) end = 0
1707   } else if (end > len) {
1708     end = len
1709   }
1710
1711   if (end < start) end = start
1712
1713   var newBuf = this.subarray(start, end)
1714   // Return an augmented `Uint8Array` instance
1715   newBuf.__proto__ = Buffer.prototype
1716   return newBuf
1717 }
1718
1719 /*
1720  * Need to make sure that buffer isn't trying to write out of bounds.
1721  */
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')
1725 }
1726
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)
1731
1732   var val = this[offset]
1733   var mul = 1
1734   var i = 0
1735   while (++i < byteLength && (mul *= 0x100)) {
1736     val += this[offset + i] * mul
1737   }
1738
1739   return val
1740 }
1741
1742 Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
1743   offset = offset >>> 0
1744   byteLength = byteLength >>> 0
1745   if (!noAssert) {
1746     checkOffset(offset, byteLength, this.length)
1747   }
1748
1749   var val = this[offset + --byteLength]
1750   var mul = 1
1751   while (byteLength > 0 && (mul *= 0x100)) {
1752     val += this[offset + --byteLength] * mul
1753   }
1754
1755   return val
1756 }
1757
1758 Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
1759   offset = offset >>> 0
1760   if (!noAssert) checkOffset(offset, 1, this.length)
1761   return this[offset]
1762 }
1763
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)
1768 }
1769
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]
1774 }
1775
1776 Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
1777   offset = offset >>> 0
1778   if (!noAssert) checkOffset(offset, 4, this.length)
1779
1780   return ((this[offset]) |
1781       (this[offset + 1] << 8) |
1782       (this[offset + 2] << 16)) +
1783       (this[offset + 3] * 0x1000000)
1784 }
1785
1786 Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
1787   offset = offset >>> 0
1788   if (!noAssert) checkOffset(offset, 4, this.length)
1789
1790   return (this[offset] * 0x1000000) +
1791     ((this[offset + 1] << 16) |
1792     (this[offset + 2] << 8) |
1793     this[offset + 3])
1794 }
1795
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)
1800
1801   var val = this[offset]
1802   var mul = 1
1803   var i = 0
1804   while (++i < byteLength && (mul *= 0x100)) {
1805     val += this[offset + i] * mul
1806   }
1807   mul *= 0x80
1808
1809   if (val >= mul) val -= Math.pow(2, 8 * byteLength)
1810
1811   return val
1812 }
1813
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)
1818
1819   var i = byteLength
1820   var mul = 1
1821   var val = this[offset + --i]
1822   while (i > 0 && (mul *= 0x100)) {
1823     val += this[offset + --i] * mul
1824   }
1825   mul *= 0x80
1826
1827   if (val >= mul) val -= Math.pow(2, 8 * byteLength)
1828
1829   return val
1830 }
1831
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)
1837 }
1838
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
1844 }
1845
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
1851 }
1852
1853 Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
1854   offset = offset >>> 0
1855   if (!noAssert) checkOffset(offset, 4, this.length)
1856
1857   return (this[offset]) |
1858     (this[offset + 1] << 8) |
1859     (this[offset + 2] << 16) |
1860     (this[offset + 3] << 24)
1861 }
1862
1863 Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
1864   offset = offset >>> 0
1865   if (!noAssert) checkOffset(offset, 4, this.length)
1866
1867   return (this[offset] << 24) |
1868     (this[offset + 1] << 16) |
1869     (this[offset + 2] << 8) |
1870     (this[offset + 3])
1871 }
1872
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)
1877 }
1878
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)
1883 }
1884
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)
1889 }
1890
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)
1895 }
1896
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')
1901 }
1902
1903 Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
1904   value = +value
1905   offset = offset >>> 0
1906   byteLength = byteLength >>> 0
1907   if (!noAssert) {
1908     var maxBytes = Math.pow(2, 8 * byteLength) - 1
1909     checkInt(this, value, offset, byteLength, maxBytes, 0)
1910   }
1911
1912   var mul = 1
1913   var i = 0
1914   this[offset] = value & 0xFF
1915   while (++i < byteLength && (mul *= 0x100)) {
1916     this[offset + i] = (value / mul) & 0xFF
1917   }
1918
1919   return offset + byteLength
1920 }
1921
1922 Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
1923   value = +value
1924   offset = offset >>> 0
1925   byteLength = byteLength >>> 0
1926   if (!noAssert) {
1927     var maxBytes = Math.pow(2, 8 * byteLength) - 1
1928     checkInt(this, value, offset, byteLength, maxBytes, 0)
1929   }
1930
1931   var i = byteLength - 1
1932   var mul = 1
1933   this[offset + i] = value & 0xFF
1934   while (--i >= 0 && (mul *= 0x100)) {
1935     this[offset + i] = (value / mul) & 0xFF
1936   }
1937
1938   return offset + byteLength
1939 }
1940
1941 Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
1942   value = +value
1943   offset = offset >>> 0
1944   if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
1945   this[offset] = (value & 0xff)
1946   return offset + 1
1947 }
1948
1949 Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
1950   value = +value
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)
1955   return offset + 2
1956 }
1957
1958 Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
1959   value = +value
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)
1964   return offset + 2
1965 }
1966
1967 Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
1968   value = +value
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)
1975   return offset + 4
1976 }
1977
1978 Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
1979   value = +value
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)
1986   return offset + 4
1987 }
1988
1989 Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
1990   value = +value
1991   offset = offset >>> 0
1992   if (!noAssert) {
1993     var limit = Math.pow(2, (8 * byteLength) - 1)
1994
1995     checkInt(this, value, offset, byteLength, limit - 1, -limit)
1996   }
1997
1998   var i = 0
1999   var mul = 1
2000   var sub = 0
2001   this[offset] = value & 0xFF
2002   while (++i < byteLength && (mul *= 0x100)) {
2003     if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
2004       sub = 1
2005     }
2006     this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
2007   }
2008
2009   return offset + byteLength
2010 }
2011
2012 Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
2013   value = +value
2014   offset = offset >>> 0
2015   if (!noAssert) {
2016     var limit = Math.pow(2, (8 * byteLength) - 1)
2017
2018     checkInt(this, value, offset, byteLength, limit - 1, -limit)
2019   }
2020
2021   var i = byteLength - 1
2022   var mul = 1
2023   var sub = 0
2024   this[offset + i] = value & 0xFF
2025   while (--i >= 0 && (mul *= 0x100)) {
2026     if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
2027       sub = 1
2028     }
2029     this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
2030   }
2031
2032   return offset + byteLength
2033 }
2034
2035 Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
2036   value = +value
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)
2041   return offset + 1
2042 }
2043
2044 Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
2045   value = +value
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)
2050   return offset + 2
2051 }
2052
2053 Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
2054   value = +value
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)
2059   return offset + 2
2060 }
2061
2062 Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
2063   value = +value
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)
2070   return offset + 4
2071 }
2072
2073 Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
2074   value = +value
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)
2082   return offset + 4
2083 }
2084
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')
2088 }
2089
2090 function writeFloat (buf, value, offset, littleEndian, noAssert) {
2091   value = +value
2092   offset = offset >>> 0
2093   if (!noAssert) {
2094     checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
2095   }
2096   ieee754.write(buf, value, offset, littleEndian, 23, 4)
2097   return offset + 4
2098 }
2099
2100 Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
2101   return writeFloat(this, value, offset, true, noAssert)
2102 }
2103
2104 Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
2105   return writeFloat(this, value, offset, false, noAssert)
2106 }
2107
2108 function writeDouble (buf, value, offset, littleEndian, noAssert) {
2109   value = +value
2110   offset = offset >>> 0
2111   if (!noAssert) {
2112     checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
2113   }
2114   ieee754.write(buf, value, offset, littleEndian, 52, 8)
2115   return offset + 8
2116 }
2117
2118 Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
2119   return writeDouble(this, value, offset, true, noAssert)
2120 }
2121
2122 Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
2123   return writeDouble(this, value, offset, false, noAssert)
2124 }
2125
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
2133
2134   // Copy 0 bytes; we're done
2135   if (end === start) return 0
2136   if (target.length === 0 || this.length === 0) return 0
2137
2138   // Fatal error conditions
2139   if (targetStart < 0) {
2140     throw new RangeError('targetStart out of bounds')
2141   }
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')
2144
2145   // Are we oob?
2146   if (end > this.length) end = this.length
2147   if (target.length - targetStart < end - start) {
2148     end = target.length - targetStart + start
2149   }
2150
2151   var len = end - start
2152   var i
2153
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]
2158     }
2159   } else if (len < 1000) {
2160     // ascending copy from start
2161     for (i = 0; i < len; ++i) {
2162       target[i + targetStart] = this[i + start]
2163     }
2164   } else {
2165     Uint8Array.prototype.set.call(
2166       target,
2167       this.subarray(start, start + len),
2168       targetStart
2169     )
2170   }
2171
2172   return len
2173 }
2174
2175 // Usage:
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') {
2183       encoding = start
2184       start = 0
2185       end = this.length
2186     } else if (typeof end === 'string') {
2187       encoding = end
2188       end = this.length
2189     }
2190     if (val.length === 1) {
2191       var code = val.charCodeAt(0)
2192       if (code < 256) {
2193         val = code
2194       }
2195     }
2196     if (encoding !== undefined && typeof encoding !== 'string') {
2197       throw new TypeError('encoding must be a string')
2198     }
2199     if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
2200       throw new TypeError('Unknown encoding: ' + encoding)
2201     }
2202   } else if (typeof val === 'number') {
2203     val = val & 255
2204   }
2205
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')
2209   }
2210
2211   if (end <= start) {
2212     return this
2213   }
2214
2215   start = start >>> 0
2216   end = end === undefined ? this.length : end >>> 0
2217
2218   if (!val) val = 0
2219
2220   var i
2221   if (typeof val === 'number') {
2222     for (i = start; i < end; ++i) {
2223       this[i] = val
2224     }
2225   } else {
2226     var bytes = Buffer.isBuffer(val)
2227       ? 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]
2232     }
2233   }
2234
2235   return this
2236 }
2237
2238 // HELPER FUNCTIONS
2239 // ================
2240
2241 var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
2242
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) {
2250     str = str + '='
2251   }
2252   return str
2253 }
2254
2255 function toHex (n) {
2256   if (n < 16) return '0' + n.toString(16)
2257   return n.toString(16)
2258 }
2259
2260 function utf8ToBytes (string, units) {
2261   units = units || Infinity
2262   var codePoint
2263   var length = string.length
2264   var leadSurrogate = null
2265   var bytes = []
2266
2267   for (var i = 0; i < length; ++i) {
2268     codePoint = string.charCodeAt(i)
2269
2270     // is surrogate component
2271     if (codePoint > 0xD7FF && codePoint < 0xE000) {
2272       // last char was a lead
2273       if (!leadSurrogate) {
2274         // no lead yet
2275         if (codePoint > 0xDBFF) {
2276           // unexpected trail
2277           if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2278           continue
2279         } else if (i + 1 === length) {
2280           // unpaired lead
2281           if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2282           continue
2283         }
2284
2285         // valid lead
2286         leadSurrogate = codePoint
2287
2288         continue
2289       }
2290
2291       // 2 leads in a row
2292       if (codePoint < 0xDC00) {
2293         if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2294         leadSurrogate = codePoint
2295         continue
2296       }
2297
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)
2303     }
2304
2305     leadSurrogate = null
2306
2307     // encode utf8
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
2313       bytes.push(
2314         codePoint >> 0x6 | 0xC0,
2315         codePoint & 0x3F | 0x80
2316       )
2317     } else if (codePoint < 0x10000) {
2318       if ((units -= 3) < 0) break
2319       bytes.push(
2320         codePoint >> 0xC | 0xE0,
2321         codePoint >> 0x6 & 0x3F | 0x80,
2322         codePoint & 0x3F | 0x80
2323       )
2324     } else if (codePoint < 0x110000) {
2325       if ((units -= 4) < 0) break
2326       bytes.push(
2327         codePoint >> 0x12 | 0xF0,
2328         codePoint >> 0xC & 0x3F | 0x80,
2329         codePoint >> 0x6 & 0x3F | 0x80,
2330         codePoint & 0x3F | 0x80
2331       )
2332     } else {
2333       throw new Error('Invalid code point')
2334     }
2335   }
2336
2337   return bytes
2338 }
2339
2340 function asciiToBytes (str) {
2341   var byteArray = []
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)
2345   }
2346   return byteArray
2347 }
2348
2349 function utf16leToBytes (str, units) {
2350   var c, hi, lo
2351   var byteArray = []
2352   for (var i = 0; i < str.length; ++i) {
2353     if ((units -= 2) < 0) break
2354
2355     c = str.charCodeAt(i)
2356     hi = c >> 8
2357     lo = c % 256
2358     byteArray.push(lo)
2359     byteArray.push(hi)
2360   }
2361
2362   return byteArray
2363 }
2364
2365 function base64ToBytes (str) {
2366   return base64.toByteArray(base64clean(str))
2367 }
2368
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]
2373   }
2374   return i
2375 }
2376
2377 // ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check
2378 // but they should be treated as valid. See: https://github.com/feross/buffer/issues/166
2379 function isArrayBuffer (obj) {
2380   return obj instanceof ArrayBuffer ||
2381     (obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' &&
2382       typeof obj.byteLength === 'number')
2383 }
2384
2385 // Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView`
2386 function isArrayBufferView (obj) {
2387   return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj)
2388 }
2389
2390 function numberIsNaN (obj) {
2391   return obj !== obj // eslint-disable-line no-self-compare
2392 }
2393
2394 },{"base64-js":3,"ieee754":17}],8:[function(require,module,exports){
2395 'use strict';
2396
2397 module.exports = earcut;
2398 module.exports.default = earcut;
2399
2400 function earcut(data, holeIndices, dim) {
2401
2402     dim = dim || 2;
2403
2404     var hasHoles = holeIndices && holeIndices.length,
2405         outerLen = hasHoles ? holeIndices[0] * dim : data.length,
2406         outerNode = linkedList(data, 0, outerLen, dim, true),
2407         triangles = [];
2408
2409     if (!outerNode) return triangles;
2410
2411     var minX, minY, maxX, maxY, x, y, invSize;
2412
2413     if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
2414
2415     // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
2416     if (data.length > 80 * dim) {
2417         minX = maxX = data[0];
2418         minY = maxY = data[1];
2419
2420         for (var i = dim; i < outerLen; i += dim) {
2421             x = data[i];
2422             y = data[i + 1];
2423             if (x < minX) minX = x;
2424             if (y < minY) minY = y;
2425             if (x > maxX) maxX = x;
2426             if (y > maxY) maxY = y;
2427         }
2428
2429         // minX, minY and invSize are later used to transform coords into integers for z-order calculation
2430         invSize = Math.max(maxX - minX, maxY - minY);
2431         invSize = invSize !== 0 ? 1 / invSize : 0;
2432     }
2433
2434     earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
2435
2436     return triangles;
2437 }
2438
2439 // create a circular doubly linked list from polygon points in the specified winding order
2440 function linkedList(data, start, end, dim, clockwise) {
2441     var i, last;
2442
2443     if (clockwise === (signedArea(data, start, end, dim) > 0)) {
2444         for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
2445     } else {
2446         for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
2447     }
2448
2449     if (last && equals(last, last.next)) {
2450         removeNode(last);
2451         last = last.next;
2452     }
2453
2454     return last;
2455 }
2456
2457 // eliminate colinear or duplicate points
2458 function filterPoints(start, end) {
2459     if (!start) return start;
2460     if (!end) end = start;
2461
2462     var p = start,
2463         again;
2464     do {
2465         again = false;
2466
2467         if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
2468             removeNode(p);
2469             p = end = p.prev;
2470             if (p === p.next) break;
2471             again = true;
2472
2473         } else {
2474             p = p.next;
2475         }
2476     } while (again || p !== end);
2477
2478     return end;
2479 }
2480
2481 // main ear slicing loop which triangulates a polygon (given as a linked list)
2482 function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
2483     if (!ear) return;
2484
2485     // interlink polygon nodes in z-order
2486     if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
2487
2488     var stop = ear,
2489         prev, next;
2490
2491     // iterate through ears, slicing them one by one
2492     while (ear.prev !== ear.next) {
2493         prev = ear.prev;
2494         next = ear.next;
2495
2496         if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
2497             // cut off the triangle
2498             triangles.push(prev.i / dim);
2499             triangles.push(ear.i / dim);
2500             triangles.push(next.i / dim);
2501
2502             removeNode(ear);
2503
2504             // skipping the next vertice leads to less sliver triangles
2505             ear = next.next;
2506             stop = next.next;
2507
2508             continue;
2509         }
2510
2511         ear = next;
2512
2513         // if we looped through the whole remaining polygon and can't find any more ears
2514         if (ear === stop) {
2515             // try filtering points and slicing again
2516             if (!pass) {
2517                 earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
2518
2519             // if this didn't work, try curing all small self-intersections locally
2520             } else if (pass === 1) {
2521                 ear = cureLocalIntersections(ear, triangles, dim);
2522                 earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
2523
2524             // as a last resort, try splitting the remaining polygon into two
2525             } else if (pass === 2) {
2526                 splitEarcut(ear, triangles, dim, minX, minY, invSize);
2527             }
2528
2529             break;
2530         }
2531     }
2532 }
2533
2534 // check whether a polygon node forms a valid ear with adjacent nodes
2535 function isEar(ear) {
2536     var a = ear.prev,
2537         b = ear,
2538         c = ear.next;
2539
2540     if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
2541
2542     // now make sure we don't have other points inside the potential ear
2543     var p = ear.next.next;
2544
2545     while (p !== ear.prev) {
2546         if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
2547             area(p.prev, p, p.next) >= 0) return false;
2548         p = p.next;
2549     }
2550
2551     return true;
2552 }
2553
2554 function isEarHashed(ear, minX, minY, invSize) {
2555     var a = ear.prev,
2556         b = ear,
2557         c = ear.next;
2558
2559     if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
2560
2561     // triangle bbox; min & max are calculated like this for speed
2562     var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x),
2563         minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y),
2564         maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x),
2565         maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
2566
2567     // z-order range for the current triangle bbox;
2568     var minZ = zOrder(minTX, minTY, minX, minY, invSize),
2569         maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
2570
2571     // first look for points inside the triangle in increasing z-order
2572     var p = ear.nextZ;
2573
2574     while (p && p.z <= maxZ) {
2575         if (p !== ear.prev && p !== ear.next &&
2576             pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
2577             area(p.prev, p, p.next) >= 0) return false;
2578         p = p.nextZ;
2579     }
2580
2581     // then look for points in decreasing z-order
2582     p = ear.prevZ;
2583
2584     while (p && p.z >= minZ) {
2585         if (p !== ear.prev && p !== ear.next &&
2586             pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
2587             area(p.prev, p, p.next) >= 0) return false;
2588         p = p.prevZ;
2589     }
2590
2591     return true;
2592 }
2593
2594 // go through all polygon nodes and cure small local self-intersections
2595 function cureLocalIntersections(start, triangles, dim) {
2596     var p = start;
2597     do {
2598         var a = p.prev,
2599             b = p.next.next;
2600
2601         if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
2602
2603             triangles.push(a.i / dim);
2604             triangles.push(p.i / dim);
2605             triangles.push(b.i / dim);
2606
2607             // remove two nodes involved
2608             removeNode(p);
2609             removeNode(p.next);
2610
2611             p = start = b;
2612         }
2613         p = p.next;
2614     } while (p !== start);
2615
2616     return p;
2617 }
2618
2619 // try splitting polygon into two and triangulate them independently
2620 function splitEarcut(start, triangles, dim, minX, minY, invSize) {
2621     // look for a valid diagonal that divides the polygon into two
2622     var a = start;
2623     do {
2624         var b = a.next.next;
2625         while (b !== a.prev) {
2626             if (a.i !== b.i && isValidDiagonal(a, b)) {
2627                 // split the polygon in two by the diagonal
2628                 var c = splitPolygon(a, b);
2629
2630                 // filter colinear points around the cuts
2631                 a = filterPoints(a, a.next);
2632                 c = filterPoints(c, c.next);
2633
2634                 // run earcut on each half
2635                 earcutLinked(a, triangles, dim, minX, minY, invSize);
2636                 earcutLinked(c, triangles, dim, minX, minY, invSize);
2637                 return;
2638             }
2639             b = b.next;
2640         }
2641         a = a.next;
2642     } while (a !== start);
2643 }
2644
2645 // link every hole into the outer loop, producing a single-ring polygon without holes
2646 function eliminateHoles(data, holeIndices, outerNode, dim) {
2647     var queue = [],
2648         i, len, start, end, list;
2649
2650     for (i = 0, len = holeIndices.length; i < len; i++) {
2651         start = holeIndices[i] * dim;
2652         end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
2653         list = linkedList(data, start, end, dim, false);
2654         if (list === list.next) list.steiner = true;
2655         queue.push(getLeftmost(list));
2656     }
2657
2658     queue.sort(compareX);
2659
2660     // process holes from left to right
2661     for (i = 0; i < queue.length; i++) {
2662         eliminateHole(queue[i], outerNode);
2663         outerNode = filterPoints(outerNode, outerNode.next);
2664     }
2665
2666     return outerNode;
2667 }
2668
2669 function compareX(a, b) {
2670     return a.x - b.x;
2671 }
2672
2673 // find a bridge between vertices that connects hole with an outer ring and and link it
2674 function eliminateHole(hole, outerNode) {
2675     outerNode = findHoleBridge(hole, outerNode);
2676     if (outerNode) {
2677         var b = splitPolygon(outerNode, hole);
2678         filterPoints(b, b.next);
2679     }
2680 }
2681
2682 // David Eberly's algorithm for finding a bridge between hole and outer polygon
2683 function findHoleBridge(hole, outerNode) {
2684     var p = outerNode,
2685         hx = hole.x,
2686         hy = hole.y,
2687         qx = -Infinity,
2688         m;
2689
2690     // find a segment intersected by a ray from the hole's leftmost point to the left;
2691     // segment's endpoint with lesser x will be potential connection point
2692     do {
2693         if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
2694             var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
2695             if (x <= hx && x > qx) {
2696                 qx = x;
2697                 if (x === hx) {
2698                     if (hy === p.y) return p;
2699                     if (hy === p.next.y) return p.next;
2700                 }
2701                 m = p.x < p.next.x ? p : p.next;
2702             }
2703         }
2704         p = p.next;
2705     } while (p !== outerNode);
2706
2707     if (!m) return null;
2708
2709     if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint
2710
2711     // look for points inside the triangle of hole point, segment intersection and endpoint;
2712     // if there are no points found, we have a valid connection;
2713     // otherwise choose the point of the minimum angle with the ray as connection point
2714
2715     var stop = m,
2716         mx = m.x,
2717         my = m.y,
2718         tanMin = Infinity,
2719         tan;
2720
2721     p = m.next;
2722
2723     while (p !== stop) {
2724         if (hx >= p.x && p.x >= mx && hx !== p.x &&
2725                 pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
2726
2727             tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
2728
2729             if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
2730                 m = p;
2731                 tanMin = tan;
2732             }
2733         }
2734
2735         p = p.next;
2736     }
2737
2738     return m;
2739 }
2740
2741 // interlink polygon nodes in z-order
2742 function indexCurve(start, minX, minY, invSize) {
2743     var p = start;
2744     do {
2745         if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
2746         p.prevZ = p.prev;
2747         p.nextZ = p.next;
2748         p = p.next;
2749     } while (p !== start);
2750
2751     p.prevZ.nextZ = null;
2752     p.prevZ = null;
2753
2754     sortLinked(p);
2755 }
2756
2757 // Simon Tatham's linked list merge sort algorithm
2758 // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
2759 function sortLinked(list) {
2760     var i, p, q, e, tail, numMerges, pSize, qSize,
2761         inSize = 1;
2762
2763     do {
2764         p = list;
2765         list = null;
2766         tail = null;
2767         numMerges = 0;
2768
2769         while (p) {
2770             numMerges++;
2771             q = p;
2772             pSize = 0;
2773             for (i = 0; i < inSize; i++) {
2774                 pSize++;
2775                 q = q.nextZ;
2776                 if (!q) break;
2777             }
2778             qSize = inSize;
2779
2780             while (pSize > 0 || (qSize > 0 && q)) {
2781
2782                 if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
2783                     e = p;
2784                     p = p.nextZ;
2785                     pSize--;
2786                 } else {
2787                     e = q;
2788                     q = q.nextZ;
2789                     qSize--;
2790                 }
2791
2792                 if (tail) tail.nextZ = e;
2793                 else list = e;
2794
2795                 e.prevZ = tail;
2796                 tail = e;
2797             }
2798
2799             p = q;
2800         }
2801
2802         tail.nextZ = null;
2803         inSize *= 2;
2804
2805     } while (numMerges > 1);
2806
2807     return list;
2808 }
2809
2810 // z-order of a point given coords and inverse of the longer side of data bbox
2811 function zOrder(x, y, minX, minY, invSize) {
2812     // coords are transformed into non-negative 15-bit integer range
2813     x = 32767 * (x - minX) * invSize;
2814     y = 32767 * (y - minY) * invSize;
2815
2816     x = (x | (x << 8)) & 0x00FF00FF;
2817     x = (x | (x << 4)) & 0x0F0F0F0F;
2818     x = (x | (x << 2)) & 0x33333333;
2819     x = (x | (x << 1)) & 0x55555555;
2820
2821     y = (y | (y << 8)) & 0x00FF00FF;
2822     y = (y | (y << 4)) & 0x0F0F0F0F;
2823     y = (y | (y << 2)) & 0x33333333;
2824     y = (y | (y << 1)) & 0x55555555;
2825
2826     return x | (y << 1);
2827 }
2828
2829 // find the leftmost node of a polygon ring
2830 function getLeftmost(start) {
2831     var p = start,
2832         leftmost = start;
2833     do {
2834         if (p.x < leftmost.x) leftmost = p;
2835         p = p.next;
2836     } while (p !== start);
2837
2838     return leftmost;
2839 }
2840
2841 // check if a point lies within a convex triangle
2842 function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
2843     return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
2844            (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
2845            (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
2846 }
2847
2848 // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
2849 function isValidDiagonal(a, b) {
2850     return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) &&
2851            locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
2852 }
2853
2854 // signed area of a triangle
2855 function area(p, q, r) {
2856     return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
2857 }
2858
2859 // check if two points are equal
2860 function equals(p1, p2) {
2861     return p1.x === p2.x && p1.y === p2.y;
2862 }
2863
2864 // check if two segments intersect
2865 function intersects(p1, q1, p2, q2) {
2866     if ((equals(p1, q1) && equals(p2, q2)) ||
2867         (equals(p1, q2) && equals(p2, q1))) return true;
2868     return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
2869            area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
2870 }
2871
2872 // check if a polygon diagonal intersects any polygon segments
2873 function intersectsPolygon(a, b) {
2874     var p = a;
2875     do {
2876         if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
2877                 intersects(p, p.next, a, b)) return true;
2878         p = p.next;
2879     } while (p !== a);
2880
2881     return false;
2882 }
2883
2884 // check if a polygon diagonal is locally inside the polygon
2885 function locallyInside(a, b) {
2886     return area(a.prev, a, a.next) < 0 ?
2887         area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
2888         area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
2889 }
2890
2891 // check if the middle point of a polygon diagonal is inside the polygon
2892 function middleInside(a, b) {
2893     var p = a,
2894         inside = false,
2895         px = (a.x + b.x) / 2,
2896         py = (a.y + b.y) / 2;
2897     do {
2898         if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
2899                 (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
2900             inside = !inside;
2901         p = p.next;
2902     } while (p !== a);
2903
2904     return inside;
2905 }
2906
2907 // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
2908 // if one belongs to the outer ring and another to a hole, it merges it into a single ring
2909 function splitPolygon(a, b) {
2910     var a2 = new Node(a.i, a.x, a.y),
2911         b2 = new Node(b.i, b.x, b.y),
2912         an = a.next,
2913         bp = b.prev;
2914
2915     a.next = b;
2916     b.prev = a;
2917
2918     a2.next = an;
2919     an.prev = a2;
2920
2921     b2.next = a2;
2922     a2.prev = b2;
2923
2924     bp.next = b2;
2925     b2.prev = bp;
2926
2927     return b2;
2928 }
2929
2930 // create a node and optionally link it with previous one (in a circular doubly linked list)
2931 function insertNode(i, x, y, last) {
2932     var p = new Node(i, x, y);
2933
2934     if (!last) {
2935         p.prev = p;
2936         p.next = p;
2937
2938     } else {
2939         p.next = last.next;
2940         p.prev = last;
2941         last.next.prev = p;
2942         last.next = p;
2943     }
2944     return p;
2945 }
2946
2947 function removeNode(p) {
2948     p.next.prev = p.prev;
2949     p.prev.next = p.next;
2950
2951     if (p.prevZ) p.prevZ.nextZ = p.nextZ;
2952     if (p.nextZ) p.nextZ.prevZ = p.prevZ;
2953 }
2954
2955 function Node(i, x, y) {
2956     // vertice index in coordinates array
2957     this.i = i;
2958
2959     // vertex coordinates
2960     this.x = x;
2961     this.y = y;
2962
2963     // previous and next vertice nodes in a polygon ring
2964     this.prev = null;
2965     this.next = null;
2966
2967     // z-order curve value
2968     this.z = null;
2969
2970     // previous and next nodes in z-order
2971     this.prevZ = null;
2972     this.nextZ = null;
2973
2974     // indicates whether this is a steiner point
2975     this.steiner = false;
2976 }
2977
2978 // return a percentage difference between the polygon area and its triangulation area;
2979 // used to verify correctness of triangulation
2980 earcut.deviation = function (data, holeIndices, dim, triangles) {
2981     var hasHoles = holeIndices && holeIndices.length;
2982     var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
2983
2984     var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
2985     if (hasHoles) {
2986         for (var i = 0, len = holeIndices.length; i < len; i++) {
2987             var start = holeIndices[i] * dim;
2988             var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
2989             polygonArea -= Math.abs(signedArea(data, start, end, dim));
2990         }
2991     }
2992
2993     var trianglesArea = 0;
2994     for (i = 0; i < triangles.length; i += 3) {
2995         var a = triangles[i] * dim;
2996         var b = triangles[i + 1] * dim;
2997         var c = triangles[i + 2] * dim;
2998         trianglesArea += Math.abs(
2999             (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
3000             (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
3001     }
3002
3003     return polygonArea === 0 && trianglesArea === 0 ? 0 :
3004         Math.abs((trianglesArea - polygonArea) / polygonArea);
3005 };
3006
3007 function signedArea(data, start, end, dim) {
3008     var sum = 0;
3009     for (var i = start, j = end - dim; i < end; i += dim) {
3010         sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
3011         j = i;
3012     }
3013     return sum;
3014 }
3015
3016 // turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
3017 earcut.flatten = function (data) {
3018     var dim = data[0][0].length,
3019         result = {vertices: [], holes: [], dimensions: dim},
3020         holeIndex = 0;
3021
3022     for (var i = 0; i < data.length; i++) {
3023         for (var j = 0; j < data[i].length; j++) {
3024             for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]);
3025         }
3026         if (i > 0) {
3027             holeIndex += data[i - 1].length;
3028             result.holes.push(holeIndex);
3029         }
3030     }
3031     return result;
3032 };
3033
3034 },{}],9:[function(require,module,exports){
3035 'use strict';
3036
3037 var OneVersionConstraint = require('individual/one-version');
3038
3039 var MY_VERSION = '7';
3040 OneVersionConstraint('ev-store', MY_VERSION);
3041
3042 var hashKey = '__EV_STORE_KEY@' + MY_VERSION;
3043
3044 module.exports = EvStore;
3045
3046 function EvStore(elem) {
3047     var hash = elem[hashKey];
3048
3049     if (!hash) {
3050         hash = elem[hashKey] = {};
3051     }
3052
3053     return hash;
3054 }
3055
3056 },{"individual/one-version":19}],10:[function(require,module,exports){
3057 'use strict';
3058 var request = require('./request');
3059 var buildQueryObject = require('./buildQueryObject');
3060 var isArray = Array.isArray;
3061
3062 function simpleExtend(obj, obj2) {
3063   var prop;
3064   for (prop in obj2) {
3065     obj[prop] = obj2[prop];
3066   }
3067   return obj;
3068 }
3069
3070 function XMLHttpSource(jsongUrl, config) {
3071   this._jsongUrl = jsongUrl;
3072   if (typeof config === 'number') {
3073     var newConfig = {
3074       timeout: config
3075     };
3076     config = newConfig;
3077   }
3078   this._config = simpleExtend({
3079     timeout: 15000,
3080     headers: {}
3081   }, config || {});
3082 }
3083
3084 XMLHttpSource.prototype = {
3085   // because javascript
3086   constructor: XMLHttpSource,
3087   /**
3088    * buildQueryObject helper
3089    */
3090   buildQueryObject: buildQueryObject,
3091
3092   /**
3093    * @inheritDoc DataSource#get
3094    */
3095   get: function httpSourceGet(pathSet) {
3096     var method = 'GET';
3097     var queryObject = this.buildQueryObject(this._jsongUrl, method, {
3098       paths: pathSet,
3099       method: 'get'
3100     });
3101     var config = simpleExtend(queryObject, this._config);
3102     // pass context for onBeforeRequest callback
3103     var context = this;
3104     return request(method, config, context);
3105   },
3106
3107   /**
3108    * @inheritDoc DataSource#set
3109    */
3110   set: function httpSourceSet(jsongEnv) {
3111     var method = 'POST';
3112     var queryObject = this.buildQueryObject(this._jsongUrl, method, {
3113       jsonGraph: jsongEnv,
3114       method: 'set'
3115     });
3116     var config = simpleExtend(queryObject, this._config);
3117     config.headers["Content-Type"] = "application/x-www-form-urlencoded";
3118     
3119     // pass context for onBeforeRequest callback
3120     var context = this;
3121     return request(method, config, context);
3122
3123   },
3124
3125   /**
3126    * @inheritDoc DataSource#call
3127    */
3128   call: function httpSourceCall(callPath, args, pathSuffix, paths) {
3129     // arguments defaults
3130     args = args || [];
3131     pathSuffix = pathSuffix || [];
3132     paths = paths || [];
3133
3134     var method = 'POST';
3135     var queryData = [];
3136     queryData.push('method=call');
3137     queryData.push('callPath=' + encodeURIComponent(JSON.stringify(callPath)));
3138     queryData.push('arguments=' + encodeURIComponent(JSON.stringify(args)));
3139     queryData.push('pathSuffixes=' + encodeURIComponent(JSON.stringify(pathSuffix)));
3140     queryData.push('paths=' + encodeURIComponent(JSON.stringify(paths)));
3141
3142     var queryObject = this.buildQueryObject(this._jsongUrl, method, queryData.join('&'));
3143     var config = simpleExtend(queryObject, this._config);
3144     config.headers["Content-Type"] = "application/x-www-form-urlencoded";
3145     
3146     // pass context for onBeforeRequest callback
3147     var context = this;
3148     return request(method, config, context);
3149   }
3150 };
3151 // ES6 modules
3152 XMLHttpSource.XMLHttpSource = XMLHttpSource;
3153 XMLHttpSource['default'] = XMLHttpSource;
3154 // commonjs
3155 module.exports = XMLHttpSource;
3156
3157 },{"./buildQueryObject":11,"./request":14}],11:[function(require,module,exports){
3158 'use strict';
3159 module.exports = function buildQueryObject(url, method, queryData) {
3160   var qData = [];
3161   var keys;
3162   var data = {url: url};
3163   var isQueryParamUrl = url.indexOf('?') !== -1;
3164   var startUrl = (isQueryParamUrl) ? '&' : '?';
3165
3166   if (typeof queryData === 'string') {
3167     qData.push(queryData);
3168   } else {
3169
3170     keys = Object.keys(queryData);
3171     keys.forEach(function (k) {
3172       var value = (typeof queryData[k] === 'object') ? JSON.stringify(queryData[k]) : queryData[k];
3173       qData.push(k + '=' + encodeURIComponent(value));
3174     });
3175   }
3176
3177   if (method === 'GET') {
3178     data.url += startUrl + qData.join('&');
3179   } else {
3180     data.data = qData.join('&');
3181   }
3182
3183   return data;
3184 };
3185
3186 },{}],12:[function(require,module,exports){
3187 (function (global){
3188 'use strict';
3189 // Get CORS support even for older IE
3190 module.exports = function getCORSRequest() {
3191     var xhr = new global.XMLHttpRequest();
3192     if ('withCredentials' in xhr) {
3193         return xhr;
3194     } else if (!!global.XDomainRequest) {
3195         return new XDomainRequest();
3196     } else {
3197         throw new Error('CORS is not supported by your browser');
3198     }
3199 };
3200
3201 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3202
3203 },{}],13:[function(require,module,exports){
3204 (function (global){
3205 'use strict';
3206 module.exports = function getXMLHttpRequest() {
3207   var progId,
3208     progIds,
3209     i;
3210   if (global.XMLHttpRequest) {
3211     return new global.XMLHttpRequest();
3212   } else {
3213     try {
3214     progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'];
3215     for (i = 0; i < 3; i++) {
3216       try {
3217         progId = progIds[i];
3218         if (new global.ActiveXObject(progId)) {
3219           break;
3220         }
3221       } catch(e) { }
3222     }
3223     return new global.ActiveXObject(progId);
3224     } catch (e) {
3225     throw new Error('XMLHttpRequest is not supported by your browser');
3226     }
3227   }
3228 };
3229
3230 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3231
3232 },{}],14:[function(require,module,exports){
3233 'use strict';
3234 var getXMLHttpRequest = require('./getXMLHttpRequest');
3235 var getCORSRequest = require('./getCORSRequest');
3236 var hasOwnProp = Object.prototype.hasOwnProperty;
3237
3238 var noop = function() {};
3239
3240 function Observable() {}
3241
3242 Observable.create = function(subscribe) {
3243   var o = new Observable();
3244
3245   o.subscribe = function(onNext, onError, onCompleted) {
3246
3247     var observer;
3248     var disposable;
3249
3250     if (typeof onNext === 'function') {
3251         observer = {
3252             onNext: onNext,
3253             onError: (onError || noop),
3254             onCompleted: (onCompleted || noop)
3255         };
3256     } else {
3257         observer = onNext;
3258     }
3259
3260     disposable = subscribe(observer);
3261
3262     if (typeof disposable === 'function') {
3263       return {
3264         dispose: disposable
3265       };
3266     } else {
3267       return disposable;
3268     }
3269   };
3270
3271   return o;
3272 };
3273
3274 function request(method, options, context) {
3275   return Observable.create(function requestObserver(observer) {
3276
3277     var config = {
3278       method: method || 'GET',
3279       crossDomain: false,
3280       async: true,
3281       headers: {},
3282       responseType: 'json'
3283     };
3284
3285     var xhr,
3286       isDone,
3287       headers,
3288       header,
3289       prop;
3290
3291     for (prop in options) {
3292       if (hasOwnProp.call(options, prop)) {
3293         config[prop] = options[prop];
3294       }
3295     }
3296
3297     // Add request with Headers
3298     if (!config.crossDomain && !config.headers['X-Requested-With']) {
3299       config.headers['X-Requested-With'] = 'XMLHttpRequest';
3300     }
3301
3302     // allow the user to mutate the config open
3303     if (context.onBeforeRequest != null) {
3304       context.onBeforeRequest(config);
3305     }
3306
3307     // create xhr
3308     try {
3309       xhr = config.crossDomain ? getCORSRequest() : getXMLHttpRequest();
3310     } catch (err) {
3311       observer.onError(err);
3312     }
3313     try {
3314       // Takes the url and opens the connection
3315       if (config.user) {
3316         xhr.open(config.method, config.url, config.async, config.user, config.password);
3317       } else {
3318         xhr.open(config.method, config.url, config.async);
3319       }
3320
3321       // Sets timeout information
3322       xhr.timeout = config.timeout;
3323
3324       // Anything but explicit false results in true.
3325       xhr.withCredentials = config.withCredentials !== false;
3326
3327       // Fills the request headers
3328       headers = config.headers;
3329       for (header in headers) {
3330         if (hasOwnProp.call(headers, header)) {
3331           xhr.setRequestHeader(header, headers[header]);
3332         }
3333       }
3334
3335       if (config.responseType) {
3336         try {
3337           xhr.responseType = config.responseType;
3338         } catch (e) {
3339           // WebKit added support for the json responseType value on 09/03/2013
3340           // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
3341           // known to throw when setting the value "json" as the response type. Other older
3342           // browsers implementing the responseType
3343           //
3344           // The json response type can be ignored if not supported, because JSON payloads are
3345           // parsed on the client-side regardless.
3346           if (config.responseType !== 'json') {
3347             throw e;
3348           }
3349         }
3350       }
3351
3352       xhr.onreadystatechange = function onreadystatechange(e) {
3353         // Complete
3354         if (xhr.readyState === 4) {
3355           if (!isDone) {
3356             isDone = true;
3357             onXhrLoad(observer, xhr, e);
3358           }
3359         }
3360       };
3361
3362       // Timeout
3363       xhr.ontimeout = function ontimeout(e) {
3364         if (!isDone) {
3365           isDone = true;
3366           onXhrError(observer, xhr, 'timeout error', e);
3367         }
3368       };
3369
3370       // Send Request
3371       xhr.send(config.data);
3372
3373     } catch (e) {
3374       observer.onError(e);
3375     }
3376     // Dispose
3377     return function dispose() {
3378       // Doesn't work in IE9
3379       if (!isDone && xhr.readyState !== 4) {
3380         isDone = true;
3381         xhr.abort();
3382       }
3383     };//Dispose
3384   });
3385 }
3386
3387 /*
3388  * General handling of ultimate failure (after appropriate retries)
3389  */
3390 function _handleXhrError(observer, textStatus, errorThrown) {
3391   // IE9: cross-domain request may be considered errors
3392   if (!errorThrown) {
3393     errorThrown = new Error(textStatus);
3394   }
3395
3396   observer.onError(errorThrown);
3397 }
3398
3399 function onXhrLoad(observer, xhr, e) {
3400   var responseData,
3401     responseObject,
3402     responseType;
3403
3404   // If there's no observer, the request has been (or is being) cancelled.
3405   if (xhr && observer) {
3406     responseType = xhr.responseType;
3407     // responseText is the old-school way of retrieving response (supported by IE8 & 9)
3408     // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
3409     responseData = ('response' in xhr) ? xhr.response : xhr.responseText;
3410
3411     // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
3412     var status = (xhr.status === 1223) ? 204 : xhr.status;
3413
3414     if (status >= 200 && status <= 399) {
3415       try {
3416         if (responseType !== 'json') {
3417           responseData = JSON.parse(responseData || '');
3418         }
3419         if (typeof responseData === 'string') {
3420           responseData = JSON.parse(responseData || '');
3421         }
3422       } catch (e) {
3423         _handleXhrError(observer, 'invalid json', e);
3424       }
3425       observer.onNext(responseData);
3426       observer.onCompleted();
3427       return;
3428
3429     } else if (status === 401 || status === 403 || status === 407) {
3430
3431       return _handleXhrError(observer, responseData);
3432
3433     } else if (status === 410) {
3434       // TODO: Retry ?
3435       return _handleXhrError(observer, responseData);
3436
3437     } else if (status === 408 || status === 504) {
3438       // TODO: Retry ?
3439       return _handleXhrError(observer, responseData);
3440
3441     } else {
3442
3443       return _handleXhrError(observer, responseData || ('Response code ' + status));
3444
3445     }//if
3446   }//if
3447 }//onXhrLoad
3448
3449 function onXhrError(observer, xhr, status, e) {
3450   _handleXhrError(observer, status || xhr.statusText || 'request error', e);
3451 }
3452
3453 module.exports = request;
3454
3455 },{"./getCORSRequest":12,"./getXMLHttpRequest":13}],15:[function(require,module,exports){
3456 (function (global){
3457 !function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.falcor=t()}}(function(){var t;return function e(t,n,r){function o(s,u){if(!n[s]){if(!t[s]){var a="function"==typeof require&&require;if(!u&&a)return a(s,!0);if(i)return i(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var p=n[s]={exports:{}};t[s][0].call(p.exports,function(e){var n=t[s][1][e];return o(n?n:e)},p,p.exports,e,t,n,r)}return n[s].exports}for(var i="function"==typeof require&&require,s=0;s<r.length;s++)o(r[s]);return o}({1:[function(t,e,n){var r=t(32),o=t(130);r.atom=o.atom,r.ref=o.ref,r.error=o.error,r.pathValue=o.pathValue,r.HttpDataSource=t(125),e.exports=r},{125:125,130:130,32:32}],2:[function(t,e,n){function r(t){var e=t||{};this._root=e._root||new o(e),this._path=e.path||e._path||[],this._scheduler=e.scheduler||e._scheduler||new l,this._source=e.source||e._source,this._request=e.request||e._request||new s(this,this._scheduler),this._ID=N++,"number"==typeof e.maxSize?this._maxSize=e.maxSize:this._maxSize=e._maxSize||r.prototype._maxSize,"number"==typeof e.collectRatio?this._collectRatio=e.collectRatio:this._collectRatio=e._collectRatio||r.prototype._collectRatio,(e.boxed||e.hasOwnProperty("_boxed"))&&(this._boxed=e.boxed||e._boxed),(e.materialized||e.hasOwnProperty("_materialized"))&&(this._materialized=e.materialized||e._materialized),"boolean"==typeof e.treatErrorsAsValues?this._treatErrorsAsValues=e.treatErrorsAsValues:e.hasOwnProperty("_treatErrorsAsValues")&&(this._treatErrorsAsValues=e._treatErrorsAsValues),e.cache&&this.setCache(e.cache)}var o=t(4),i=t(3),s=t(55),u=t(64),a=t(65),c=t(61),p=t(63),h=t(73),f=t(75),l=t(74),d=t(81),v=t(84),y=t(49),b=t(134),m=t(88),g=t(100),w=t(96),x=t(102),_=t(98),S=t(99),E=t(77),C=t(76),A=t(130),N=0,k=t(116),O=function(){},P=t(14),j=t(19),D={pathValue:!0,pathSyntax:!0,json:!0,jsonGraph:!0},q=t(72);e.exports=r,r.ref=A.ref,r.atom=A.atom,r.error=A.error,r.pathValue=A.pathValue,r.prototype.constructor=r,r.prototype._materialized=!1,r.prototype._boxed=!1,r.prototype._progressive=!1,r.prototype._treatErrorsAsValues=!1,r.prototype._maxSize=Math.pow(2,53)-1,r.prototype._collectRatio=.75,r.prototype.get=t(71),r.prototype._getWithPaths=t(70),r.prototype.set=function(){var t=k(arguments,D,"set");return t!==!0?new u(function(e){e.onError(t)}):this._set.apply(this,arguments)},r.prototype.preload=function(){var t=k(arguments,q,"preload");if(t!==!0)return new u(function(e){e.onError(t)});var e=Array.prototype.slice.call(arguments),n=this;return new u(function(t){return n.get.apply(n,e).subscribe(function(){},function(e){t.onError(e)},function(){t.onCompleted()})})},r.prototype._set=function(){var t,e=-1,n=arguments.length,r=arguments[n-1];for(w(r)?n-=1:r=void 0,t=new Array(n);++e<n;)t[e]=arguments[e];return a.create(this,t,r)},r.prototype.call=function(){var t,e=-1,n=arguments.length;for(t=new Array(n);++e<n;){var r=arguments[e];t[e]=r;var o=typeof r;if(e>1&&!Array.isArray(r)||0===e&&!Array.isArray(r)&&"string"!==o||1===e&&!Array.isArray(r)&&!x(r))return new u(function(t){t.onError(new Error("Invalid argument"))})}return c.create(this,t)},r.prototype.invalidate=function(){var t,e=-1,n=arguments.length,r=arguments[n-1];for(t=new Array(n);++e<n;)if(t[e]=b.fromPath(arguments[e]),"object"!=typeof t[e])throw new Error("Invalid argument");p.create(this,t,r).subscribe(O,function(t){throw t})},r.prototype.deref=t(5),r.prototype.getValue=t(16),r.prototype.setValue=t(79),r.prototype._getValueSync=t(24),r.prototype._setValueSync=t(80),r.prototype._derefSync=t(6),r.prototype.setCache=function(t){var e=this._root.cache;if(t!==e){var n=this._root,r=this._path;this._path=[],this._root.cache={},"undefined"!=typeof e&&y(n,n.expired,m(e),0),S(t)?C(this,[t]):_(t)?E(this,[t]):g(t)&&E(this,[{json:t}]),this._path=r}else"undefined"==typeof e&&(this._root.cache={});return this},r.prototype.getCache=function(){var t=v(arguments);if(0===t.length)return P(this._root.cache);var e=[{}],n=this._path;return j.getWithPathsAsJSONGraph(this,t,e),this._path=n,e[0].jsonGraph},r.prototype.getVersion=function(t){var e=t&&b.fromPath(t)||[];if(Array.isArray(e)===!1)throw new Error("Model#getVersion must be called with an Array path.");return this._path.length&&(e=this._path.concat(e)),this._getVersion(this,e)},r.prototype._syncCheck=function(t){if(Boolean(this._source)&&this._root.syncRefCount<=0&&this._root.unsafeMode===!1)throw new Error("Model#"+t+" may only be called within the context of a request selector.");return!0},r.prototype._clone=function(t){var e=new r(this);for(var n in t){var o=t[n];"delete"===o?delete e[n]:e[n]=o}return e.setCache=void 0,e},r.prototype.batch=function(t){var e=t;"number"==typeof e?e=new f(Math.round(Math.abs(e))):e&&e.schedule||(e=new h);var n=this._clone();return n._request=new s(n,e),n},r.prototype.unbatch=function(){var t=this._clone();return t._request=new s(t,new l),t},r.prototype.treatErrorsAsValues=function(){return this._clone({_treatErrorsAsValues:!0})},r.prototype.asDataSource=function(){return new i(this)},r.prototype._materialize=function(){return this._clone({_materialized:!0})},r.prototype._dematerialize=function(){return this._clone({_materialized:"delete"})},r.prototype.boxValues=function(){return this._clone({_boxed:!0})},r.prototype.unboxValues=function(){return this._clone({_boxed:"delete"})},r.prototype.withoutDataSource=function(){return this._clone({_source:"delete"})},r.prototype.toJSON=function(){return{$type:"ref",value:this._path}},r.prototype.getPath=function(){return d(this._path)},r.prototype._getBoundValue=t(13),r.prototype._getVersion=t(18),r.prototype._getValueSync=t(17),r.prototype._getPathValuesAsPathMap=j.getWithPathsAsPathMap,r.prototype._getPathValuesAsJSONG=j.getWithPathsAsJSONGraph,r.prototype._setPathValuesAsJSON=t(78),r.prototype._setPathValuesAsJSONG=t(78),r.prototype._setPathValuesAsPathMap=t(78),r.prototype._setPathValuesAsValues=t(78),r.prototype._setPathMapsAsJSON=t(77),r.prototype._setPathMapsAsJSONG=t(77),r.prototype._setPathMapsAsPathMap=t(77),r.prototype._setPathMapsAsValues=t(77),r.prototype._setJSONGsAsJSON=t(76),r.prototype._setJSONGsAsJSONG=t(76),r.prototype._setJSONGsAsPathMap=t(76),r.prototype._setJSONGsAsValues=t(76),r.prototype._setCache=t(77),r.prototype._invalidatePathValuesAsJSON=t(48),r.prototype._invalidatePathMapsAsJSON=t(47)},{100:100,102:102,116:116,13:13,130:130,134:134,14:14,16:16,17:17,18:18,19:19,24:24,3:3,4:4,47:47,48:48,49:49,5:5,55:55,6:6,61:61,63:63,64:64,65:65,70:70,71:71,72:72,73:73,74:74,75:75,76:76,77:77,78:78,79:79,80:80,81:81,84:84,88:88,96:96,98:98,99:99}],3:[function(t,e,n){function r(t){this._model=t._materialize().treatErrorsAsValues()}r.prototype.get=function(t){return this._model.get.apply(this._model,t)._toJSONG()},r.prototype.set=function(t){return this._model.set(t)._toJSONG()},r.prototype.call=function(t,e,n,r){var o=[t,e,n].concat(r);return this._model.call.apply(this._model,o)._toJSONG()},e.exports=r},{}],4:[function(t,e,n){function r(t){var e=t||{};this.syncRefCount=0,this.expired=e.expired||[],this.unsafeMode=e.unsafeMode||!1,this.collectionScheduler=e.collectionScheduler||new s,this.cache={},o(e.comparator)&&(this.comparator=e.comparator),o(e.errorSelector)&&(this.errorSelector=e.errorSelector),o(e.onChange)&&(this.onChange=e.onChange)}var o=t(96),i=t(91),s=t(74);r.prototype.errorSelector=function(t,e){return e},r.prototype.comparator=function(t,e){return i(t,"value")&&i(e,"value")?t.value===e.value&&t.$type===e.$type&&t.$expires===e.$expires:t===e},e.exports=r},{74:74,91:91,96:96}],5:[function(t,e,n){function r(t,e){var n,r=!1;try{++t._root.syncRefCount,n=t._derefSync(e)}catch(i){n=i,r=!0}finally{--t._root.syncRefCount}return r?o.Observable["throw"](n):o.Observable["return"](n)}var o=t(159),i=t(134);e.exports=function(t){for(var e=this,n=-1,s=arguments.length-1,u=new Array(s),a=i.fromPath(t);++n<s;)u[n]=i.fromPath(arguments[n+1]);if(0===s)throw new Error("Model#deref requires at least one value path.");return o.Observable.defer(function(){return r(e,a)}).flatMap(function(t){if(Boolean(t)){if(s>0){var n=o.Observable.of(t);return t.get.apply(t,u)["catch"](o.Observable.empty()).concat(n).last().flatMap(function(){return r(e,a)}).filter(function(t){return t})}return o.Observable["return"](t)}if(s>0){var i=u.map(function(t){return a.concat(t)});return e.get.apply(e,i).concat(o.Observable.defer(function(){return r(e,a)})).last().filter(function(t){return t})}return o.Observable.empty()})}},{134:134,159:159}],6:[function(t,e,n){var r=t(134),o=t(13),i=t(8),s=t(118);e.exports=function(t){var e=r.fromPath(t);if(!Array.isArray(e))throw new Error("Model#derefSync must be called with an Array path.");var n=o(this,this._path.concat(e),!1),u=n.path,a=n.value,c=n.found;if(c&&void 0!==a&&(a.$type!==s||void 0!==a.value)){if(a.$type)throw new i;return this._clone({_path:u})}}},{118:118,13:13,134:134,8:8}],7:[function(t,e,n){function r(){this.message=r.message,this.stack=(new Error).stack}r.prototype=new Error,r.prototype.name="BoundJSONGraphModelError",r.message="It is not legal to use the JSON Graph format from a bound Model. JSON Graph format can only be used from a root model.",e.exports=r},{}],8:[function(t,e,n){function r(t,e){this.message=i,this.stack=(new Error).stack,this.boundPath=t,this.shortedPath=e}var o="InvalidModelError",i="The boundPath of the model is not valid since a value or error was found before the path end.";r.prototype=new Error,r.prototype.name=o,r.message=i,e.exports=r},{}],9:[function(t,e,n){function r(t){this.message="An exception was thrown when making a request.",this.stack=(new Error).stack,this.innerError=t}var o="InvalidSourceError";r.prototype=new Error,r.prototype.name=o,r.is=function(t){return t&&t.name===o},e.exports=r},{}],10:[function(t,e,n){function r(){this.message="The allowed number of retries have been exceeded.",this.stack=(new Error).stack}var o="MaxRetryExceededError";r.prototype=new Error,r.prototype.name=o,r.is=function(t){return t&&t.name===o},e.exports=r},{}],11:[function(t,e,n){function r(t,e,n,r,o,h,f){for(var l,d,v=n,y=o,b=r,m=0;;){if(0===m&&b[c]?(m=y.length,d=b[c]):(l=y[m++],d=v[l]),d){var g=d.$type,w=g&&d.value||d;if(m<y.length){if(g){v=d;break}v=d;continue}if(v=d,g&&u(d))break;if(b[c]||i(b,d),g===a){f?s(t,d,h,null,null,null,y,y.length,f):p(t,d),m=0,y=w,b=d,v=e;continue}break}v=void 0;break}if(m<y.length&&void 0!==v){for(var x=[],_=0;m>_;_++)x[_]=y[_];y=x}return[v,y]}var o=t(26),i=o.create,s=t(22),u=t(27),a=t(120),c=t(33),p=t(29).promote;e.exports=r},{120:120,22:22,26:26,27:27,29:29,33:33}],12:[function(t,e,n){var r=t(15),o=t(8),i=t(7);e.exports=function(t,e){return function(n,s,u){var a,c,p,h=u[0],f={values:u,optimizedPaths:[]},l=n._root.cache,d=n._path,v=l,y=d.length,b=[];if(y){if(e)return{criticalError:new i};if(v=r(n,d),v.$type)return{criticalError:new o(d,d)};for(a=[],c=0;y>c;++c)a[c]=d[c]}else a=[],y=0;for(c=0,p=s.length;p>c;c++)t(n,l,v,s[c],0,h,f,b,a,y,e);return f}}},{15:15,7:7,8:8}],13:[function(t,e,n){var r=t(17),o=t(8);e.exports=function(t,e,n){var i,s,u,a,c,p=e,h=e;for(i=t._boxed,n=t._materialized,s=t._treatErrorsAsValues,t._boxed=!0,t._materialized=void 0===n||n,t._treatErrorsAsValues=!0,u=r(t,p.concat(null),!0),t._boxed=i,t._materialized=n,t._treatErrorsAsValues=s,p=u.optimizedPath,a=u.shorted,c=u.found,u=u.value;p.length&&null===p[p.length-1];)p.pop();if(c&&a)throw new o(h,p);return{path:p,value:u,shorted:a,found:c}}},{17:17,8:8}],14:[function(t,e,n){function r(t){var e,n,r,o={},i=Object.keys(t);for(n=0,r=i.length;r>n;n++)e=i[n],s(e)||(o[e]=t[e]);return o}function o(t,e,n){Object.keys(t).filter(function(e){return!s(e)&&t[e]}).forEach(function(n){var s=t[n],u=e[n];if(u||(u=e[n]={}),s.$type){var a,c=s.value&&"object"==typeof s.value,p=!t[i];return a=c||p?r(s):s.value,void(e[n]=a)}o(s,u,n)})}var i=t(37),s=t(97);e.exports=function(t){var e={};return o(t,e),e}},{37:37,97:97}],15:[function(t,e,n){e.exports=function(t,e){for(var n=t._root.cache,r=-1,o=e.length;++r<o&&n&&!n.$type;)n=n[e[r]];return n}},{}],16:[function(t,e,n){var r=t(64),o=t(134);e.exports=function(t){for(var e=o.fromPath(t),n=0,i=e.length;++n<i;)if("object"==typeof e[n])return new r(function(t){t.onError(new Error("Paths must be simple paths"))});var s=this;return new r(function(t){return s.get(e).subscribe(function(n){for(var r=n.json,o=-1,i=e.length;r&&++o<i;)r=r[e[o]];t.onNext(r)},function(e){t.onError(e)},function(){t.onCompleted()})})}},{134:134,64:64}],17:[function(t,e,n){var r=t(11),o=t(25),i=t(27),s=t(29).promote,u=t(120),a=t(118),c=t(119);e.exports=function(t,e,n){for(var p,h,f,l,d,v=t._root.cache,y=e.length,b=[],m=!1,g=!1,w=0,x=v,_=v,S=v,E=!0,C=!1;x&&y>w;){if(p=e[w++],null!==p&&(x=_[p],b[b.length]=p),!x){S=void 0,m=!0,E=!1;break}if(f=x.$type,f===a&&void 0===x.value){S=void 0,E=!1,m=y>w;break}if(y>w){if(f===u){if(i(x)){C=!0,S=void 0,E=!1;break}if(l=r(t,v,v,x,x.value),d=l[0],!d){S=void 0,x=void 0,E=!1;break}f=d.$type,x=d,b=l[1].slice(0)}if(f)break}else S=x;_=x}if(y>w&&!C){for(h=w;y>h;++h)if(null!==e[w]){g=!0;break}for(g?(m=!0,S=void 0):S=x,h=w;y>h;++h)null!==e[h]&&(b[b.length]=e[h])}if(S&&f&&(i(S)?S=void 0:s(t,S)),S&&f===c&&!t._treatErrorsAsValues)throw{path:w===y?e:e.slice(0,w),value:S.value};return S&&t._boxed?S=Boolean(f)&&!n?o(S):S:!S&&t._materialized?S={$type:a}:S&&(S=S.value),{value:S,shorted:m,optimizedPath:b,found:E}}},{11:11,118:118,119:119,120:120,25:25,27:27,29:29}],18:[function(t,e,n){var r=t(46);e.exports=function(t,e){var n=t._getValueSync({_boxed:!0,_root:t._root,_treatErrorsAsValues:t._treatErrorsAsValues},e,!0).value,o=n&&n[r];return null==o?-1:o}},{46:46}],19:[function(t,e,n){var r=t(12),o=t(31),i=r(o,!1),s=r(o,!0);e.exports={getValueSync:t(17),getBoundValue:t(13),getWithPathsAsPathMap:i,getWithPathsAsJSONGraph:s}},{12:12,13:13,17:17,31:31}],20:[function(t,e,n){var r=t(29),o=t(25),i=r.promote;e.exports=function(t,e,n,r,s){var u=e.value;s.errors||(s.errors=[]),t._boxed&&(u=o(e)),s.errors.push({path:r.slice(0,n+1),value:u}),i(t,e)}},{25:25,29:29}],21:[function(t,e,n){function r(t,e,n,r,o,i,s){s.requestedMissingPaths.push(r.slice(0,n).concat(e)),s.optimizedMissingPaths.push(o.slice(0,i).concat(e))}var o=t(30),i=o.fastCopy;e.exports=function(t,e,n,o,s,u,a){var c;o.requestedMissingPaths||(o.requestedMissingPaths=[],o.optimizedMissingPaths=[]),c=n<e.length?i(e,n):[],r(t,c,n,s,u,a,o)}},{30:30}],22:[function(t,e,n){var r=t(29),o=t(25),i=r.promote,s=t(120),u=t(118),a=t(119),c=t(37);e.exports=function(t,e,n,r,p,h,f,l,d,v){if(n){var y,b,m,g,w,x,_,S,E=!1;if(e&&i(t,e),e&&void 0!==e.value||(E=t._materialized),E)S={$type:u};else if(t._boxed)S=o(e);else if(e.$type===s||e.$type===a)S=d?o(e):e.value;else if(d){var C=e.value&&"object"==typeof e.value,A=!e[c];S=C||A?o(e):e.value}else S=e.value;if(p&&(p.hasValue=!0),d){for(w=n.jsonGraph,w||(w=n.jsonGraph={},n.paths=[]),y=0,b=l-1;b>y;y++)g=f[y],w[g]||(w[g]={}),w=w[g];g=f[y],w[g]=E?{$type:u}:S,h&&n.paths.push(h.slice(0,r))}else if(0===r)n.json=S;else{for(w=n.json,w||(w=n.json={}),y=0;r-1>y;y++)m=h[y],w[m]||(w[m]={}),x=w,_=m,w=w[m];m=h[y],null!==m?w[m]=S:x[_]=S}}}},{118:118,119:119,120:120,25:25,29:29,37:37}],23:[function(t,e,n){var r=t(27),o=t(26),i=t(29),s=o.remove,u=i.splice,a=t(119),c=t(20),p=t(22),h=t(21),f=t(28),l=t(35);e.exports=function(t,e,n,o,i,d,v,y,b,m,g){var w=e&&e.$type,x=e&&void 0===e.value;return e&&w?void(r(e)?(e[l]||(u(t,e),s(e)),h(t,n,o,d,v,y,b)):w===a?(g&&(v[o]=null),m||t._treatErrorsAsValues?p(t,e,i,o,d,v,y,b,m,g):c(t,e,o,v,d)):(g&&(v[o]=null),(!x||x&&t._materialized)&&p(t,e,i,o,d,v,y,b,m,g))):void(f(t)?p(t,e,i,o,d,v,y,b,m,g):h(t,n,o,d,v,y,b))}},{119:119,20:20,21:21,22:22,26:26,27:27,28:28,29:29,35:35}],24:[function(t,e,n){var r=t(134);e.exports=function(t){var e=r.fromPath(t);if(Array.isArray(e)===!1)throw new Error("Model#getValueSync must be called with an Array path.");return this._path.length&&(e=this._path.concat(e)),this._syncCheck("getValueSync")&&this._getValueSync(this,e).value}},{134:134}],25:[function(t,e,n){var r=t(40);e.exports=function(t){var e,n,o,i=Object.keys(t);for(e={},n=0,o=i.length;o>n;n++){var s=i[n];s[0]!==r&&(e[s]=t[s])}return e}},{40:40}],26:[function(t,e,n){function r(t,e){var n=e[a]||0;e[i+n]=t,e[a]=n+1,t[u]=n,t[s]=e}function o(t){var e=t[s];if(e){for(var n=t[u],r=e[a];r>n;)e[i+n]=e[i+n+1],++n;e[a]=r-1,t[s]=void 0,t[u]=void 0}}var i=t(43),s=t(33),u=t(42),a=t(44);e.exports={create:r,remove:o}},{33:33,42:42,43:43,44:44}],27:[function(t,e,n){var r=t(106);e.exports=function(t){var e=void 0===t.$expires&&-1||t.$expires;return-1!==e&&1!==e&&(0===e||e<r())}},{106:106}],28:[function(t,e,n){e.exports=function(t){return t._materialized&&!t._source}},{}],29:[function(t,e,n){function r(t,e){var n=t._root,r=n[i];if(r!==e){var o=e[a],s=e[u];s&&(s[a]=o),o&&(o[u]=s),e[a]=void 0,n[i]=e,e[u]=r,r[a]=e}}function o(t,e){var n=t._root,r=e[a],o=e[u];o&&(o[a]=r),r&&(r[u]=o),e[a]=void 0,e===n[i]&&(n[i]=void 0),e===n[s]&&(n[s]=void 0),e[c]=!0,n.expired.push(e)}var i=t(34),s=t(45),u=t(38),a=t(41),c=t(35);e.exports={promote:r,splice:o}},{34:34,35:35,38:38,41:41,45:45}],30:[function(t,e,n){function r(t,e){var n,r,o,i=[];for(r=0,o=e||0,n=t.length;n>o;r++,o++)i[r]=t[o];return i}function o(t,e){var n,r,o,i=[];for(n=0,r=t.length;r>n;n++)i[n]=t[n];for(o=0,r=e.length;r>o;o++)null!==e[o]&&(i[n++]=e[o]);return i}function i(t,e){var n,r,o,i=[];for(n=0,r=t.length;r>n;n++)i[n]=t[n];for(o=0,r=e.length;r>o;o++)i[n++]=e[o];return i}e.exports={fastCat:i,fastCatSkipNulls:o,fastCopy:r}},{}],31:[function(t,e,n){var r=t(11),o=t(23),i=t(27),s=t(143).iterateKeySet,u=t(120),a=t(29).promote;e.exports=function c(t,e,n,p,h,f,l,d,v,y,b,m){var g=m,w=v;if(!n||n&&n.$type||h===p.length)return void o(t,n,p,h,f,l,d,w,y,b,g);var x,_;x=p[h];var S="object"==typeof x,E=h+1,C=!1,A=x;if(S&&(C={},A=s(x,C)),void 0!==A||!C.done){var N=y+1;do{g=!1;var k;null===A?k=n:(k=n[A],w[y]=A,d[h]=A);var O=w,P=N;if(k){var j=k.$type,D=j&&k.value||k;if(E<p.length&&j&&j===u&&!i(k)){b&&o(t,k,p,E,f,l,null,w,P,b,g),a(t,k);var q=r(t,e,e,k,D,f,b);g=!0,k=q[0];var R=q[1];for(O=[],P=R.length,_=0;P>_;++_)O[_]=R[_]}}c(t,e,k,p,E,f,l,d,O,P,b,g),C&&!C.done&&(A=s(x,C))}while(C&&!C.done)}}},{11:11,120:120,143:143,23:23,27:27,29:29}],32:[function(t,e,n){"use strict";function r(t){return new r.Model(t)}"function"==typeof Promise?r.Promise=Promise:r.Promise=t(151),e.exports=r,r.Model=t(2)},{151:151,2:2}],33:[function(t,e,n){e.exports=t(40)+"context"},{40:40}],34:[function(t,e,n){e.exports=t(40)+"head"},{40:40}],35:[function(t,e,n){e.exports=t(40)+"invalidated"},{40:40}],36:[function(t,e,n){e.exports=t(40)+"key"},{40:40}],37:[function(t,e,n){e.exports="$modelCreated"},{}],38:[function(t,e,n){e.exports=t(40)+"next"},{40:40}],39:[function(t,e,n){e.exports=t(40)+"parent"},{40:40}],40:[function(t,e,n){e.exports=String.fromCharCode(30)},{}],41:[function(t,e,n){e.exports=t(40)+"prev"},{40:40}],42:[function(t,e,n){e.exports=t(40)+"ref-index"},{40:40}],43:[function(t,e,n){e.exports=t(40)+"ref"},{40:40}],44:[function(t,e,n){e.exports=t(40)+"refs-length"},{40:40}],45:[function(t,e,n){e.exports=t(40)+"tail"},{40:40}],46:[function(t,e,n){e.exports=t(40)+"version"},{40:40}],47:[function(t,e,n){function r(t,e,n,o,s,u,c,p,h,f){if(!_(t)&&!t.$type)for(var l in t)if(l[0]!==a&&"$"!==l[0]&&m(t,l)){var d=t[l],v=g(d)&&!d.$type,y=i(n,o,s,l,d,v,!1,u,c,p,h,f),w=y[0],x=y[1];w&&(v?r(d,e+1,n,x,w,u,c,p,h,f):A(w,x,l,p)&&C(x,b(w),p,u))}}function o(t,e,n,r,o,s,a,h){if(w(n))return S(n,o,s),[void 0,e];y(s,n);var d=n,v=n.value,b=e;if(n=n[p],null!=n)b=n[c]||e;else{var m=0,g=v.length-1;b=n=e;do{var x=v[m],E=g>m,C=i(e,b,n,x,t,E,!0,r,o,s,a,h);if(n=C[0],_(n))return C;b=C[1]}while(m++<g);if(d[p]!==n){var A=n[l]||0;n[l]=A+1,n[u+A]=d,d[p]=n,d[f]=A}}return[n,b]}function i(t,e,n,r,i,u,a,c,p,h,f,l){for(var v=n.$type;v===d;){var y=o(i,t,n,c,p,h,f,l);if(n=y[0],_(n))return y;e=y[1],v=n&&n.$type}if(void 0!==v)return[n,e];if(null==r){if(u)throw new Error("`null` is not allowed in branch key positions.");n&&(r=n[s])}else e=n,n=e[r];return[n,e]}var s=t(36),u=t(43),a=t(40),c=t(39),p=t(33),h=t(46),f=t(42),l=t(44),d=t(120),v=t(13),y=t(50),b=t(88),m=t(91),g=t(100),w=t(95),x=t(96),_=t(102),S=t(86),E=t(92),C=t(115),A=t(109);e.exports=function(t,e){for(var n=t._root,o=n,i=n.expired,s=E(),u=n._comparator,a=n._errorSelector,p=t._path,f=n.cache,l=p.length?v(t,p).value:f,d=l[c]||f,y=f[h],b=-1,m=e.length;++b<m;){var g=e[b];r(g.json,0,f,d,l,s,i,o,u,a)}var w=f[h],_=n.onChange;x(_)&&y!==w&&_()}},{100:100,102:102,109:109,115:115,120:120,13:13,33:33,36:36,39:39,40:40,42:42,43:43,44:44,46:46,50:50,86:86,88:88,91:91,92:92,95:95,96:96}],48:[function(t,e,n){function r(t,e,n,o,s,u,a,c){var p={},h=e<t.length-1,f=t[e],l=x(f,p);do{var d=i(n,o,s,l,h,!1,u,a,c),v=d[0],b=d[1];v&&(h?r(t,e+1,n,b,v,u,a,c):E(v,b,l,c)&&S(b,y(v),c,u)),l=x(f,p)}while(!p.done)}function o(t,e,n,r,o){if(b(e))return w(e,r,o),[void 0,t];v(o,e);var s=e,p=e.value,l=t;if(e=e[c],null!=e)l=e[a]||t;else{var d=0,y=p.length-1;l=e=t;do{var m=p[d],x=y>d,_=i(t,l,e,m,x,!0,n,r,o);if(e=_[0],g(e))return _;l=_[1]}while(d++<y);if(s[c]!==e){var S=e[f]||0;e[f]=S+1,e[u+S]=s,s[c]=e,s[h]=S}}return[e,l]}function i(t,e,n,r,i,u,a,c,p){for(var h=n.$type;h===l;){var f=o(t,n,a,c,p);if(n=f[0],g(n))return f;e=f[1],h=n.$type}if(void 0!==h)return[n,e];if(null==r){if(i)throw new Error("`null` is not allowed in branch key positions.");n&&(r=n[s])}else e=n,n=e[r];return[n,e]}var s=t(36),u=t(43),a=t(39),c=t(33),p=t(46),h=t(42),f=t(44),l=t(120),d=t(13),v=t(50),y=t(88),b=t(95),m=t(96),g=t(102),w=t(86),x=t(143).iterateKeySet,_=t(92),S=t(115),E=t(109);e.exports=function(t,e){for(var n=t._root,o=n,i=n.expired,s=_(),u=t._path,c=n.cache,h=u.length?d(t,u).value:c,f=h[a]||c,l=c[p],v=-1,y=e.length;++v<y;){var b=e[v];r(b,0,c,f,h,s,i,o)}var g=c[p],w=n.onChange;m(w)&&l!==g&&w()}},{102:102,109:109,115:115,120:120,13:13,143:143,33:33,36:36,39:39,42:42,43:43,44:44,46:46,50:50,86:86,88:88,92:92,95:95,96:96}],49:[function(t,e,n){var r=t(36),o=t(39),i=t(34),s=t(45),u=t(38),a=t(41),c=t(108),p=t(115);e.exports=function(t,e,n,h,f,l){var d=n,v=f;"number"!=typeof v&&(v=.75);var y,b,m,g="number"==typeof l,w=h*v;for(b=e.pop();b;)m=b.$size||0,d-=m,g===!0?p(b,m,t,l):(y=b[o])&&c(b,y,b[r],t),b=e.pop();if(d>=h){var x=t[s];for(b=x;d>=w&&b;)x=x[a],m=b.$size||0,d-=m,g===!0&&p(b,m,t,l),b=x;t[s]=t[a]=b,null==b?t[i]=t[u]=void 0:b[u]=void 0}}},{108:108,115:115,34:34,36:36,38:38,39:39,41:41,45:45}],50:[function(t,e,n){var r=t(121),o=t(34),i=t(45),s=t(38),u=t(41),a=t(100);e.exports=function(t,e){if(a(e)&&e.$expires!==r){var n=t[o],c=t[i],p=e[s],h=e[u];e!==n&&(null!=p&&"object"==typeof p&&(p[u]=h),null!=h&&"object"==typeof h&&(h[s]=p),p=n,null!=n&&"object"==typeof n&&(n[u]=e),t[o]=t[s]=n=e,n[s]=p,n[u]=void 0),null!=c&&e!==c||(t[i]=t[u]=c=h||e)}return e}},{100:100,121:121,34:34,38:38,41:41,45:45}],51:[function(t,e,n){var r=t(34),o=t(45),i=t(38),s=t(41);e.exports=function(t,e){var n=t[r],u=t[o],a=e[i],c=e[s];null!=a&&"object"==typeof a&&(a[s]=c),null!=c&&"object"==typeof c&&(c[i]=a),e===n&&(t[r]=t[i]=a),e===u&&(t[o]=t[s]=c),e[i]=e[s]=void 0,n=u=a=c=void 0}},{34:34,38:38,41:41,45:45}],52:[function(t,e,n){function r(t,e){var n=!1;return function(){if(!n&&!t._disposed){n=!0,t._callbacks[e]=null,t._optimizedPaths[e]=[],t._requestedPaths[e]=[];var r=--t._count;0!==r||t.sent||(t._disposable.dispose(),t.requestQueue.removeRequest(t))}}}function o(t){for(var e=[],n=-1,r=0,o=t.length;o>r;++r)for(var i=t[r],s=0,u=i.length;u>s;++s)e[++n]=i[s];return e}var i=t(59),s=t(60),u=0,a=t(57).GetRequest,c=t(76),p=t(78),h=t(119),f=[],l=function(t,e){this.sent=!1,this.scheduled=!1,this.requestQueue=e,this.id=++u,this.type=a,this._scheduler=t,this._pathMap={},this._optimizedPaths=[],this._requestedPaths=[],this._callbacks=[],this._count=0,this._disposable=null,this._collapsed=null,this._disposed=!1};l.prototype={batch:function(t,e,n){var o=this,i=o._optimizedPaths,u=o._requestedPaths,a=o._callbacks,c=i.length;return i[c]=e,u[c]=t,a[c]=n,++o._count,o.scheduled||(o.scheduled=!0,o._disposable=o._scheduler.schedule(function(){s(o,i,function(t,e){if(o.requestQueue.removeRequest(o),o._disposed=!0,o._count){o._merge(u,t,e);for(var n=0,r=a.length;r>n;++n){var i=a[n];i&&i(t,e)}}})})),r(o,c)},add:function(t,e,n){var o,s,u=this,a=i(t,e,u._pathMap);a?(s=a[2],o=a[1]):(s=t,o=e);var c=!1,p=!1;if(o.length<e.length){c=!0;var h=u._callbacks.length;u._callbacks[h]=n,u._requestedPaths[h]=a[0],u._optimizedPaths[h]=[],++u._count,p=r(u,h)}return[c,s,o,p]},_merge:function(t,e,n){var r=this,i=r.requestQueue.model,s=i._root,u=s.errorSelector,a=s.comparator,l=i._path;i._path=f;var d=o(t);if(e){var v=e;v instanceof Error&&(v={message:v.message}),v.$type||(v={$type:h,value:v});var y=d.map(function(t){return{path:t,value:v}});p(i,y,null,u,a)}else c(i,[{paths:d,jsonGraph:n.jsonGraph}],null,u,a);i._path=l}},e.exports=l},{119:119,57:57,59:59,60:60,76:76,78:78}],53:[function(t,e,n){function r(){this.length=0,this.pending=!1,this.pathmaps=[],s.call(this,this._subscribe)}var o=t(159),i=o.Observer,s=o.Observable,u=o.Disposable,a=o.SerialDisposable,c=o.CompositeDisposable,p=t(9),h=t(143),f=h.iterateKeySet;r.create=function(t,e,n){var r=new this;return r.queue=t,r.model=e,r.index=n,r},r.prototype=Object.create(s.prototype),r.prototype.constructor=r,r.prototype.insertPath=function(t,e,n,r,o){var i=r||0,s=o||t.length-1,u=n||this.pathmaps[s+1]||(this.pathmaps[s+1]=Object.create(null));if(void 0===u||null===u)return!1;var a,c,p=t[i],h={};a=f(p,h);do{if(c=u[a],s>i){if(null==c){if(e)return!1;c=u[a]=Object.create(null)}if(this.insertPath(t,e,c,i+1,s)===!1)return!1}else u[a]=(c||0)+1,this.length+=1;h.done||(a=f(p,h))}while(!h.done);return!0},r.prototype.removePath=function(t,e,n,r){var o=n||0,i=r||t.length-1,s=e||this.pathmaps[i+1];if(void 0===s||null===s)return!0;var u,a,c=0,p=t[o],h={};u=f(p,h);do if(a=s[u],void 0!==a&&null!==a){if(i>o){c+=this.removePath(t,a,o+1,i);var l=void 0;for(l in a)break;void 0===l&&delete s[u]}else a=s[u]=(a||1)-1,0===a&&delete s[u],c+=1,this.length-=1;h.done||(u=f(p,h))}while(!h.done);return c},r.prototype.getSourceObserver=function(t){var e=this;return i.create(function(n){n.jsonGraph=n.jsonGraph||n.jsong||n.values||n.value,n.index=e.index,t.onNext(n)},function(e){t.onError(e)},function(){t.onCompleted()})},r.prototype._subscribe=function(t){var e=this,n=this.queue;e.pending=!0;var r=!1,o=new a,i=u.create(function(){r||(r=!0,n&&n._remove(e))}),s=new c(o,i);try{o.setDisposable(this.model._source[this.method](this.getSourceArgs()).subscribe(this.getSourceObserver(t)))}catch(h){throw new p(h)}return s},e.exports=r},{143:143,159:159,9:9}],54:[function(t,e,n){function r(t,e){this.total=0,this.model=t,this.requests=[],this.scheduler=e}var o=t(58),i=t(40),s=t(90),u=t(100),a=t(143);r.prototype.set=function(t){return t.paths=a.collapse(t.paths),o.create(this.model,t)},r.prototype._remove=function(t){var e=this.requests,n=e.indexOf(t);-1!==n&&e.splice(n,1)},r.prototype.distributePaths=function(t,e,n){var r,o,i=this.model,s=-1,u=t.length,a=-1,c=e.length,p=[];t:for(;++s<u;){var h=t[s];for(a=-1;++a<c;)if(o=e[a],o.insertPath(h,o.pending)){p[a]=o;continue t}r||(r=n.create(this,i,this.total++),e[a]=r,p[c++]=r),r.insertPath(h,!1)}var f=[],l=-1;for(a=-1;++a<c;)o=p[a],null!=o&&(f[++l]=o);return f},r.prototype.mergeJSONGraphs=function(t,e){var n=0,r=[],o=[],a=[],c=t.index,p=e.index;t.index=Math.max(c,p),r[-1]=t.jsonGraph||{},o[-1]=e.jsonGraph||{};t:for(;n>-1;){for(var h=r[n-1],f=o[n-1],l=a[n-1]||(a[n-1]=Object.keys(f));l.length>0;){var d=l.pop();if(d[0]!==i)if(h.hasOwnProperty(d)){var v=h[d],y=s(v),b=f[d],m=s(b);if(u(v)&&u(b)&&!y&&!m){r[n]=v,o[n]=b,n+=1;continue t}p>c&&(h[d]=b)}else h[d]=f[d]}n-=1}return t},e.exports=r},{100:100,143:143,40:40,58:58,90:90}],55:[function(t,e,n){function r(t,e){this.model=t,this.scheduler=e,this.requests=this._requests=[]}var o=t(54),i=t(56);r.prototype.get=i.prototype.get,r.prototype.removeRequest=i.prototype.removeRequest,r.prototype.set=o.prototype.set,r.prototype.call=o.prototype.call,e.exports=r},{54:54,56:56}],56:[function(t,e,n){function r(t,e){this.model=t,this.scheduler=e,this.requests=this._requests=[]}var o=t(57),i=t(52);r.prototype={setScheduler:function(t){this.scheduler=t},get:function(t,e,n){function r(){v||(--h,0===h&&n())}var s,u,a,c=this,p=[],h=0,f=c._requests,l=e,d=t,v=!1;for(s=0,u=f.length;u>s;++s)if(a=f[s],a.type===o.GetRequest){if(a.sent){var y=a.add(d,l,r);y[0]&&(d=y[1],l=y[2],p[p.length]=y[3],++h)}else a.batch(d,l,r),l=[],d=[],++h;if(!l.length)break}if(l.length){a=new i(c.scheduler,c),f[f.length]=a,++h;var b=a.batch(d,l,r);p[p.length]=b}return function(){if(!v&&0!==h){v=!0;for(var t=p.length,e=0;t>e;++e)p[e]()}}},removeRequest:function(t){for(var e=this._requests,n=e.length;--n>=0;)if(e[n].id===t.id){e.splice(n,1);break}}},e.exports=r},{52:52,57:57}],57:[function(t,e,n){e.exports={GetRequest:"GET"}},{}],58:[function(t,e,n){function r(){s.call(this)}var o=t(159),i=o.Observer,s=t(53),u=t(83),a=t(76),c=t(78),p=new Array(0);r.create=function(t,e){var n=new r;return n.model=t,n.jsonGraphEnvelope=e,n},r.prototype=Object.create(s.prototype),r.prototype.constructor=r,r.prototype.method="set",r.prototype.insertPath=function(){return!1},r.prototype.removePath=function(){return 0},r.prototype.getSourceArgs=function(){return this.jsonGraphEnvelope},r.prototype.getSourceObserver=function(t){var e=this.model,n=e._path,r=this.jsonGraphEnvelope.paths,o=e._root,h=o.errorSelector,f=o.comparator;return s.prototype.getSourceObserver.call(this,i.create(function(o){e._path=p;var i=a(e,[{paths:r,jsonGraph:o.jsonGraph}],null,h,f);o.paths=i[1],e._path=n,t.onNext(o)},function(o){e._path=p,c(e,u(r,function(t){return{path:t,value:o}}),null,h,f),e._path=n,t.onError(o)},function(){t.onCompleted()}))},e.exports=r},{159:159,53:53,76:76,78:78,83:83}],59:[function(t,e,n){var r=t(143).hasIntersection,o=t(84);e.exports=function(t,e,n){for(var i=[],s=[],u=[],a=-1,c=-1,p=!1,h=0,f=e.length;f>h;++h){var l=e[h],d=n[l.length];d&&r(d,l,0)?(!p&&h>0&&(s=o(t,0,h),i=o(e,0,h)),u[++a]=t[h],p=!0):p&&(i[++c]=l,s[c]=t[h])}return p?[u,i,s]:null}},{143:143,84:84}],60:[function(t,e,n){var r=t(143),o=r.toTree,i=r.toPaths;e.exports=function(t,e,n){if(0===t._count)return void t.requestQueue.removeRequest(t);t.sent=!0,t.scheduled=!1;for(var r=t._pathMap,s=Object.keys(e),u=0,a=s.length;a>u;++u)for(var c=e[u],p=0,h=c.length;h>p;++p){var f=c[p],l=f.length;if(r[l]){var d=r[l];d[d.length]=f}else r[l]=[f]}for(var v=Object.keys(r),y=0,b=v.length;b>y;++y){var m=v[y];r[m]=o(r[m])}var g,w=t._collasped=i(r);t.requestQueue.model._source.get(w).subscribe(function(t){g=t},function(t){n(t,g)},function(){n(null,g)})}},{143:143}],61:[function(t,e,n){function r(t){u.call(this,t||i)}function o(t){return s.Observable.defer(function(){return t})}function i(t){function e(t){function e(t,e){if(Boolean(e.invalidated))t.invalidations.push(t.localThisPath.concat(e.path));else{var n=e.path,r=e.value;Boolean(r)&&"object"==typeof r&&r.$type===f?t.references.push({path:i(n),value:e.value}):t.values.push({path:i(n),value:e.value})}return t}function n(t){var e=t.values.concat(t.references);return e.length>0?o(g.set.apply(g,e)._toJSONG()).map(function(e){return{results:t,envelope:e}}):u["return"]({results:t,envelope:{jsonGraph:{},paths:[]}})}function r(t){var e,n=t.envelope,r=t.results,c=r.values,p=r.references,h=r.invalidations,f=c.map(a).map(i),l=p.reduce(s,[]),d=b.map(i),v=l.concat(d);return e=v.length>0?o(m.get.apply(m,f.concat(v))._toJSONG()):u["return"](n),e.doAction(function(t){t.invalidated=h})}function s(t,e){var n=e.path;return t.push.apply(t,y.map(function(t){return n.concat(t)})),t}function a(t){return t.path}var c=t&&t.localFn;if("function"==typeof c){var p=t.model,h=p._path,l=c.apply(p,v).reduce(e,{values:[],references:[],invalidations:[],localThisPath:h}).flatMap(n).flatMap(r);return u["return"](l)}return u.empty()}function n(t){function e(t){var e=t.invalidated;return e&&e.length&&m.invalidate.apply(m,e),t}return t&&"object"==typeof t?s.Observable.defer(function(){
3458 var e;try{e=t.call(x,v,y,b)}catch(n){e=u["throw"](new p(n))}return e}).map(e):u.empty()}function r(t){return o(g.set(t)).reduce(function(t){return t},null).map(function(){return{invalidated:t.invalidated,paths:t.paths.map(function(t){return t.slice(w.length)})}})}function i(t){return _.concat(t)}var c=this.args,l=this.model,d=h.fromPath(c[0]),v=c[1]||[],y=(c[2]||[]).map(h.fromPath),b=(c[3]||[]).map(h.fromPath),m=l._clone({_path:[]}),g=m.withoutDataSource(),w=l._path,x=w.concat(d),_=x.slice(0,-1),S=o(l.withoutDataSource().get(d)).map(function(t){for(var e=t.json,n=-1,r=d.length;e&&++n<r;)e=e[d[n]];var o=m._derefSync(_).boxValues();return{model:o,localFn:e}}).flatMap(e).defaultIfEmpty(n(l._source)).mergeAll().flatMap(r),E=new a;return E.add(S.subscribe(function(e){var n=e.paths,r=e.invalidated,i=l.get.apply(l,n);"AsJSONG"===t.outputFormat&&(i=o(i._toJSONG()).doAction(function(t){t.invalidated=r})),E.add(i.subscribe(t))},function(e){t.onError(e)})),E}var s=t(159)&&t(158),u=s.Observable,a=s.CompositeDisposable,c=t(64),p=t(9),h=t(134),f=t(120);r.create=c.create,r.prototype=Object.create(u.prototype),r.prototype.constructor=r,r.prototype.invokeSourceRequest=function(t){return this},r.prototype.ensureCollect=function(t){return this},r.prototype.initialize=function(){return this},e.exports=r},{120:120,134:134,158:158,159:159,64:64,9:9}],62:[function(t,e,n){function r(t){i.call(this,t)}var o=t(159),i=o.Observable,s=t(64),u=t(134),a=t(88),c=t(49),p=t(81),h=t(46),f=Array.isArray,l=t(101),d=t(98),v=t(99);r.create=s.create,r.prototype=Object.create(i.prototype),r.prototype.constructor=r,r.prototype.subscribeCount=0,r.prototype.subscribeLimit=10,r.prototype.initialize=function(){for(var t,e,n=this.model,r=this.outputFormat||"AsPathMap",o=this.isProgressive,i=[{}],s=[],a=this.args,c=-1,h=a.length;++c<h;){var y,b=a[c];f(b)||"string"==typeof b?(b=u.fromPath(b),y="PathValues"):l(b)?(b.path=u.fromPath(b.path),y="PathValues"):v(b)?y="JSONGs":d(b)&&(y="PathMaps"),e!==y&&(e=y,t={inputType:y,arguments:[]},s.push(t),t.values=i),t.arguments.push(b)}return this.boundPath=p(n._path),this.groups=s,this.outputFormat=r,this.isProgressive=o,this.isCompleted=!1,this.isMaster=null==n._source,this.values=i,this},r.prototype.invokeSourceRequest=function(t){return this},r.prototype.ensureCollect=function(t){var e=this["finally"](function(){var e=t._root,n=e.cache;e.collectionScheduler.schedule(function(){c(e,e.expired,a(n),t._maxSize,t._collectRatio,n[h])})});return new this.constructor(function(t){return e.subscribe(t)})},e.exports=r},{101:101,134:134,159:159,46:46,49:49,64:64,81:81,88:88,98:98,99:99}],63:[function(t,e,n){function r(t){u.call(this,t||o)}function o(t){for(var e=this.model,n=this.method,r=this.groups,o=-1,i=r.length;++o<i;){var u=r[o],a=u.inputType,c=u.arguments;if(c.length>0){var p="_"+n+a+"AsJSON",h=e[p];h(e,c)}}return t.onCompleted(),s.empty}var i=t(159),s=i.Disposable,u=t(62);r.create=u.create,r.prototype=Object.create(u.prototype),r.prototype.method="invalidate",r.prototype.constructor=r,e.exports=r},{159:159,62:62}],64:[function(t,e,n){function r(t){this._subscribe=t}function o(t){var e=this.model,n=new this.type;return n.model=e,n.args=this.args,n.outputFormat=t.outputFormat||"AsPathMap",n.isProgressive=t.isProgressive||!1,n.subscribeCount=0,n.subscribeLimit=t.retryLimit||10,n.initialize().invokeSourceRequest(e).ensureCollect(e).subscribe(t)}var i=t(32),s=t(159)&&t(158),u=s.Observable,a=t(84),c=t(105),p={outputFormat:{value:"AsJSONG"}},h={isProgressive:{value:!0}};r.create=function(t,e){var n=new r(o);return n.args=e,n.type=this,n.model=t,n},r.prototype=Object.create(u.prototype),r.prototype.constructor=r,r.prototype._mixin=function(){var t=this,e=a(arguments);return new t.constructor(function(n){return t.subscribe(e.reduce(function(t,e){return Object.create(t,e)},n))})},r.prototype._toJSONG=function(){return this._mixin(p)},r.prototype.progressively=function(){return this._mixin(h)},r.prototype.subscribe=function(t,e,n){var r=t;r&&"object"==typeof r||(r={onNext:t||c,onError:e||c,onCompleted:n||c});var o=this._subscribe(r);switch(typeof o){case"function":return{dispose:o};case"object":return o||{dispose:c};default:return{dispose:c}}},r.prototype.then=function(t,e){var n=this;return new i.Promise(function(t,e){var r,o=!1;n.toArray().subscribe(function(t){r=t.length<=1?t[0]:t},function(t){o=!0,e(t)},function(){o===!1&&t(r)})}).then(t,e)},e.exports=r},{105:105,158:158,159:159,32:32,84:84}],65:[function(t,e,n){function r(t){l.call(this,t||o)}function o(t){return this.isCompleted?s.call(this,t):i.call(this,t)}function i(t){if(this.subscribeCount++>this.subscribeLimit)return t.onError("Loop kill switch thrown."),h.empty;for(var e=[],n=[],r=this.model,o=this.isMaster,i=r._root,c=this.outputFormat,p=i.errorSelector,f=this.method,l=this.groups,d=-1,y=l.length;++d<y;){var b=l[d],m=b.inputType,g=b.arguments;if(g.length>0){var w="_"+f+m+c,x=r[w],_=x(r,g,null,p);n.push.apply(n,_[1]),"PathValues"===m?e.push.apply(e,g.map(u)):"JSONGs"===m?e.push.apply(e,v(g,a)):e.push.apply(e,_[0])}}return this.requestedPaths=e,o?(this.isCompleted=!0,s.call(this,t)):void t.onError({method:f,optimizedPaths:n,invokeSourceRequest:!0})}function s(t){var e=new f(this.model,this.requestedPaths);return"AsJSONG"===this.outputFormat&&(e=e._toJSONG()),this.isProgressive&&(e=e.progressively()),e.subscribe(t)}function u(t){return t.path}function a(t){return t.paths}var c=t(159),p=c.Observable,h=c.Disposable,f=t(67),l=t(62),d=t(9),v=t(82),y=new Array(0);r.create=l.create,r.prototype=Object.create(l.prototype),r.prototype.method="set",r.prototype.constructor=r,r.prototype.invokeSourceRequest=function(t){var e=this,n=this["catch"](function(r){var o;if(r&&r.invokeSourceRequest===!0){var i={},s=t._path,u=r.optimizedPaths;t._path=y,t._getPathValuesAsJSONG(t._materialize().withoutDataSource(),u,[i]),t._path=s,o=t._request.set(i)["do"](function(t){e.isCompleted=u.length===t.paths.length},function(){e.isCompleted=!0}).materialize().flatMap(function(t){if("C"===t.kind)return p.empty();if("E"===t.kind){var e=t.exception;if(d.is(e))return p["throw"](t.exception)}return n})}else o=p["throw"](r);return o});return new this.constructor(function(t){return n.subscribe(t)})},e.exports=r},{159:159,62:62,67:67,82:82,9:9}],66:[function(t,e,n){var r=function(t){this.disposed=!1,this.currentDisposable=t};r.prototype={dispose:function(){if(!this.disposed&&this.currentDisposable){this.disposed=!0;var t=this.currentDisposable;t.dispose?t.dispose():t()}}},e.exports=r},{}],67:[function(t,e,n){var r=t(64),o=t(68),i=t(69),s={dispose:function(){}},u=t(159).Observable,a=e.exports=function(t,e,n,r){this.model=t,this.currentRemainingPaths=e,this.isJSONGraph=n||!1,this.isProgressive=r||!1};a.prototype=Object.create(u.prototype),a.prototype.subscribe=r.prototype.subscribe,a.prototype.then=r.prototype.then,a.prototype._toJSONG=function(){return new a(this.model,this.currentRemainingPaths,!0,this.isProgressive)},a.prototype.progressively=function(){return new a(this.model,this.currentRemainingPaths,this.isJSONGraph,!0)},a.prototype._subscribe=function(t){var e=[{}],n=[],r=t.isJSONG=this.isJSONGraph,u=this.isProgressive,a=o(this.model,this.currentRemainingPaths,t,u,r,e,n);return a?i(this,this.model,a,t,e,n,1):s}},{159:159,64:64,68:68,69:69}],68:[function(t,e,n){var r=t(19),o=r.getWithPathsAsJSONGraph,i=r.getWithPathsAsPathMap;e.exports=function(t,e,n,r,s,u,a){var c;if(c=s?o(t,e,u):i(t,e,u),c.criticalError)return n.onError(c.criticalError),null;var p=c.hasValue,h=!c.requestedMissingPaths||!t._source,f=u[0].json||u[0].jsonGraph;if(c.errors)for(var l=c.errors,d=a.length,v=0,y=l.length;y>v;++v,++d)a[d]=l[v];if(p&&r||f&&h)try{++t._root.syncRefCount,n.onNext(u[0])}catch(b){throw b}finally{--t._root.syncRefCount}return h?(a.length?n.onError(a):n.onCompleted(),null):c}},{19:19}],69:[function(t,e,n){var r=t(68),o=t(10),i=t(30).fastCat,s=t(49),u=t(88),a=t(66),c=t(46);e.exports=function p(t,e,n,h,f,l,d){if(10===d)throw new o;var v=e._request,y=n.requestedMissingPaths,b=n.optimizedMissingPaths,m=new a,g=[],w=e._path;if(w.length)for(var x=0,_=y.length;_>x;++x)g[x]=i(w,y[x]);else g=y;var S=v.get(g,b,function(){var n=r(e,y,h,t.isProgressive,t.isJSONGraph,f,l);if(n)m.currentDisposable=p(t,e,n,h,f,l,d+1);else{var o=e._root,i=o.cache,a=i[c];s(o,o.expired,u(i),e._maxSize,e._collectRatio,a)}});return m.currentDisposable=S,m}},{10:10,30:30,46:46,49:49,66:66,68:68,88:88}],70:[function(t,e,n){var r=t(67);e.exports=function(t){return new r(this,t)}},{67:67}],71:[function(t,e,n){var r=t(134),o=t(64),i=t(72),s=t(116),u=t(67);e.exports=function(){var t=s(arguments,i,"get");if(t!==!0)return new o(function(e){e.onError(t)});var e=r.fromPathsOrPathValues(arguments);return new u(this,e)}},{116:116,134:134,64:64,67:67,72:72}],72:[function(t,e,n){e.exports={path:!0,pathSyntax:!0}},{}],73:[function(t,e,n){function r(){}var o=t(123),i=t(159),s=i.Disposable;r.prototype.schedule=function(t){return o(t),s.empty},r.prototype.scheduleWithState=function(t,e){var n=this;return o(function(){e(n,t)}),s.empty},e.exports=r},{123:123,159:159}],74:[function(t,e,n){function r(){}var o=t(159),i=o.Disposable;r.prototype.schedule=function(t){return t(),i.empty},r.prototype.scheduleWithState=function(t,e){return e(this,t),i.empty},e.exports=r},{159:159}],75:[function(t,e,n){function r(t){this.delay=t}var o=t(159),i=o.Disposable;r.prototype.schedule=function(t){var e=setTimeout(t,this.delay);return i.create(function(){void 0!==e&&(clearTimeout(e),e=void 0)})},r.prototype.scheduleWithState=function(t,e){var n=this,r=setTimeout(function(){e(n,t)},this.delay);return i.create(function(){void 0!==r&&(clearTimeout(r),r=void 0)})},e.exports=r},{159:159}],76:[function(t,e,n){function r(t,e,n,o,s,u,a,c,p,h,f,d,v,y,b,g,w){for(var x={},_=e<t.length-1,S=t[e],E=m(S,x),C=d.index;;){f.depth=e;var A=i(n,o,s,u,a,c,E,_,!1,f,d,v,y,b,g,w);f[e]=E,f.index=e,d[d.index++]=E;var N=A[0],k=A[1];if(N&&(_?r(t,e+1,n,k,N,u,A[3],A[2],p,h,f,d,v,y,b,g,w):(l(b,N),p.push(f.slice(0,f.index+1)),h.push(d.slice(0,d.index)))),E=m(S,x),x.done)break;d.index=C}}function o(t,e,n,r,o,s,c,f,v,m,g){var w=e.value;if(s.splice(0,s.length),s.push.apply(s,w),d(e))return s.index=w.length,b(e,f,v),[void 0,t,r,n];l(v,e);var x=0,_=e,S=w.length-1,E=e=t,C=r=n;do{var A=w[x],N=S>x,k=i(t,E,e,n,C,r,A,N,!0,o,s,c,f,v,m,g);if(e=k[0],y(e))return s.index=x,k;E=k[1],r=k[2],C=k[3]}while(x++<S);if(s.index=x,_[a]!==e){var O=e[h]||0;e[h]=O+1,e[u+O]=_,_[a]=e,_[p]=O}return[e,E,r,C]}function i(t,e,n,r,i,u,a,c,p,h,l,d,v,b,m,g){for(var x=n.$type;x===f;){var _=o(t,n,r,u,h,l,d,v,b,m,g);if(n=_[0],y(n))return _;e=_[1],u=_[2],i=_[3],x=n.$type}if(void 0!==x)return[n,e,u,i];if(null==a){if(c)throw new Error("`null` is not allowed in branch key positions.");n&&(a=n[s])}else e=n,i=u,n=e[a],u=i&&i[a];return n=w(e,n,u,a,h,l,d,v,b,m,g),[n,e,u,i]}var s=t(36),u=t(43),a=t(33),c=t(46),p=t(42),h=t(44),f=t(120),l=t(50),d=t(94),v=t(96),y=t(102),b=t(86),m=t(143).iterateKeySet,g=t(92),w=t(103);e.exports=function(t,e,n,o,i){for(var s=t._root,u=s,a=s.expired,p=g(),h=s.cache,f=h[c],l=[],d=[],y=[],b=[],m=-1,w=e.length;++m<w;)for(var x=e[m],_=x.paths,S=x.jsonGraph,E=-1,C=_.length;++E<C;){var A=_[E];d.index=0,r(A,0,h,h,h,S,S,S,y,b,l,d,p,a,u,i,o)}var N=h[c],k=s.onChange;return v(k)&&f!==N&&k(),[y,b]}},{102:102,103:103,120:120,143:143,33:33,36:36,42:42,43:43,44:44,46:46,50:50,86:86,92:92,94:94,96:96}],77:[function(t,e,n){function r(t,e,n,o,u,a,c,p,h,f,l,d,v,y){var b=s(t);if(b&&b.length)for(var g=0,x=b.length,_=h.index;;){var S=b[g],E=t[S],C=w(E)&&!E.$type;p.depth=e;var A=i(n,o,u,S,E,C,!1,p,h,f,l,d,v,y);p[e]=S,p.index=e,h[h.index++]=S;var N=A[0],k=A[1];if(N&&(C?r(E,e+1,n,k,N,a,c,p,h,f,l,d,v,y):(m(d,N),a.push(p.slice(0,p.index+1)),c.push(h.slice(0,h.index)))),++g>=x)break;h.index=_}}function o(t,e,n,r,o,s,u,c,f,v){var y=n.value;if(o.splice(0,o.length),o.push.apply(o,y),x(n))return o.index=y.length,E(n,u,c),[void 0,e];m(c,n);var b=n,g=e;if(n=n[h],null!=n)g=n[p]||e,o.index=y.length;else{var w=0,_=y.length-1;g=n=e;do{var C=y[w],A=_>w,N=i(e,g,n,C,t,A,!0,r,o,s,u,c,f,v);if(n=N[0],S(n))return o.index=w,N;g=N[1]}while(w++<_);if(o.index=w,b[h]!==n){var k=n[d]||0;n[d]=k+1,n[a+k]=b,b[h]=n,b[l]=k}}return[n,g]}function i(t,e,n,r,i,s,a,c,p,h,f,l,d,y){for(var b=n.$type;b===v;){var m=o(i,t,n,c,p,h,f,l,d,y);if(n=m[0],S(n))return m;e=m[1],b=n&&n.$type}if(void 0!==b)return[n,e];if(null==r){if(s)throw new Error("`null` is not allowed in branch key positions.");n&&(r=n[u])}else e=n,n=e[r];return n=A(e,n,r,i,s,a,c,p,h,f,l,d,y),[n,e]}function s(t){if(w(t)&&!t.$type){var e=[],n=0;b(t)&&(e[n++]="length");for(var r in t)r[0]!==c&&"$"!==r[0]&&g(t,r)&&(e[n++]=r);return e}}var u=t(36),a=t(43),c=t(40),p=t(39),h=t(33),f=t(46),l=t(42),d=t(44),v=t(120),y=t(13),b=Array.isArray,m=t(50),g=t(91),w=t(100),x=t(95),_=t(96),S=t(102),E=t(86),C=t(92),A=t(104);e.exports=function(t,e,n,o,i){for(var s=t._root,u=s,a=s.expired,c=C(),h=t._path,l=s.cache,d=h.length?y(t,h).value:l,v=d[p]||l,b=l[f],m=[],g=[],w=[],x=h.length,S=-1,E=e.length;++S<E;){var A=e[S],N=h.slice(0);N.index=x,r(A.json,0,l,v,d,g,w,m,N,c,a,u,i,o)}var k=l[f],O=s.onChange;return _(O)&&b!==k&&O(),[g,w]}},{100:100,102:102,104:104,120:120,13:13,33:33,36:36,39:39,40:40,42:42,43:43,44:44,46:46,50:50,86:86,91:91,92:92,95:95,96:96}],78:[function(t,e,n){function r(t,e,n,o,s,u,a,c,p,h,f,l,d,y,b){for(var m={},g=n<e.length-1,x=e[n],_=w(x,m),S=h.index;;){p.depth=n;var E=i(o,s,u,_,t,g,!1,p,h,f,l,d,y,b);p[n]=_,p.index=n,h[h.index++]=_;var C=E[0],A=E[1];if(C&&(g?r(t,e,n+1,o,A,C,a,c,p,h,f,l,d,y,b):(v(d,C),a.push(p.slice(0,p.index+1)),c.push(h.slice(0,h.index)))),_=w(x,m),m.done)break;h.index=S}}function o(t,e,n,r,o,s,p,l,d,b){var w=n.value;if(o.splice(0,o.length),o.push.apply(o,w),y(n))return o.index=w.length,g(n,p,l),[void 0,e];v(l,n);var x=n,_=e;if(n=n[c],null!=n)_=n[a]||e,o.index=w.length;else{var S=0,E=w.length-1;_=n=e;do{var C=w[S],A=E>S,N=i(e,_,n,C,t,A,!0,r,o,s,p,l,d,b);if(n=N[0],m(n))return o.index=S,N;_=N[1]}while(S++<E);if(o.index=S,x[c]!==n){var k=n[f]||0;n[f]=k+1,n[u+k]=x,x[c]=n,x[h]=k}}return[n,_]}function i(t,e,n,r,i,u,a,c,p,h,f,d,v,y){for(var b=n.$type;b===l;){var g=o(i,t,n,c,p,h,f,d,v,y);if(n=g[0],m(n))return g;e=g[1],b=n.$type}if(void 0!==b)return[n,e];if(null==r){if(u)throw new Error("`null` is not allowed in branch key positions.");n&&(r=n[s])}else e=n,n=e[r];return n=_(e,n,r,i,u,a,c,p,h,f,d,v,y),[n,e]}var s=t(36),u=t(43),a=t(39),c=t(33),p=t(46),h=t(42),f=t(44),l=t(120),d=t(13),v=t(50),y=t(95),b=t(96),m=t(102),g=t(86),w=t(143).iterateKeySet,x=t(92),_=t(104);e.exports=function(t,e,n,o,i){for(var s=t._root,u=s,c=s.expired,h=x(),f=t._path,l=s.cache,v=f.length?d(t,f).value:l,y=v[a]||l,m=l[p],g=[],w=[],_=[],S=f.length,E=-1,C=e.length;++E<C;){var A=e[E],N=A.path,k=A.value,O=f.slice(0);O.index=S,r(k,N,0,l,y,v,w,_,g,O,h,c,u,i,o)}var P=l[p],j=s.onChange;return b(j)&&m!==P&&j(),[w,_]}},{102:102,104:104,120:120,13:13,143:143,33:33,36:36,39:39,42:42,43:43,44:44,46:46,50:50,86:86,92:92,95:95,96:96}],79:[function(t,e,n){var r=t(130),o=t(64),i=t(101);e.exports=function(t,e){for(var n=i(t)?t:r.pathValue(t,e),s=0,u=n.path,a=u.length;++s<a;)if("object"==typeof u[s])return new o(function(t){t.onError(new Error("Paths must be simple paths"))});var c=this;return new o(function(t){return c._set(n).subscribe(function(e){for(var n=e.json,r=-1,o=u.length;n&&++r<o;)n=n[u[r]];t.onNext(n)},function(e){t.onError(e)},function(){t.onCompleted()})})}},{101:101,130:130,64:64}],80:[function(t,e,n){var r=t(134),o=t(101),i=t(78);e.exports=function(t,e,n,s){var u=r.fromPath(t),a=e,c=n,p=s;if(o(u)?(p=c,c=a,a=u):a={path:u,value:a},o(a)===!1)throw new Error("Model#setValueSync must be called with an Array path.");return"function"!=typeof c&&(c=this._root._errorSelector),"function"!=typeof p&&(p=this._root._comparator),this._syncCheck("setValueSync")?(i(this,[a]),this._getValueSync(this,a.path).value):void 0}},{101:101,134:134,78:78}],81:[function(t,e,n){e.exports=function(t){if(!t)return t;for(var e=-1,n=t.length,r=[];++e<n;)r[e]=t[e];return r}},{}],82:[function(t,e,n){e.exports=function(t,e){for(var n=-1,r=-1,o=t.length,i=[];++r<o;)for(var s=e(t[r],r,t),u=-1,a=s.length;++u<a;)i[++n]=s[u];return i}},{}],83:[function(t,e,n){e.exports=function(t,e){for(var n=-1,r=t.length,o=new Array(r);++n<r;)o[n]=e(t[n],n,t);return o}},{}],84:[function(t,e,n){e.exports=function(t,e,n){var r=e||0,o=-1,i=t.length-r;0>i&&(i=0),n>0&&i>n&&(i=n);for(var s=new Array(i);++o<i;)s[o]=t[o+r];return s}},{}],85:[function(t,e,n){var r=t(40),o=t(91),i=Array.isArray,s=t(100);e.exports=function(t){var e=t;if(s(e)){e=i(t)?[]:{};var n=t;for(var u in n)u[0]!==r&&o(n,u)&&(e[u]=n[u])}return e}},{100:100,40:40,91:91}],86:[function(t,e,n){var r=t(51),o=t(35);e.exports=function(t,e,n){return t[o]||(t[o]=!0,e.push(t),r(n,t)),t}},{35:35,51:51}],87:[function(t,e,n){var r=t(100);e.exports=function(t){return r(t)&&t.$expires||void 0}},{100:100}],88:[function(t,e,n){var r=t(100);e.exports=function(t){return r(t)&&t.$size||0}},{100:100}],89:[function(t,e,n){var r=t(100);e.exports=function(t){return r(t)&&t.$timestamp||void 0}},{100:100}],90:[function(t,e,n){var r=t(100);e.exports=function(t,e){var n=r(t)&&t.$type||void 0;return e&&n?"branch":n}},{100:100}],91:[function(t,e,n){var r=t(100),o=Object.prototype.hasOwnProperty;e.exports=function(t,e){return r(t)&&o.call(t,e)}},{100:100}],92:[function(t,e,n){var r=1;e.exports=function(){return r++}},{}],93:[function(t,e,n){var r=t(36),o=t(39),i=t(46);e.exports=function(t,e,n,s){return t[r]=n,t[o]=e,t[i]=s,e[n]=t,t}},{36:36,39:39,46:46}],94:[function(t,e,n){var r=t(106),o=t(122),i=t(121);e.exports=function(t){var e=t.$expires;return null!=e&&e!==i&&e!==o&&e<r()}},{106:106,121:121,122:122}],95:[function(t,e,n){var r=t(106),o=t(122),i=t(121);e.exports=function(t){var e=t.$expires;return null!=e&&e!==i&&(e===o||e<r())}},{106:106,121:121,122:122}],96:[function(t,e,n){var r="function";e.exports=function(t){return Boolean(t)&&typeof t===r}},{}],97:[function(t,e,n){var r=t(40);e.exports=function(t){return"$size"===t||t&&t.charAt(0)===r}},{40:40}],98:[function(t,e,n){var r=t(100);e.exports=function(t){return r(t)&&"json"in t}},{100:100}],99:[function(t,e,n){var r=Array.isArray,o=t(100);e.exports=function(t){return o(t)&&r(t.paths)&&(o(t.jsonGraph)||o(t.jsong)||o(t.json)||o(t.values)||o(t.value))}},{100:100}],100:[function(t,e,n){var r="object";e.exports=function(t){return null!==t&&typeof t===r}},{}],101:[function(t,e,n){var r=Array.isArray,o=t(100);e.exports=function(t){return o(t)&&(r(t.path)||"string"==typeof t.path)}},{100:100}],102:[function(t,e,n){var r="object";e.exports=function(t){return null==t||typeof t!==r}},{}],103:[function(t,e,n){var r=t(36),o=t(39),i=t(120),s=t(119),u=t(88),a=t(89),c=t(100),p=t(95),h=t(96),f=t(50),l=t(117),d=t(93),v=t(86),y=t(110),b=t(115),m=t(107);e.exports=function(t,e,n,g,w,x,_,S,E,C,A){var N,k,O,P,j,D,q;if(e===n){if(null===n)return e=l(n,void 0,n),t=b(t,-e.$size,E,_),e=d(e,t,g),f(E,e),e;if(void 0===n)return n;if(P=c(e),P&&(k=e.$type,null==k))return null==e[o]&&(e[r]=g,e[o]=t),e}else P=c(e),P&&(k=e.$type);if(k!==i){if(j=c(n),j&&(O=n.$type),P&&!k&&(null==n||j&&!O))return e}else{if(null==n)return p(e)?void v(e,S,E):e;if(j=c(n),j&&(O=n.$type,O===i))if(e===n){if(null!=e[o])return e}else if(D=e.$timestamp,q=n.$timestamp,!p(e)&&!p(n)&&D>q)return}if(k&&j&&!O)return d(y(e,n,t,g,E),t,g);if(O||!j){if(O===s&&h(A)&&(n=A(m(w,g),n)),O&&e===n)null==e[o]&&(e=l(e,k,e.value),t=b(t,-e.$size,E,_),e=d(e,t,g,_));else{var R=!0;!k&&P||(R=a(n)<a(e)==!1,(k||O)&&h(C)&&(R=!C(e,n,x.slice(0,x.index)))),R&&(n=l(n,O,O?n.value:n),N=u(e)-u(n),e=y(e,n,t,g,E),t=b(t,N,E,_),e=d(e,t,g,_))}p(e)?v(e,S,E):f(E,e)}else null==e&&(e=d(n,t,g));return e}},{100:100,107:107,110:110,115:115,117:117,119:119,120:120,36:36,39:39,50:50,86:86,88:88,89:89,93:93,95:95,96:96}],104:[function(t,e,n){var r=t(120),o=t(119),i=t(90),s=t(88),u=t(89),a=t(95),c=t(102),p=t(96),h=t(117),f=t(86),l=t(93),d=t(110),v=t(115),y=t(114),b=t(107);e.exports=function(t,e,n,m,g,w,x,_,S,E,C,A,N){var k=i(e,w);if(g||w)k&&a(e)&&(k="expired",f(e,E,C)),(k&&k!==r||c(e))&&(e=d(e,{},t,n,C),e=l(e,t,n,S),e=y(e,S));else{var O=m,P=i(O),j=u(O)<u(e)==!1;if((k||P)&&p(A)&&(j=!A(e,O,_.slice(0,_.index))),j){P===o&&p(N)&&(O=N(b(x,n),O)),O=h(O,P,P?O.value:O);var D=s(e)-s(O);e=d(e,O,t,n,C),t=v(t,D,C,S),e=l(e,t,n,S)}}return e}},{102:102,107:107,110:110,114:114,115:115,117:117,119:119,120:120,86:86,88:88,89:89,90:90,93:93,95:95,96:96}],105:[function(t,e,n){e.exports=function(){}},{}],106:[function(t,e,n){e.exports=Date.now},{}],107:[function(t,e,n){e.exports=function(t,e){var n=t.slice(0,t.depth);return n[n.length]=e,n}},{}],108:[function(t,e,n){var r=t(120),o=t(39),i=t(51),s=t(100),u=t(112),a=t(113);e.exports=function(t,e,n,c){if(s(t)){var p=t.$type;return Boolean(p)&&(p===r&&a(t),i(c,t)),u(t),e[n]=t[o]=void 0,!0}return!1}},{100:100,112:112,113:113,120:120,39:39,51:51}],109:[function(t,e,n){var r=t(91),o=t(40),i=t(108);e.exports=function s(t,e,n,u){if(i(t,e,n,u)){if(null==t.$type)for(var a in t)a[0]!==o&&"$"!==a[0]&&r(t,a)&&s(t[a],t,a,u);return!0}return!1}},{108:108,40:40,91:91}],110:[function(t,e,n){var r=t(100),o=t(111),i=t(109);e.exports=function(t,e,n,s,u){return t===e?t:(r(t)&&(o(t,e),i(t,n,s,u)),n[s]=e,e)}},{100:100,109:109,111:111}],111:[function(t,e,n){var r=t(43),o=t(33),i=t(44);e.exports=function(t,e){for(var n=t[i]||0,s=e[i]||0,u=-1;++u<n;){var a=t[r+u];void 0!==a&&(a[o]=e,e[r+(s+u)]=a,t[r+u]=void 0)}return e[i]=n+s,t[i]=void 0,e}},{33:33,43:43,44:44}],112:[function(t,e,n){var r=t(43),o=t(33),i=t(42),s=t(44);e.exports=function(t){for(var e=-1,n=t[s]||0;++e<n;){var u=t[r+e];null!=u&&(u[o]=u[i]=t[r+e]=void 0)}return t[s]=void 0,t}},{33:33,42:42,43:43,44:44}],113:[function(t,e,n){var r=t(43),o=t(33),i=t(42),s=t(44);e.exports=function(t){var e=t[o];if(e){for(var n=(t[i]||0)-1,u=(e[s]||0)-1;++n<=u;)e[r+n]=e[r+(n+1)];e[s]=u,t[i]=t[o]=e=void 0}return t}},{33:33,42:42,43:43,44:44}],114:[function(t,e,n){var r=t(43),o=t(39),i=t(46),s=t(44);e.exports=function(t,e){var n=[t],u=0;do{var a=n[u--];if(a&&a[i]!==e){a[i]=e,n[u++]=a[o];for(var c=-1,p=a[s]||0;++c<p;)n[u++]=a[r+c]}}while(u>-1);return t}},{39:39,43:43,44:44,46:46}],115:[function(t,e,n){var r=t(36),o=t(46),i=t(39),s=t(108),u=t(114);e.exports=function(t,e,n,a){var c=t;do{var p=c[i],h=c.$size=(c.$size||0)-e;0>=h&&null!=p?s(c,p,c[r],n):c[o]!==a&&u(c,a),c=p}while(c);return t}},{108:108,114:114,36:36,39:39,46:46}],116:[function(t,e,n){var r=Array.isArray,o=t(101),i=t(99),s=t(98),u=t(134);e.exports=function(t,e,n){for(var a=0,c=t.length;c>a;++a){var p=t[a],h=!1;if(r(p)&&e.path?h=!0:"string"==typeof p&&e.pathSyntax?h=!0:o(p)&&e.pathValue?(p.path=u.fromPath(p.path),h=!0):i(p)&&e.jsonGraph?h=!0:s(p)&&e.json?h=!0:"function"==typeof p&&a+1===c&&e.selector&&(h=!0),!h)return new Error("Unrecognized argument "+typeof p+" ["+String(p)+"] to Model#"+n)}return!0}},{101:101,134:134,98:98,99:99}],117:[function(t,e,n){var r=t(130),o=r.atom,i=t(106),s=t(122),u=t(37),a=50,c=t(85),p=Array.isArray,h=t(88),f=t(87);e.exports=function(t,e,n){var r=0,l=t,d=e;if(d?(l=c(l),r=h(l),l.$type=d):(l=o(n),d=l.$type,l[u]=!0),null==n)r=a+1;else if(null==r||0>=r)switch(typeof n){case"object":r=p(n)?a+n.length:a+1;break;case"string":r=a+n.length;break;default:r=a+1}var v=f(l);return"number"==typeof v&&s>v&&(l.$expires=i()+-1*v),l.$size=r,l}},{106:106,122:122,130:130,37:37,85:85,87:87,88:88}],118:[function(t,e,n){e.exports="atom"},{}],119:[function(t,e,n){e.exports="error"},{}],120:[function(t,e,n){e.exports="ref"},{}],121:[function(t,e,n){e.exports=1},{}],122:[function(t,e,n){e.exports=0},{}],123:[function(t,e,n){"use strict";function r(){if(a.length)throw a.shift()}function o(t){var e;e=u.length?u.pop():new i,e.task=t,s(e)}function i(){this.task=null}var s=t(124),u=[],a=[],c=s.makeRequestCallFromTimer(r);e.exports=o,i.prototype.call=function(){try{this.task.call()}catch(t){o.onerror?o.onerror(t):(a.push(t),c())}finally{this.task=null,u[u.length]=this}}},{124:124}],124:[function(t,e,n){(function(t){"use strict";function n(t){u.length||(s(),a=!0),u[u.length]=t}function r(){for(;c<u.length;){var t=c;if(c+=1,u[t].call(),c>p){for(var e=0,n=u.length-c;n>e;e++)u[e]=u[e+c];u.length-=c,c=0}}u.length=0,c=0,a=!1}function o(t){var e=1,n=new h(t),r=document.createTextNode("");return n.observe(r,{characterData:!0}),function(){e=-e,r.data=e}}function i(t){return function(){function e(){clearTimeout(n),clearInterval(r),t()}var n=setTimeout(e,0),r=setInterval(e,50)}}e.exports=n;var s,u=[],a=!1,c=0,p=1024,h=t.MutationObserver||t.WebKitMutationObserver;s="function"==typeof h?o(r):i(r),n.requestFlush=s,n.makeRequestCallFromTimer=i}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],125:[function(t,e,n){"use strict";function r(t,e){var n;for(n in e)t[n]=e[n];return t}function o(t,e){if(this._jsongUrl=t,"number"==typeof e){var n={timeout:e};e=n}this._config=r({timeout:15e3,headers:{}},e||{})}var i=t(129),s=t(126);Array.isArray;o.prototype={constructor:o,buildQueryObject:s,get:function(t){var e="GET",n=this.buildQueryObject(this._jsongUrl,e,{paths:t,method:"get"}),o=r(n,this._config),s=this;return i(e,o,s)},set:function(t){var e="POST",n=this.buildQueryObject(this._jsongUrl,e,{jsonGraph:t,method:"set"}),o=r(n,this._config);o.headers["Content-Type"]="application/x-www-form-urlencoded";var s=this;return i(e,o,s)},call:function(t,e,n,o){e=e||[],n=n||[],o=o||[];var s="POST",u=[];u.push("method=call"),u.push("callPath="+encodeURIComponent(JSON.stringify(t))),u.push("arguments="+encodeURIComponent(JSON.stringify(e))),u.push("pathSuffixes="+encodeURIComponent(JSON.stringify(n))),u.push("paths="+encodeURIComponent(JSON.stringify(o)));var a=this.buildQueryObject(this._jsongUrl,s,u.join("&")),c=r(a,this._config);c.headers["Content-Type"]="application/x-www-form-urlencoded";var p=this;return i(s,c,p)}},o.XMLHttpSource=o,o["default"]=o,e.exports=o},{126:126,129:129}],126:[function(t,e,n){"use strict";e.exports=function(t,e,n){var r,o=[],i={url:t},s=-1!==t.indexOf("?"),u=s?"&":"?";return"string"==typeof n?o.push(n):(r=Object.keys(n),r.forEach(function(t){var e="object"==typeof n[t]?JSON.stringify(n[t]):n[t];o.push(t+"="+encodeURIComponent(e))})),"GET"===e?i.url+=u+o.join("&"):i.data=o.join("&"),i}},{}],127:[function(t,e,n){(function(t){"use strict";e.exports=function(){var e=new t.XMLHttpRequest;if("withCredentials"in e)return e;if(t.XDomainRequest)return new XDomainRequest;throw new Error("CORS is not supported by your browser")}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],128:[function(t,e,n){(function(t){"use strict";e.exports=function(){var e,n,r;if(t.XMLHttpRequest)return new t.XMLHttpRequest;try{for(n=["Msxml2.XMLHTTP","Microsoft.XMLHTTP","Msxml2.XMLHTTP.4.0"],r=0;3>r;r++)try{if(e=n[r],new t.ActiveXObject(e))break}catch(o){}return new t.ActiveXObject(e)}catch(o){throw new Error("XMLHttpRequest is not supported by your browser")}}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],129:[function(t,e,n){"use strict";function r(){}function o(t,e,n){return r.create(function(r){var o,i,h,f,l,d={method:t||"GET",crossDomain:!1,async:!0,headers:{},responseType:"json"};for(l in e)p.call(e,l)&&(d[l]=e[l]);d.crossDomain||d.headers["X-Requested-With"]||(d.headers["X-Requested-With"]="XMLHttpRequest"),null!=n.onBeforeRequest&&n.onBeforeRequest(d);try{o=d.crossDomain?c():a()}catch(v){r.onError(v)}try{d.user?o.open(d.method,d.url,d.async,d.user,d.password):o.open(d.method,d.url,d.async),o.timeout=d.timeout,o.withCredentials=d.withCredentials!==!1,h=d.headers;for(f in h)p.call(h,f)&&o.setRequestHeader(f,h[f]);if(d.responseType)try{o.responseType=d.responseType}catch(y){if("json"!==d.responseType)throw y}o.onreadystatechange=function(t){4===o.readyState&&(i||(i=!0,s(r,o,t)))},o.ontimeout=function(t){i||(i=!0,u(r,o,"timeout error",t))},o.send(d.data)}catch(y){r.onError(y)}return function(){i||4===o.readyState||(i=!0,o.abort())}})}function i(t,e,n){n||(n=new Error(e)),t.onError(n)}function s(t,e,n){var r,o;if(e&&t){o=e.responseType,r="response"in e?e.response:e.responseText;var s=1223===e.status?204:e.status;if(s>=200&&399>=s){try{"json"!==o&&(r=JSON.parse(r||"")),"string"==typeof r&&(r=JSON.parse(r||""))}catch(n){i(t,"invalid json",n)}return t.onNext(r),void t.onCompleted()}return 401===s||403===s||407===s?i(t,r):410===s?i(t,r):408===s||504===s?i(t,r):i(t,r||"Response code "+s)}}function u(t,e,n,r){i(t,n||e.statusText||"request error",r)}var a=t(128),c=t(127),p=Object.prototype.hasOwnProperty,h=function(){};r.create=function(t){var e=new r;return e.subscribe=function(e,n,r){var o,i;return o="function"==typeof e?{onNext:e,onError:n||h,onCompleted:r||h}:e,i=t(o),"function"==typeof i?{dispose:i}:i},e},e.exports=o},{127:127,128:128}],130:[function(t,e,n){function r(t,e,n){var r=Object.create(null);if(null!=n){for(var o in n)r[o]=n[o];return r.$type=t,r.value=e,r}return{$type:t,value:e}}var o=t(134);e.exports={ref:function(t,e){return r("ref",o.fromPath(t),e)},atom:function(t,e){return r("atom",t,e)},undefined:function(){return r("atom")},error:function(t,e){return r("error",t,e)},pathValue:function(t,e){return{path:o.fromPath(t),value:e}},pathInvalidation:function(t){return{path:o.fromPath(t),invalidated:!0}}}},{134:134}],131:[function(t,e,n){e.exports={integers:"integers",ranges:"ranges",keys:"keys"}},{}],132:[function(t,e,n){var r={token:"token",dotSeparator:".",commaSeparator:",",openingBracket:"[",closingBracket:"]",openingBrace:"{",closingBrace:"}",escape:"\\",space:" ",colon:":",quote:"quote",unknown:"unknown"};e.exports=r},{}],133:[function(t,e,n){e.exports={indexer:{nested:"Indexers cannot be nested.",needQuotes:"unquoted indexers must be numeric.",empty:"cannot have empty indexers.",leadingDot:"Indexers cannot have leading dots.",leadingComma:"Indexers cannot have leading comma.",requiresComma:"Indexers require commas between indexer args.",routedTokens:"Only one token can be used per indexer when specifying routed tokens."},range:{precedingNaN:"ranges must be preceded by numbers.",suceedingNaN:"ranges must be suceeded by numbers."},routed:{invalid:"Invalid routed token.  only integers|ranges|keys are supported."},quote:{empty:"cannot have empty quoted keys.",illegalEscape:"Invalid escape character.  Only quotes are escapable."},unexpectedToken:"Unexpected token.",invalidIdentifier:"Invalid Identifier.",invalidPath:"Please provide a valid path.",throwError:function(t,e,n){if(n)throw t+" -- "+e.parseString+" with next token: "+n;throw t+" -- "+e.parseString}}},{}],134:[function(t,e,n){var r=t(140),o=t(135),i=t(131),s=function(t,e){return o(new r(t,e))};e.exports=s,s.fromPathsOrPathValues=function(t,e){if(!t)return[];for(var n=[],r=0,o=t.length;o>r;r++)"string"==typeof t[r]?n[r]=s(t[r],e):"string"==typeof t[r].path?n[r]={path:s(t[r].path,e),value:t[r].value}:n[r]=t[r];return n},s.fromPath=function(t,e){return t?"string"==typeof t?s(t,e):t:[]},s.RoutedTokens=i},{131:131,135:135,140:140}],135:[function(t,e,n){var r=t(132),o=t(133),i=t(136);e.exports=function(t){for(var e=t.next(),n={},s=[];!e.done;){switch(e.type){case r.token:var u=+e.token[0];isNaN(u)||o.throwError(o.invalidIdentifier,t),s[s.length]=e.token;break;case r.dotSeparator:0===s.length&&o.throwError(o.unexpectedToken,t);break;case r.space:break;case r.openingBracket:i(t,e,n,s);break;default:o.throwError(o.unexpectedToken,t)}e=t.next()}return 0===s.length&&o.throwError(o.invalidPath,t),s}},{132:132,133:133,136:136}],136:[function(t,e,n){var r=t(132),o=t(133),i=o.indexer,s=t(138),u=t(137),a=t(139);e.exports=function(t,e,n,c){var p=t.next(),h=!1,f=1,l=!1;for(n.indexer=[];!p.done;){switch(p.type){case r.token:case r.quote:n.indexer.length===f&&o.throwError(i.requiresComma,t)}switch(p.type){case r.openingBrace:l=!0,a(t,p,n,c);break;case r.token:var d=+p.token;isNaN(d)&&o.throwError(i.needQuotes,t),n.indexer[n.indexer.length]=d;break;case r.dotSeparator:n.indexer.length||o.throwError(i.leadingDot,t),s(t,p,n,c);
3459 break;case r.space:break;case r.closingBracket:h=!0;break;case r.quote:u(t,p,n,c);break;case r.openingBracket:o.throwError(i.nested,t);break;case r.commaSeparator:++f;break;default:o.throwError(o.unexpectedToken,t)}if(h)break;p=t.next()}0===n.indexer.length&&o.throwError(i.empty,t),n.indexer.length>1&&l&&o.throwError(i.routedTokens,t),1===n.indexer.length&&(n.indexer=n.indexer[0]),c[c.length]=n.indexer,n.indexer=void 0}},{132:132,133:133,137:137,138:138,139:139}],137:[function(t,e,n){var r=t(132),o=t(133),i=o.quote;e.exports=function(t,e,n,s){for(var u=t.next(),a="",c=e.token,p=!1,h=!1;!u.done;){switch(u.type){case r.token:case r.space:case r.dotSeparator:case r.commaSeparator:case r.openingBracket:case r.closingBracket:case r.openingBrace:case r.closingBrace:p&&o.throwError(i.illegalEscape,t),a+=u.token;break;case r.quote:p?(a+=u.token,p=!1):u.token!==c?a+=u.token:h=!0;break;case r.escape:p=!0;break;default:o.throwError(o.unexpectedToken,t)}if(h)break;u=t.next()}0===a.length&&o.throwError(i.empty,t),n.indexer[n.indexer.length]=a}},{132:132,133:133}],138:[function(t,e,n){var r=t(140),o=t(132),i=t(133);e.exports=function(t,e,n,s){var u,a=t.peek(),c=1,p=!1,h=!0,f=n.indexer.length-1,l=r.toNumber(n.indexer[f]);for(isNaN(l)&&i.throwError(i.range.precedingNaN,t);!p&&!a.done;){switch(a.type){case o.dotSeparator:3===c&&i.throwError(i.unexpectedToken,t),++c,3===c&&(h=!1);break;case o.token:u=r.toNumber(t.next().token),isNaN(u)&&i.throwError(i.range.suceedingNaN,t),p=!0;break;default:p=!0}if(p)break;t.next(),a=t.peek()}n.indexer[f]={from:l,to:h?u:u-1}}},{132:132,133:133,140:140}],139:[function(t,e,n){var r=t(132),o=t(131),i=t(133),s=i.routed;e.exports=function(t,e,n,u){var a=t.next(),c=!1,p="";switch(a.token){case o.integers:case o.ranges:case o.keys:break;default:i.throwError(s.invalid,t)}var h=t.next();if(h.type===r.colon&&(c=!0,h=t.next(),h.type!==r.token&&i.throwError(s.invalid,t),p=h.token,h=t.next()),h.type===r.closingBrace){var f={type:a.token,named:c,name:p};n.indexer[n.indexer.length]=f}else i.throwError(s.invalid,t)}},{131:131,132:132,133:133}],140:[function(t,e,n){function r(t,e,n){return{token:t,done:n,type:e}}function o(t,e,n){var o,g=!1,w="",x=n?m:b;do{if(o=e+1>=t.length)break;var _=t[e+1];if(void 0===_||-1!==x.indexOf(_)){if(w.length)break;++e;var S;switch(_){case s:S=i.dotSeparator;break;case u:S=i.commaSeparator;break;case a:S=i.openingBracket;break;case c:S=i.closingBracket;break;case p:S=i.openingBrace;break;case h:S=i.closingBrace;break;case y:S=i.space;break;case d:case v:S=i.quote;break;case l:S=i.escape;break;case f:S=i.colon;break;default:S=i.unknown}g=r(_,S,!1);break}w+=_,++e}while(!o);return!g&&w.length&&(g=r(w,i.token,!1)),g||(g={done:!0}),{token:g,idx:e}}var i=t(132),s=".",u=",",a="[",c="]",p="{",h="}",f=":",l="\\",d='"',v="'",y=" ",b="\\'\"[]., ",m="\\{}'\"[]., :",g=e.exports=function(t,e){this._string=t,this._idx=-1,this._extended=e,this.parseString=""};g.prototype={next:function(){var t=this._nextToken?this._nextToken:o(this._string,this._idx,this._extended);return this._idx=t.idx,this._nextToken=!1,this.parseString+=t.token.token,t.token},peek:function(){var t=this._nextToken?this._nextToken:o(this._string,this._idx,this._extended);return this._nextToken=t,t.token}},g.toNumber=function(t){return isNaN(+t)?NaN:+t}},{132:132}],141:[function(t,e,n){var r=t(147),o=t(148);e.exports=function(t){var e=t.reduce(function(t,e){var n=e.length;return t[n]||(t[n]=[]),t[n].push(e),t},{});return Object.keys(e).forEach(function(t){e[t]=o(e[t])}),r(e)}},{147:147,148:148}],142:[function(t,e,n){var r=t(144);e.exports=function o(t,e,n){for(var i=t,s=!0;s&&n<e.length;++n){var u=e[n],a=typeof u;if(u&&"object"===a){var c={},p=r(u,c),h=n+1;do{var f=i[p];s=void 0!==f,s&&(s=o(f,e,h)),p=r(u,c)}while(s&&!c.done);break}i=i[u],s=void 0!==i}return s}},{144:144}],143:[function(t,e,n){e.exports={iterateKeySet:t(144),toTree:t(148),toTreeWithUnion:t(149),pathsComplementFromTree:t(146),pathsComplementFromLengthTree:t(145),hasIntersection:t(142),toPaths:t(147),collapse:t(141)}},{141:141,142:142,144:144,145:145,146:146,147:147,148:148,149:149}],144:[function(t,e,n){function r(t,e){var n=e.from=t.from||0,r=e.to=t.to||"number"==typeof t.length&&e.from+t.length-1||0;e.rangeOffset=e.from,e.loaded=!0,n>r&&(e.empty=!0)}function o(t,e){e.done=!1;var n=e.isObject=!(!t||"object"!=typeof t);e.isArray=n&&i(t),e.arrayOffset=0}var i=Array.isArray;e.exports=function(t,e){if(void 0===e.isArray&&o(t,e),e.isArray){var n;do{e.loaded&&e.rangeOffset>e.to&&(++e.arrayOffset,e.loaded=!1);var i=e.arrayOffset,s=t.length;if(i>=s){e.done=!0;break}var u=t[e.arrayOffset],a=typeof u;if("object"===a){if(e.loaded||r(u,e),e.empty)continue;n=e.rangeOffset++}else++e.arrayOffset,n=u}while(void 0===n);return n}return e.isObject?(e.loaded||r(t,e),e.rangeOffset>e.to?void(e.done=!0):e.rangeOffset++):(e.done=!0,t)}},{}],145:[function(t,e,n){var r=t(142);e.exports=function(t,e){for(var n=[],o=-1,i=0,s=t.length;s>i;++i){var u=t[i];r(e[u.length],u,0)||(n[++o]=u)}return n}},{142:142}],146:[function(t,e,n){var r=t(142);e.exports=function(t,e){for(var n=[],o=-1,i=0,s=t.length;s>i;++i)r(e,t[i],0)||(n[++o]=t[i]);return n}},{142:142}],147:[function(t,e,n){function r(t){return null!==t&&typeof t===f}function o(t,e,n){var r,i,s,u,h,f,l,d,v,y,b,m,g,w,x=c(String(e)),_=Object.create(null),S=[],E=-1,C=0,A=[],N=0;if(u=[],h=-1,n-1>e){for(f=a(t,u);++h<f;)r=u[h],i=o(t[r],e+1,n),s=i.code,_[s]?i=_[s]:(S[C++]=s,i=_[s]={keys:[],sets:i.sets}),x=c(x+r+s),p(r)&&i.keys.push(parseInt(r,10))||i.keys.push(r);for(;++E<C;)if(r=S[E],i=_[r],u=i.keys,f=u.length,f>0)for(l=i.sets,d=-1,v=l.length,g=u[0];++d<v;){for(y=l[d],b=-1,m=y.length,w=new Array(m+1),w[0]=f>1&&u||g;++b<m;)w[b+1]=y[b];A[N++]=w}}else for(f=a(t,u),f>1?A[N++]=[u]:A[N++]=u;++h<f;)x=c(x+u[h]);return{code:x,sets:A}}function i(t){for(var e=-1,n=t.length;++e<n;){var r=t[e];h(r)&&(t[e]=s(r))}return t}function s(t){for(var e=-1,n=t.length-1,r=n>0;++e<=n;){var o=t[e];if(!p(o)){r=!1;break}t[e]=parseInt(o,10)}if(r===!0){t.sort(u);var i=t[0],s=t[n];if(n>=s-i)return{from:i,to:s}}return t}function u(t,e){return t-e}function a(t,e,n){var r=0;for(var o in t)e[r++]=o;return r>1&&e.sort(n),r}function c(t){for(var e=5381,n=-1,r=t.length;++n<r;)e=(e<<5)+e+t.charCodeAt(n);return String(e)}function p(t){return!h(t)&&t-parseFloat(t)+1>=0}var h=Array.isArray,f="object";e.exports=function(t){var e,n=[],s=0;for(var u in t)if(p(u)&&r(e=t[u]))for(var a=o(e,0,parseInt(u,10)).sets,c=-1,h=a.length;++c<h;)n[s++]=i(a[c]);return n}},{}],148:[function(t,e,n){function r(t,e,n){var i,s=e[n],u={},a=n+1;i=o(s,u);do{var c=t[i];c||(a===e.length?t[i]=null:c=t[i]={}),a<e.length&&r(c,e,a),u.done||(i=o(s,u))}while(!u.done)}var o=t(144);Array.isArray;e.exports=function(t){return t.reduce(function(t,e){return r(t,e,0),t},{})}},{144:144}],149:[function(t,e,n){},{}],150:[function(t,e,n){function r(){p=!1,u.length?c=u.concat(c):h=-1,c.length&&o()}function o(){if(!p){var t=setTimeout(r);p=!0;for(var e=c.length;e;){for(u=c,c=[];++h<e;)u&&u[h].run();h=-1,e=c.length}u=null,p=!1,clearTimeout(t)}}function i(t,e){this.fun=t,this.array=e}function s(){}var u,a=e.exports={},c=[],p=!1,h=-1;a.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];c.push(new i(t,e)),1!==c.length||p||setTimeout(o,0)},i.prototype.run=function(){this.fun.apply(null,this.array)},a.title="browser",a.browser=!0,a.env={},a.argv=[],a.version="",a.versions={},a.on=s,a.addListener=s,a.once=s,a.off=s,a.removeListener=s,a.removeAllListeners=s,a.emit=s,a.binding=function(t){throw new Error("process.binding is not supported")},a.cwd=function(){return"/"},a.chdir=function(t){throw new Error("process.chdir is not supported")},a.umask=function(){return 0}},{}],151:[function(t,e,n){"use strict";e.exports=t(156)},{156:156}],152:[function(t,e,n){"use strict";function r(){}function o(t){try{return t.then}catch(e){return y=e,b}}function i(t,e){try{return t(e)}catch(n){return y=n,b}}function s(t,e,n){try{t(e,n)}catch(r){return y=r,b}}function u(t){if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof t)throw new TypeError("not a function");this._37=0,this._12=null,this._59=[],t!==r&&d(t,this)}function a(t,e,n){return new t.constructor(function(o,i){var s=new u(r);s.then(o,i),c(t,new l(e,n,s))})}function c(t,e){for(;3===t._37;)t=t._12;return 0===t._37?void t._59.push(e):void v(function(){var n=1===t._37?e.onFulfilled:e.onRejected;if(null===n)return void(1===t._37?p(e.promise,t._12):h(e.promise,t._12));var r=i(n,t._12);r===b?h(e.promise,y):p(e.promise,r)})}function p(t,e){if(e===t)return h(t,new TypeError("A promise cannot be resolved with itself."));if(e&&("object"==typeof e||"function"==typeof e)){var n=o(e);if(n===b)return h(t,y);if(n===t.then&&e instanceof u)return t._37=3,t._12=e,void f(t);if("function"==typeof n)return void d(n.bind(e),t)}t._37=1,t._12=e,f(t)}function h(t,e){t._37=2,t._12=e,f(t)}function f(t){for(var e=0;e<t._59.length;e++)c(t,t._59[e]);t._59=null}function l(t,e,n){this.onFulfilled="function"==typeof t?t:null,this.onRejected="function"==typeof e?e:null,this.promise=n}function d(t,e){var n=!1,r=s(t,function(t){n||(n=!0,p(e,t))},function(t){n||(n=!0,h(e,t))});n||r!==b||(n=!0,h(e,y))}var v=t(124),y=null,b={};e.exports=u,u._99=r,u.prototype.then=function(t,e){if(this.constructor!==u)return a(this,t,e);var n=new u(r);return c(this,new l(t,e,n)),n}},{124:124}],153:[function(t,e,n){"use strict";var r=t(152);e.exports=r,r.prototype.done=function(t,e){var n=arguments.length?this.then.apply(this,arguments):this;n.then(null,function(t){setTimeout(function(){throw t},0)})}},{152:152}],154:[function(t,e,n){"use strict";function r(t){var e=new o(o._99);return e._37=1,e._12=t,e}var o=t(152);e.exports=o;var i=r(!0),s=r(!1),u=r(null),a=r(void 0),c=r(0),p=r("");o.resolve=function(t){if(t instanceof o)return t;if(null===t)return u;if(void 0===t)return a;if(t===!0)return i;if(t===!1)return s;if(0===t)return c;if(""===t)return p;if("object"==typeof t||"function"==typeof t)try{var e=t.then;if("function"==typeof e)return new o(e.bind(t))}catch(n){return new o(function(t,e){e(n)})}return r(t)},o.all=function(t){var e=Array.prototype.slice.call(t);return new o(function(t,n){function r(s,u){if(u&&("object"==typeof u||"function"==typeof u)){if(u instanceof o&&u.then===o.prototype.then){for(;3===u._37;)u=u._12;return 1===u._37?r(s,u._12):(2===u._37&&n(u._12),void u.then(function(t){r(s,t)},n))}var a=u.then;if("function"==typeof a){var c=new o(a.bind(u));return void c.then(function(t){r(s,t)},n)}}e[s]=u,0===--i&&t(e)}if(0===e.length)return t([]);for(var i=e.length,s=0;s<e.length;s++)r(s,e[s])})},o.reject=function(t){return new o(function(e,n){n(t)})},o.race=function(t){return new o(function(e,n){t.forEach(function(t){o.resolve(t).then(e,n)})})},o.prototype["catch"]=function(t){return this.then(null,t)}},{152:152}],155:[function(t,e,n){"use strict";var r=t(152);e.exports=r,r.prototype["finally"]=function(t){return this.then(function(e){return r.resolve(t()).then(function(){return e})},function(e){return r.resolve(t()).then(function(){throw e})})}},{152:152}],156:[function(t,e,n){"use strict";e.exports=t(152),t(153),t(155),t(154),t(157)},{152:152,153:153,154:154,155:155,157:157}],157:[function(t,e,n){"use strict";var r=t(152),o=t(123);e.exports=r,r.denodeify=function(t,e){return e=e||1/0,function(){var n=this,o=Array.prototype.slice.call(arguments,0,e>0?e:0);return new r(function(e,r){o.push(function(t,n){t?r(t):e(n)});var i=t.apply(n,o);!i||"object"!=typeof i&&"function"!=typeof i||"function"!=typeof i.then||e(i)})}},r.nodeify=function(t){return function(){var e=Array.prototype.slice.call(arguments),n="function"==typeof e[e.length-1]?e.pop():null,i=this;try{return t.apply(this,arguments).nodeify(n,i)}catch(s){if(null===n||"undefined"==typeof n)return new r(function(t,e){e(s)});o(function(){n.call(i,s)})}}},r.prototype.nodeify=function(t,e){return"function"!=typeof t?this:void this.then(function(n){o(function(){t.call(e,null,n)})},function(n){o(function(){t.call(e,n)})})}},{123:123,152:152}],158:[function(e,n,r){(function(o){(function(i){var s={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},u=s[typeof window]&&window||this,a=s[typeof r]&&r&&!r.nodeType&&r,c=s[typeof n]&&n&&!n.nodeType&&n,p=(c&&c.exports===a&&a,s[typeof o]&&o);!p||p.global!==p&&p.window!==p||(u=p),"function"==typeof t&&t.amd?t(["rx"],function(t,e){return i(u,e,t)}):"object"==typeof n&&n&&n.exports===a?n.exports=i(u,n.exports,e(159)):u.Rx=i(u,{},u.Rx)}).call(this,function(t,e,n,r){function o(){try{return l.apply(this,arguments)}catch(t){return M.e=t,M}}function i(t){if(!E(t))throw new TypeError("fn must be a function");return l=t,o}function s(t,e,n){return new b(function(r){var o=!1,i=null,s=[];return t.subscribe(function(t){var u,a;try{a=e(t)}catch(c){return void r.onError(c)}if(u=0,o)try{u=n(a,i)}catch(p){return void r.onError(p)}else o=!0,i=a;u>0&&(i=a,s=[]),u>=0&&s.push(t)},function(t){r.onError(t)},function(){r.onNext(s),r.onCompleted()})},t)}function u(t){if(0===t.length)throw new D;return t[0]}function a(t,e,n,r){if(0>e)throw new R;return new b(function(o){var i=e;return t.subscribe(function(t){0===i--&&(o.onNext(t),o.onCompleted())},function(t){o.onError(t)},function(){n?(o.onNext(r),o.onCompleted()):o.onError(new R)})},t)}function c(t,e,n){return new b(function(r){var o=n,i=!1;return t.subscribe(function(t){i?r.onError(new Error("Sequence contains more than one element")):(o=t,i=!0)},function(t){r.onError(t)},function(){i||e?(r.onNext(o),r.onCompleted()):r.onError(new D)})},t)}function p(t,e,n){return new b(function(r){return t.subscribe(function(t){r.onNext(t),r.onCompleted()},function(t){r.onError(t)},function(){e?(r.onNext(n),r.onCompleted()):r.onError(new D)})},t)}function h(t,e,n){return new b(function(r){var o=n,i=!1;return t.subscribe(function(t){o=t,i=!0},function(t){r.onError(t)},function(){i||e?(r.onNext(o),r.onCompleted()):r.onError(new D)})},t)}function f(t,e,n,o){var i=j(e,n,3);return new b(function(e){var n=0;return t.subscribe(function(r){var s;try{s=i(r,n,t)}catch(u){return void e.onError(u)}s?(e.onNext(o?n:r),e.onCompleted()):n++},function(t){e.onError(t)},function(){e.onNext(o?-1:r),e.onCompleted()})},t)}var l,d=n.Observable,v=d.prototype,y=n.CompositeDisposable,b=n.AnonymousObservable,m=n.Disposable.empty,g=(n.internals.isEqual,n.helpers),w=g.not,x=g.defaultComparer,_=g.identity,S=g.defaultSubComparer,E=g.isFunction,C=g.isPromise,A=g.isArrayLike,N=g.isIterable,k=n.internals.inherits,O=d.fromPromise,P=d.from,j=n.internals.bindCallback,D=n.EmptyError,q=n.ObservableBase,R=n.ArgumentOutOfRangeError,M={e:{}};v.aggregate=function(){var t,e,n=!1,r=this;return 2===arguments.length?(n=!0,e=arguments[0],t=arguments[1]):t=arguments[0],new b(function(o){var i,s,u;return r.subscribe(function(r){!u&&(u=!0);try{i?s=t(s,r):(s=n?t(e,r):r,i=!0)}catch(a){return o.onError(a)}},function(t){o.onError(t)},function(){u&&o.onNext(s),!u&&n&&o.onNext(e),!u&&!n&&o.onError(new D),o.onCompleted()})},r)};var T=function(t){function e(e,n,r,o){this.source=e,this.acc=n,this.hasSeed=r,this.seed=o,t.call(this)}function n(t,e){this.o=t,this.acc=e.acc,this.hasSeed=e.hasSeed,this.seed=e.seed,this.hasAccumulation=!1,this.result=null,this.hasValue=!1,this.isStopped=!1}return k(e,t),e.prototype.subscribeCore=function(t){return this.source.subscribe(new n(t,this))},n.prototype.onNext=function(t){this.isStopped||(!this.hasValue&&(this.hasValue=!0),this.hasAccumulation?this.result=i(this.acc)(this.result,t):(this.result=this.hasSeed?i(this.acc)(this.seed,t):t,this.hasAccumulation=!0),this.result===M&&this.o.onError(this.result.e))},n.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},n.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.hasValue&&this.o.onNext(this.result),!this.hasValue&&this.hasSeed&&this.o.onNext(this.seed),!this.hasValue&&!this.hasSeed&&this.o.onError(new D),this.o.onCompleted())},n.prototype.dispose=function(){this.isStopped=!0},n.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},e}(q);return v.reduce=function(t){var e=!1;if(2===arguments.length){e=!0;var n=arguments[1]}return new T(this,t,e,n)},v.some=function(t,e){var n=this;return t?n.filter(t,e).some():new b(function(t){return n.subscribe(function(){t.onNext(!0),t.onCompleted()},function(e){t.onError(e)},function(){t.onNext(!1),t.onCompleted()})},n)},v.any=function(){return this.some.apply(this,arguments)},v.isEmpty=function(){return this.any().map(w)},v.every=function(t,e){return this.filter(function(e){return!t(e)},e).some().map(w)},v.all=function(){return this.every.apply(this,arguments)},v.includes=function(t,e){function n(t,e){return 0===t&&0===e||t===e||isNaN(t)&&isNaN(e)}var r=this;return new b(function(o){var i=0,s=+e||0;return Math.abs(s)===1/0&&(s=0),0>s?(o.onNext(!1),o.onCompleted(),m):r.subscribe(function(e){i++>=s&&n(e,t)&&(o.onNext(!0),o.onCompleted())},function(t){o.onError(t)},function(){o.onNext(!1),o.onCompleted()})},this)},v.contains=function(t,e){v.includes(t,e)},v.count=function(t,e){return t?this.filter(t,e).count():this.reduce(function(t){return t+1},0)},v.indexOf=function(t,e){var n=this;return new b(function(r){var o=0,i=+e||0;return Math.abs(i)===1/0&&(i=0),0>i?(r.onNext(-1),r.onCompleted(),m):n.subscribe(function(e){o>=i&&e===t&&(r.onNext(o),r.onCompleted()),o++},function(t){r.onError(t)},function(){r.onNext(-1),r.onCompleted()})},n)},v.sum=function(t,e){return t&&E(t)?this.map(t,e).sum():this.reduce(function(t,e){return t+e},0)},v.minBy=function(t,e){return e||(e=S),s(this,t,function(t,n){return-1*e(t,n)})},v.min=function(t){return this.minBy(_,t).map(function(t){return u(t)})},v.maxBy=function(t,e){return e||(e=S),s(this,t,e)},v.max=function(t){return this.maxBy(_,t).map(function(t){return u(t)})},v.average=function(t,e){return t&&E(t)?this.map(t,e).average():this.reduce(function(t,e){return{sum:t.sum+e,count:t.count+1}},{sum:0,count:0}).map(function(t){if(0===t.count)throw new D;return t.sum/t.count})},v.sequenceEqual=function(t,e){var n=this;return e||(e=x),new b(function(r){var o=!1,i=!1,s=[],u=[],a=n.subscribe(function(t){var n,o;if(u.length>0){o=u.shift();try{n=e(o,t)}catch(a){return void r.onError(a)}n||(r.onNext(!1),r.onCompleted())}else i?(r.onNext(!1),r.onCompleted()):s.push(t)},function(t){r.onError(t)},function(){o=!0,0===s.length&&(u.length>0?(r.onNext(!1),r.onCompleted()):i&&(r.onNext(!0),r.onCompleted()))});(A(t)||N(t))&&(t=P(t)),C(t)&&(t=O(t));var c=t.subscribe(function(t){var n;if(s.length>0){var i=s.shift();try{n=e(i,t)}catch(a){return void r.onError(a)}n||(r.onNext(!1),r.onCompleted())}else o?(r.onNext(!1),r.onCompleted()):u.push(t)},function(t){r.onError(t)},function(){i=!0,0===u.length&&(s.length>0?(r.onNext(!1),r.onCompleted()):o&&(r.onNext(!0),r.onCompleted()))});return new y(a,c)},n)},v.elementAt=function(t){return a(this,t,!1)},v.elementAtOrDefault=function(t,e){return a(this,t,!0,e)},v.single=function(t,e){return t&&E(t)?this.where(t,e).single():c(this,!1)},v.singleOrDefault=function(t,e,n){return t&&E(t)?this.filter(t,n).singleOrDefault(null,e):c(this,!0,e)},v.first=function(t,e){return t?this.where(t,e).first():p(this,!1)},v.firstOrDefault=function(t,e,n){return t?this.where(t).firstOrDefault(null,e):p(this,!0,e)},v.last=function(t,e){return t?this.where(t,e).last():h(this,!1)},v.lastOrDefault=function(t,e,n){return t?this.where(t,n).lastOrDefault(null,e):h(this,!0,e)},v.find=function(t,e){return f(this,t,e,!1)},v.findIndex=function(t,e){return f(this,t,e,!0)},v.toSet=function(){if("undefined"==typeof t.Set)throw new TypeError;var e=this;return new b(function(n){var r=new t.Set;return e.subscribe(function(t){r.add(t)},function(t){n.onError(t)},function(){n.onNext(r),n.onCompleted()})},e)},v.toMap=function(e,n){if("undefined"==typeof t.Map)throw new TypeError;var r=this;return new b(function(o){var i=new t.Map;return r.subscribe(function(t){var r;try{r=e(t)}catch(s){return void o.onError(s)}var u=t;if(n)try{u=n(t)}catch(s){return void o.onError(s)}i.set(r,u)},function(t){o.onError(t)},function(){o.onNext(i),o.onCompleted()})},r)},n})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{159:159}],159:[function(e,n,r){(function(e,o){(function(i){function u(t){for(var e=[],n=0,r=t.length;r>n;n++)e.push(t[n]);return e}function a(t,e){if(ct&&e.stack&&"object"==typeof t&&null!==t&&t.stack&&-1===t.stack.indexOf(lt)){for(var n=[],r=e;r;r=r.source)r.stack&&n.unshift(r.stack);n.unshift(t.stack);var o=n.join("\n"+lt+"\n");t.stack=c(o)}}function c(t){for(var e=t.split("\n"),n=[],r=0,o=e.length;o>r;r++){var i=e[r];p(i)||h(i)||!i||n.push(i)}return n.join("\n")}function p(t){var e=l(t);if(!e)return!1;var n=e[0],r=e[1];return n===ht&&r>=ft&&$n>=r}function h(t){return-1!==t.indexOf("(module.js:")||-1!==t.indexOf("(node.js:")}function f(){if(ct)try{throw new Error}catch(t){var e=t.stack.split("\n"),n=e[0].indexOf("@")>0?e[1]:e[2],r=l(n);if(!r)return;return ht=r[0],r[1]}}function l(t){var e=/at .+ \((.+):(\d+):(?:\d+)\)$/.exec(t);if(e)return[e[1],Number(e[2])];var n=/at ([^ ]+):(\d+):(?:\d+)$/.exec(t);if(n)return[n[1],Number(n[2])];var r=/.*@(.+):(\d+)$/.exec(t);return r?[r[1],Number(r[2])]:void 0}function d(t){var e=[];if(!Ht(t))return e;Ut.nonEnumArgs&&t.length&&Xt(t)&&(t=Yt.call(t));var n=Ut.enumPrototypes&&"function"==typeof t,r=Ut.enumErrorProps&&(t===Jt||t instanceof Error);for(var o in t)n&&"prototype"==o||r&&("message"==o||"name"==o)||e.push(o);if(Ut.nonEnumShadows&&t!==It){var i=t.constructor,s=-1,u=kt;if(t===(i&&i.prototype))var a=t===Lt?$t:t===Jt?qt:Wt.call(t),c=Ft[a];for(;++s<u;)o=Nt[s],c&&c[o]||!zt.call(t,o)||e.push(o)}return e}function v(t,e,n){for(var r=-1,o=n(t),i=o.length;++r<i;){var s=o[r];if(e(t[s],s,t)===!1)break}return t}function y(t,e){return v(t,e,d)}function b(t){return"function"!=typeof t.toString&&"string"==typeof(t+"")}function m(t,e,n,r){if(t===e)return 0!==t||1/t==1/e;var o=typeof t,i=typeof e;if(t===t&&(null==t||null==e||"function"!=o&&"object"!=o&&"function"!=i&&"object"!=i))return!1;var s=Wt.call(t),u=Wt.call(e);if(s==Ot&&(s=Tt),u==Ot&&(u=Tt),s!=u)return!1;switch(s){case jt:case Dt:return+t==+e;case Mt:return t!=+t?e!=+e:0==t?1/t==1/e:t==+e;case Vt:case $t:return t==String(e)}var a=s==Pt;if(!a){if(s!=Tt||!Ut.nodeClass&&(b(t)||b(e)))return!1;var c=!Ut.argsObject&&Xt(t)?Object:t.constructor,p=!Ut.argsObject&&Xt(e)?Object:e.constructor;if(!(c==p||zt.call(t,"constructor")&&zt.call(e,"constructor")||at(c)&&c instanceof c&&at(p)&&p instanceof p||!("constructor"in t&&"constructor"in e)))return!1}n||(n=[]),r||(r=[]);for(var h=n.length;h--;)if(n[h]==t)return r[h]==e;var f=0,l=!0;if(n.push(t),r.push(e),a){if(h=t.length,f=e.length,l=f==h)for(;f--;){var d=e[f];if(!(l=m(t[f],d,n,r)))break}}else y(e,function(e,o,i){return zt.call(i,o)?(f++,l=zt.call(t,o)&&m(t[o],e,n,r)):void 0}),l&&y(t,function(t,e,n){return zt.call(n,e)?l=--f>-1:void 0});return n.pop(),r.pop(),l}function g(t,e){for(var n=new Array(t),r=0;t>r;r++)n[r]=e();return n}function w(){try{return Qt.apply(this,arguments)}catch(t){return ne.e=t,ne}}function x(t){if(!at(t))throw new TypeError("fn must be a function");return Qt=t,w}function _(t){throw t}function S(t,e){this.id=t,this.value=e}function E(t,e){this.scheduler=t,this.disposable=e,this.isDisposed=!1}function C(t,e){e.isDisposed||(e.isDisposed=!0,e.disposable.dispose())}function A(t){this._s=s}function N(t){this._s=s,this._l=s.length,this._i=0}function k(t){this._a=t}function O(t){this._a=t,this._l=q(t),this._i=0}function P(t){return"number"==typeof t&&X.isFinite(t)}function j(t){var e,n=t[xt];if(!n&&"string"==typeof t)return e=new A(t),e[xt]();if(!n&&t.length!==i)return e=new k(t),e[xt]();if(!n)throw new TypeError("Object is not iterable");return t[xt]()}function D(t){var e=+t;return 0===e?e:isNaN(e)?e:0>e?-1:1}function q(t){var e=+t.length;return isNaN(e)?0:0!==e&&P(e)?(e=D(e)*Math.floor(Math.abs(e)),0>=e?0:e>en?en:e):e}function R(t,e){this.observer=t,this.parent=e}function M(t,e){return me(t)||(t=_e),new rn(e,t)}function T(t,e){this.observer=t,this.parent=e}function V(t,e){this.observer=t,this.parent=e}function $(t,e){return new qn(function(n){var r=new fe,o=new le;return o.setDisposable(r),r.setDisposable(t.subscribe(function(t){n.onNext(t)},function(t){try{var r=e(t)}catch(i){return n.onError(i)}ut(r)&&(r=Xe(r));var s=new fe;o.setDisposable(s),s.setDisposable(r.subscribe(n))},function(t){n.onCompleted(t)})),o},t)}function W(){return!1}function z(t,e){var n=this;return new qn(function(r){var o=0,i=t.length;return n.subscribe(function(n){if(i>o){var s=t[o++],u=x(e)(n,s);if(u===ne)return r.onError(u.e);r.onNext(u)}else r.onCompleted()},function(t){r.onError(t)},function(){r.onCompleted()})},n)}function W(){return!1}function G(){return[]}function W(){return!1}function J(){return[]}function I(t,e){this.observer=t,this.accumulator=e.accumulator,this.hasSeed=e.hasSeed,this.seed=e.seed,this.hasAccumulation=!1,this.accumulation=null,this.hasValue=!1,this.isStopped=!1}function L(t,e,n){var r=At(e,n,3);return t.map(function(e,n){var o=r(e,n,t);return ut(o)&&(o=Xe(o)),(Et(o)||St(o))&&(o=nn(o)),o}).concatAll()}function B(t,e,n){for(var r=0,o=t.length;o>r;r++)if(n(t[r],e))return r;return-1}function F(t){this.comparer=t,this.set=[]}function U(t,e,n){var r=At(e,n,3);return t.map(function(e,n){var o=r(e,n,t);return ut(o)&&(o=Xe(o)),(Et(o)||St(o))&&(o=nn(o)),o}).mergeAll()}var H={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},X=H[typeof window]&&window||this,Q=H[typeof r]&&r&&!r.nodeType&&r,K=H[typeof n]&&n&&!n.nodeType&&n,Y=K&&K.exports===Q&&Q,Z=H[typeof o]&&o;!Z||Z.global!==Z&&Z.window!==Z||(X=Z);var tt={internals:{},config:{Promise:X.Promise},helpers:{}},et=tt.helpers.noop=function(){},nt=(tt.helpers.notDefined=function(t){return"undefined"==typeof t},tt.helpers.identity=function(t){return t}),rt=(tt.helpers.pluck=function(t){return function(e){return e[t]}},tt.helpers.just=function(t){return function(){return t}},tt.helpers.defaultNow=Date.now),ot=tt.helpers.defaultComparer=function(t,e){return Kt(t,e)},it=tt.helpers.defaultSubComparer=function(t,e){return t>e?1:e>t?-1:0},st=(tt.helpers.defaultKeySerializer=function(t){return t.toString()},tt.helpers.defaultError=function(t){throw t}),ut=tt.helpers.isPromise=function(t){return!!t&&"function"!=typeof t.subscribe&&"function"==typeof t.then},at=(tt.helpers.asArray=function(){return Array.prototype.slice.call(arguments)},tt.helpers.not=function(t){return!t},tt.helpers.isFunction=function(){var t=function(t){return"function"==typeof t||!1};return t(/x/)&&(t=function(t){return"function"==typeof t&&"[object Function]"==Wt.call(t)}),t}());tt.config.longStackSupport=!1;var ct=!1;try{throw new Error}catch(pt){ct=!!pt.stack}var ht,ft=f(),lt="From previous event:",dt=tt.EmptyError=function(){this.message="Sequence contains no elements.",Error.call(this)};dt.prototype=Error.prototype;var vt=tt.ObjectDisposedError=function(){this.message="Object has been disposed",Error.call(this)};vt.prototype=Error.prototype;var yt=tt.ArgumentOutOfRangeError=function(){this.message="Argument out of range",Error.call(this)};yt.prototype=Error.prototype;var bt=tt.NotSupportedError=function(t){this.message=t||"This operation is not supported",Error.call(this)};bt.prototype=Error.prototype;var mt=tt.NotImplementedError=function(t){this.message=t||"This operation is not implemented",Error.call(this)};mt.prototype=Error.prototype;var gt=tt.helpers.notImplemented=function(){throw new mt},wt=tt.helpers.notSupported=function(){throw new bt},xt="function"==typeof Symbol&&Symbol.iterator||"_es6shim_iterator_";X.Set&&"function"==typeof(new X.Set)["@@iterator"]&&(xt="@@iterator");var _t=tt.doneEnumerator={done:!0,value:i},St=tt.helpers.isIterable=function(t){return t[xt]!==i},Et=tt.helpers.isArrayLike=function(t){return t&&t.length!==i};tt.helpers.iterator=xt;var Ct,At=tt.internals.bindCallback=function(t,e,n){if("undefined"==typeof e)return t;switch(n){case 0:return function(){return t.call(e)};case 1:return function(n){return t.call(e,n)};case 2:return function(n,r){return t.call(e,n,r)};case 3:return function(n,r,o){return t.call(e,n,r,o)}}return function(){return t.apply(e,arguments)}},Nt=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],kt=Nt.length,Ot="[object Arguments]",Pt="[object Array]",jt="[object Boolean]",Dt="[object Date]",qt="[object Error]",Rt="[object Function]",Mt="[object Number]",Tt="[object Object]",Vt="[object RegExp]",$t="[object String]",Wt=Object.prototype.toString,zt=Object.prototype.hasOwnProperty,Gt=Wt.call(arguments)==Ot,Jt=Error.prototype,It=Object.prototype,Lt=String.prototype,Bt=It.propertyIsEnumerable;try{Ct=!(Wt.call(document)==Tt&&!({toString:0}+""))}catch(pt){Ct=!0}var Ft={};Ft[Pt]=Ft[Dt]=Ft[Mt]={constructor:!0,toLocaleString:!0,toString:!0,valueOf:!0},Ft[jt]=Ft[$t]={constructor:!0,toString:!0,valueOf:!0},Ft[qt]=Ft[Rt]=Ft[Vt]={constructor:!0,toString:!0},Ft[Tt]={constructor:!0};var Ut={};!function(){var t=function(){this.x=1},e=[];t.prototype={valueOf:1,y:1};for(var n in new t)e.push(n);for(n in arguments);Ut.enumErrorProps=Bt.call(Jt,"message")||Bt.call(Jt,"name"),Ut.enumPrototypes=Bt.call(t,"prototype"),Ut.nonEnumArgs=0!=n,Ut.nonEnumShadows=!/valueOf/.test(e)}(1);var Ht=tt.internals.isObject=function(t){var e=typeof t;return t&&("function"==e||"object"==e)||!1},Xt=function(t){return t&&"object"==typeof t?Wt.call(t)==Ot:!1};Gt||(Xt=function(t){return t&&"object"==typeof t?zt.call(t,"callee"):!1});var Qt,Kt=tt.internals.isEqual=function(t,e){return m(t,e,[],[])},Yt=({}.hasOwnProperty,Array.prototype.slice),Zt=this.inherits=tt.internals.inherits=function(t,e){function n(){this.constructor=t}n.prototype=e.prototype,t.prototype=new n},te=tt.internals.addProperties=function(t){for(var e=[],n=1,r=arguments.length;r>n;n++)e.push(arguments[n]);for(var o=0,i=e.length;i>o;o++){var s=e[o];for(var u in s)t[u]=s[u]}},ee=tt.internals.addRef=function(t,e){return new qn(function(n){return new ie(e.getDisposable(),t.subscribe(n))})},ne={e:{}};S.prototype.compareTo=function(t){var e=this.value.compareTo(t.value);return 0===e&&(e=this.id-t.id),e};var re=tt.internals.PriorityQueue=function(t){this.items=new Array(t),this.length=0},oe=re.prototype;oe.isHigherPriority=function(t,e){return this.items[t].compareTo(this.items[e])<0},oe.percolate=function(t){if(!(t>=this.length||0>t)){var e=t-1>>1;if(!(0>e||e===t)&&this.isHigherPriority(t,e)){var n=this.items[t];this.items[t]=this.items[e],this.items[e]=n,this.percolate(e)}}},oe.heapify=function(t){if(+t||(t=0),!(t>=this.length||0>t)){var e=2*t+1,n=2*t+2,r=t;if(e<this.length&&this.isHigherPriority(e,r)&&(r=e),n<this.length&&this.isHigherPriority(n,r)&&(r=n),r!==t){var o=this.items[t];this.items[t]=this.items[r],this.items[r]=o,this.heapify(r)}}},oe.peek=function(){return this.items[0].value},oe.removeAt=function(t){this.items[t]=this.items[--this.length],this.items[this.length]=i,this.heapify()},oe.dequeue=function(){var t=this.peek();return this.removeAt(0),t},oe.enqueue=function(t){var e=this.length++;this.items[e]=new S(re.count++,t),this.percolate(e)},oe.remove=function(t){for(var e=0;e<this.length;e++)if(this.items[e].value===t)return this.removeAt(e),!0;return!1},re.count=0;var ie=tt.CompositeDisposable=function(){var t,e,n=[];if(Array.isArray(arguments[0]))n=arguments[0],e=n.length;else for(e=arguments.length,n=new Array(e),t=0;e>t;t++)n[t]=arguments[t];for(t=0;e>t;t++)if(!pe(n[t]))throw new TypeError("Not a disposable");this.disposables=n,this.isDisposed=!1,this.length=n.length},se=ie.prototype;se.add=function(t){this.isDisposed?t.dispose():(this.disposables.push(t),this.length++)},se.remove=function(t){var e=!1;if(!this.isDisposed){var n=this.disposables.indexOf(t);-1!==n&&(e=!0,this.disposables.splice(n,1),this.length--,t.dispose())}return e},se.dispose=function(){
3460 if(!this.isDisposed){this.isDisposed=!0;for(var t=this.disposables.length,e=new Array(t),n=0;t>n;n++)e[n]=this.disposables[n];for(this.disposables=[],this.length=0,n=0;t>n;n++)e[n].dispose()}};var ue=tt.Disposable=function(t){this.isDisposed=!1,this.action=t||et};ue.prototype.dispose=function(){this.isDisposed||(this.action(),this.isDisposed=!0)};var ae=ue.create=function(t){return new ue(t)},ce=ue.empty={dispose:et},pe=ue.isDisposable=function(t){return t&&at(t.dispose)},he=ue.checkDisposed=function(t){if(t.isDisposed)throw new vt},fe=tt.SingleAssignmentDisposable=function(){this.isDisposed=!1,this.current=null};fe.prototype.getDisposable=function(){return this.current},fe.prototype.setDisposable=function(t){if(this.current)throw new Error("Disposable has already been assigned");var e=this.isDisposed;!e&&(this.current=t),e&&t&&t.dispose()},fe.prototype.dispose=function(){if(!this.isDisposed){this.isDisposed=!0;var t=this.current;this.current=null}t&&t.dispose()};var le=tt.SerialDisposable=function(){this.isDisposed=!1,this.current=null};le.prototype.getDisposable=function(){return this.current},le.prototype.setDisposable=function(t){var e=this.isDisposed;if(!e){var n=this.current;this.current=t}n&&n.dispose(),e&&t&&t.dispose()},le.prototype.dispose=function(){if(!this.isDisposed){this.isDisposed=!0;var t=this.current;this.current=null}t&&t.dispose()};var de=tt.RefCountDisposable=function(){function t(t){this.disposable=t,this.disposable.count++,this.isInnerDisposed=!1}function e(t){this.underlyingDisposable=t,this.isDisposed=!1,this.isPrimaryDisposed=!1,this.count=0}return t.prototype.dispose=function(){this.disposable.isDisposed||this.isInnerDisposed||(this.isInnerDisposed=!0,this.disposable.count--,0===this.disposable.count&&this.disposable.isPrimaryDisposed&&(this.disposable.isDisposed=!0,this.disposable.underlyingDisposable.dispose()))},e.prototype.dispose=function(){this.isDisposed||this.isPrimaryDisposed||(this.isPrimaryDisposed=!0,0===this.count&&(this.isDisposed=!0,this.underlyingDisposable.dispose()))},e.prototype.getDisposable=function(){return this.isDisposed?ce:new t(this)},e}();E.prototype.dispose=function(){this.scheduler.scheduleWithState(this,C)};var ve=tt.internals.ScheduledItem=function(t,e,n,r,o){this.scheduler=t,this.state=e,this.action=n,this.dueTime=r,this.comparer=o||it,this.disposable=new fe};ve.prototype.invoke=function(){this.disposable.setDisposable(this.invokeCore())},ve.prototype.compareTo=function(t){return this.comparer(this.dueTime,t.dueTime)},ve.prototype.isCancelled=function(){return this.disposable.isDisposed},ve.prototype.invokeCore=function(){return this.action(this.scheduler,this.state)};var ye=tt.Scheduler=function(){function t(t,e,n,r){this.now=t,this._schedule=e,this._scheduleRelative=n,this._scheduleAbsolute=r}function e(t,e){return e(),ce}t.isScheduler=function(e){return e instanceof t};var n=t.prototype;return n.schedule=function(t){return this._schedule(t,e)},n.scheduleWithState=function(t,e){return this._schedule(t,e)},n.scheduleWithRelative=function(t,n){return this._scheduleRelative(n,t,e)},n.scheduleWithRelativeAndState=function(t,e,n){return this._scheduleRelative(t,e,n)},n.scheduleWithAbsolute=function(t,n){return this._scheduleAbsolute(n,t,e)},n.scheduleWithAbsoluteAndState=function(t,e,n){return this._scheduleAbsolute(t,e,n)},t.now=rt,t.normalize=function(t){return 0>t&&(t=0),t},t}(),be=ye.normalize,me=ye.isScheduler;!function(t){function e(t,e){function n(e){o(e,function(e){var r=!1,o=!1,s=t.scheduleWithState(e,function(t,e){return r?i.remove(s):o=!0,n(e),ce});o||(i.add(s),r=!0)})}var r=e[0],o=e[1],i=new ie;return n(r),i}function n(t,e,n){function r(e){i(e,function(e,o){var i=!1,u=!1,a=t[n](e,o,function(t,e){return i?s.remove(a):u=!0,r(e),ce});u||(s.add(a),i=!0)})}var o=e[0],i=e[1],s=new ie;return r(o),s}function r(t,e){t(function(n){e(t,n)})}t.scheduleRecursive=function(t){return this.scheduleRecursiveWithState(t,r)},t.scheduleRecursiveWithState=function(t,n){return this.scheduleWithState([t,n],e)},t.scheduleRecursiveWithRelative=function(t,e){return this.scheduleRecursiveWithRelativeAndState(e,t,r)},t.scheduleRecursiveWithRelativeAndState=function(t,e,r){return this._scheduleRelative([t,r],e,function(t,e){return n(t,e,"scheduleWithRelativeAndState")})},t.scheduleRecursiveWithAbsolute=function(t,e){return this.scheduleRecursiveWithAbsoluteAndState(e,t,r)},t.scheduleRecursiveWithAbsoluteAndState=function(t,e,r){return this._scheduleAbsolute([t,r],e,function(t,e){return n(t,e,"scheduleWithAbsoluteAndState")})}}(ye.prototype),function(t){ye.prototype.schedulePeriodic=function(t,e){return this.schedulePeriodicWithState(null,t,e)},ye.prototype.schedulePeriodicWithState=function(t,e,n){if("undefined"==typeof X.setInterval)throw new bt;e=be(e);var r=t,o=X.setInterval(function(){r=n(r)},e);return ae(function(){X.clearInterval(o)})}}(ye.prototype),function(t){t.catchError=t["catch"]=function(t){return new Ae(this,t)}}(ye.prototype);var ge,we,xe=(tt.internals.SchedulePeriodicRecursive=function(){function t(t,e){e(0,this._period);try{this._state=this._action(this._state)}catch(n){throw this._cancel.dispose(),n}}function e(t,e,n,r){this._scheduler=t,this._state=e,this._period=n,this._action=r}return e.prototype.start=function(){var e=new fe;return this._cancel=e,e.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,t.bind(this))),e},e}(),ye.immediate=function(){function t(t,e){return e(this,t)}return new ye(rt,t,wt,wt)}()),_e=ye.currentThread=function(){function t(){for(;n.length>0;){var t=n.dequeue();!t.isCancelled()&&t.invoke()}}function e(e,r){var o=new ve(this,e,r,this.now());if(n)n.enqueue(o);else{n=new re(4),n.enqueue(o);var i=x(t)();if(n=null,i===ne)return _(i.e)}return o.disposable}var n,r=new ye(rt,e,wt,wt);return r.scheduleRequired=function(){return!n},r}(),Se=function(){var t,e=et;if(X.setTimeout)t=X.setTimeout,e=X.clearTimeout;else{if(!X.WScript)throw new bt;t=function(t,e){X.WScript.Sleep(e),t()}}return{setTimeout:t,clearTimeout:e}}(),Ee=Se.setTimeout,Ce=Se.clearTimeout;!function(){function t(e){if(s)Ee(function(){t(e)},0);else{var n=i[e];if(n){s=!0;var r=x(n)();if(we(e),s=!1,r===ne)return _(r.e)}}}function n(){if(!X.postMessage||X.importScripts)return!1;var t=!1,e=X.onmessage;return X.onmessage=function(){t=!0},X.postMessage("","*"),X.onmessage=e,t}function r(e){"string"==typeof e.data&&e.data.substring(0,c.length)===c&&t(e.data.substring(c.length))}var o=1,i={},s=!1;we=function(t){delete i[t]};var u=RegExp("^"+String(Wt).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$"),a="function"==typeof(a=Z&&Y&&Z.setImmediate)&&!u.test(a)&&a;if(at(a))ge=function(e){var n=o++;return i[n]=e,a(function(){t(n)}),n};else if("undefined"!=typeof e&&"[object process]"==={}.toString.call(e))ge=function(n){var r=o++;return i[r]=n,e.nextTick(function(){t(r)}),r};else if(n()){var c="ms.rx.schedule"+Math.random();X.addEventListener?X.addEventListener("message",r,!1):X.attachEvent?X.attachEvent("onmessage",r):X.onmessage=r,ge=function(t){var e=o++;return i[e]=t,X.postMessage(c+currentId,"*"),e}}else if(X.MessageChannel){var p=new X.MessageChannel;p.port1.onmessage=function(e){t(e.data)},ge=function(t){var e=o++;return i[e]=t,p.port2.postMessage(e),e}}else ge="document"in X&&"onreadystatechange"in X.document.createElement("script")?function(e){var n=X.document.createElement("script"),r=o++;return i[r]=e,n.onreadystatechange=function(){t(r),n.onreadystatechange=null,n.parentNode.removeChild(n),n=null},X.document.documentElement.appendChild(n),r}:function(e){var n=o++;return i[n]=e,Ee(function(){t(n)},0),n}}();var Ae=(ye.timeout=ye["default"]=function(){function t(t,e){var n=this,r=new fe,o=ge(function(){!r.isDisposed&&r.setDisposable(e(n,t))});return new ie(r,ae(function(){we(o)}))}function e(t,e,n){var r=this,o=ye.normalize(e),i=new fe;if(0===o)return r.scheduleWithState(t,n);var s=Ee(function(){!i.isDisposed&&i.setDisposable(n(r,t))},o);return new ie(i,ae(function(){Ce(s)}))}function n(t,e,n){return this.scheduleWithRelativeAndState(t,e-this.now(),n)}return new ye(rt,t,e,n)}(),function(t){function e(t,e){return this._scheduler.scheduleWithState(t,this._wrap(e))}function n(t,e,n){return this._scheduler.scheduleWithRelativeAndState(t,e,this._wrap(n))}function r(t,e,n){return this._scheduler.scheduleWithAbsoluteAndState(t,e,this._wrap(n))}function o(o,i){this._scheduler=o,this._handler=i,this._recursiveOriginal=null,this._recursiveWrapper=null,t.call(this,this._scheduler.now.bind(this._scheduler),e,n,r)}return Zt(o,t),o.prototype._clone=function(t){return new o(t,this._handler)},o.prototype._wrap=function(t){var e=this;return function(n,r){try{return t(e._getRecursiveWrapper(n),r)}catch(o){if(!e._handler(o))throw o;return ce}}},o.prototype._getRecursiveWrapper=function(t){if(this._recursiveOriginal!==t){this._recursiveOriginal=t;var e=this._clone(t);e._recursiveOriginal=t,e._recursiveWrapper=e,this._recursiveWrapper=e}return this._recursiveWrapper},o.prototype.schedulePeriodicWithState=function(t,e,n){var r=this,o=!1,i=new fe;return i.setDisposable(this._scheduler.schedulePeriodicWithState(t,e,function(t){if(o)return null;try{return n(t)}catch(e){if(o=!0,!r._handler(e))throw e;return i.dispose(),null}})),i},o}(ye)),Ne=tt.Notification=function(){function t(t,e,n,r,o,i){this.kind=t,this.value=e,this.exception=n,this._accept=r,this._acceptObservable=o,this.toString=i}return t.prototype.accept=function(t,e,n){return t&&"object"==typeof t?this._acceptObservable(t):this._accept(t,e,n)},t.prototype.toObservable=function(t){var e=this;return me(t)||(t=xe),new qn(function(n){return t.scheduleWithState(e,function(t,e){e._acceptObservable(n),"N"===e.kind&&n.onCompleted()})})},t}(),ke=Ne.createOnNext=function(){function t(t){return t(this.value)}function e(t){return t.onNext(this.value)}function n(){return"OnNext("+this.value+")"}return function(r){return new Ne("N",r,null,t,e,n)}}(),Oe=Ne.createOnError=function(){function t(t,e){return e(this.exception)}function e(t){return t.onError(this.exception)}function n(){return"OnError("+this.exception+")"}return function(r){return new Ne("E",null,r,t,e,n)}}(),Pe=Ne.createOnCompleted=function(){function t(t,e,n){return n()}function e(t){return t.onCompleted()}function n(){return"OnCompleted()"}return function(){return new Ne("C",null,null,t,e,n)}}(),je=tt.Observer=function(){};je.prototype.toNotifier=function(){var t=this;return function(e){return e.accept(t)}},je.prototype.asObserver=function(){return new Me(this.onNext.bind(this),this.onError.bind(this),this.onCompleted.bind(this))},je.prototype.checked=function(){return new Te(this)};var De=je.create=function(t,e,n){return t||(t=et),e||(e=st),n||(n=et),new Me(t,e,n)};je.fromNotifier=function(t,e){return new Me(function(n){return t.call(e,ke(n))},function(n){return t.call(e,Oe(n))},function(){return t.call(e,Pe())})},je.prototype.notifyOn=function(t){return new $e(t,this)},je.prototype.makeSafe=function(t){return new AnonymousSafeObserver(this._onNext,this._onError,this._onCompleted,t)};var qe,Re=tt.internals.AbstractObserver=function(t){function e(){this.isStopped=!1,t.call(this)}return Zt(e,t),e.prototype.next=gt,e.prototype.error=gt,e.prototype.completed=gt,e.prototype.onNext=function(t){this.isStopped||this.next(t)},e.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.error(t))},e.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.completed())},e.prototype.dispose=function(){this.isStopped=!0},e.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.error(t),!0)},e}(je),Me=tt.AnonymousObserver=function(t){function e(e,n,r){t.call(this),this._onNext=e,this._onError=n,this._onCompleted=r}return Zt(e,t),e.prototype.next=function(t){this._onNext(t)},e.prototype.error=function(t){this._onError(t)},e.prototype.completed=function(){this._onCompleted()},e}(Re),Te=function(t){function e(e){t.call(this),this._observer=e,this._state=0}Zt(e,t);var n=e.prototype;return n.onNext=function(t){this.checkAccess();var e=x(this._observer.onNext).call(this._observer,t);this._state=0,e===ne&&_(e.e)},n.onError=function(t){this.checkAccess();var e=x(this._observer.onError).call(this._observer,t);this._state=2,e===ne&&_(e.e)},n.onCompleted=function(){this.checkAccess();var t=x(this._observer.onCompleted).call(this._observer);this._state=2,t===ne&&_(t.e)},n.checkAccess=function(){if(1===this._state)throw new Error("Re-entrancy detected");if(2===this._state)throw new Error("Observer completed");0===this._state&&(this._state=1)},e}(je),Ve=tt.internals.ScheduledObserver=function(t){function e(e,n){t.call(this),this.scheduler=e,this.observer=n,this.isAcquired=!1,this.hasFaulted=!1,this.queue=[],this.disposable=new le}return Zt(e,t),e.prototype.next=function(t){var e=this;this.queue.push(function(){e.observer.onNext(t)})},e.prototype.error=function(t){var e=this;this.queue.push(function(){e.observer.onError(t)})},e.prototype.completed=function(){var t=this;this.queue.push(function(){t.observer.onCompleted()})},e.prototype.ensureActive=function(){var t=!1,e=this;!this.hasFaulted&&this.queue.length>0&&(t=!this.isAcquired,this.isAcquired=!0),t&&this.disposable.setDisposable(this.scheduler.scheduleRecursive(function(t){var n;if(!(e.queue.length>0))return void(e.isAcquired=!1);n=e.queue.shift();try{n()}catch(r){throw e.queue=[],e.hasFaulted=!0,r}t()}))},e.prototype.dispose=function(){t.prototype.dispose.call(this),this.disposable.dispose()},e}(Re),$e=function(t){function e(e,n,r){t.call(this,e,n),this._cancel=r}return Zt(e,t),e.prototype.next=function(e){t.prototype.next.call(this,e),this.ensureActive()},e.prototype.error=function(e){t.prototype.error.call(this,e),this.ensureActive()},e.prototype.completed=function(){t.prototype.completed.call(this),this.ensureActive()},e.prototype.dispose=function(){t.prototype.dispose.call(this),this._cancel&&this._cancel.dispose(),this._cancel=null},e}(Ve),We=tt.Observable=function(){function t(t){if(tt.config.longStackSupport&&ct){try{throw new Error}catch(e){this.stack=e.stack.substring(e.stack.indexOf("\n")+1)}var n=this;this._subscribe=function(e){var r=e.onError.bind(e);return e.onError=function(t){a(t,n),r(t)},t.call(n,e)}}else this._subscribe=t}return qe=t.prototype,qe.subscribe=qe.forEach=function(t,e,n){return this._subscribe("object"==typeof t?t:De(t,e,n))},qe.subscribeOnNext=function(t,e){return this._subscribe(De("undefined"!=typeof e?function(n){t.call(e,n)}:t))},qe.subscribeOnError=function(t,e){return this._subscribe(De(null,"undefined"!=typeof e?function(n){t.call(e,n)}:t))},qe.subscribeOnCompleted=function(t,e){return this._subscribe(De(null,null,"undefined"!=typeof e?function(){t.call(e)}:t))},t}(),ze=tt.ObservableBase=function(t){function e(t){return t&&at(t.dispose)?t:at(t)?ae(t):ce}function n(t,n){var r=n[0],o=n[1],i=x(o.subscribeCore).call(o,r);return i!==ne||r.fail(ne.e)?void r.setDisposable(e(i)):_(ne.e)}function r(t){var e=new Rn(t),r=[e,this];return _e.scheduleRequired()?_e.scheduleWithState(r,n):n(null,r),e}function o(){t.call(this,r)}return Zt(o,t),o.prototype.subscribeCore=gt,o}(We),Ge=tt.internals.Enumerable=function(){},Je=function(t){function e(e){this.sources=e,t.call(this)}function n(t,e,n){this.o=t,this.s=e,this.e=n,this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){var e,r=new le,o=xe.scheduleRecursiveWithState(this.sources[xt](),function(o,i){if(!e){var s=x(o.next).call(o);if(s===ne)return t.onError(s.e);if(s.done)return t.onCompleted();var u=s.value;ut(u)&&(u=Xe(u));var a=new fe;r.setDisposable(a),a.setDisposable(u.subscribe(new n(t,i,o)))}});return new ie(r,o,ae(function(){e=!0}))},n.prototype.onNext=function(t){this.isStopped||this.o.onNext(t)},n.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},n.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.s(this.e))},n.prototype.dispose=function(){this.isStopped=!0},n.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},e}(ze);Ge.prototype.concat=function(){return new Je(this)};var Ie=function(t){function e(e){this.sources=e,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){var e,n=this.sources[xt](),r=new le,o=xe.scheduleRecursiveWithState(null,function(o,i){if(!e){var s=x(n.next).call(n);if(s===ne)return t.onError(s.e);if(s.done)return null!==o?t.onError(o):t.onCompleted();var u=s.value;ut(u)&&(u=Xe(u));var a=new fe;r.setDisposable(a),a.setDisposable(u.subscribe(function(e){t.onNext(e)},i,function(){t.onCompleted()}))}});return new ie(r,o,ae(function(){e=!0}))},e}(ze);Ge.prototype.catchError=function(){return new Ie(this)},Ge.prototype.catchErrorWhen=function(t){var e=this;return new qn(function(n){var r,o,i=new Tn,s=new Tn,u=t(i),a=u.subscribe(s),c=e[xt](),p=new le,h=xe.scheduleRecursive(function(t){if(!r){var e=x(c.next).call(c);if(e===ne)return n.onError(e.e);if(e.done)return void(o?n.onError(o):n.onCompleted());var u=e.value;ut(u)&&(u=Xe(u));var a=new fe,h=new fe;p.setDisposable(new ie(h,a)),a.setDisposable(u.subscribe(function(t){n.onNext(t)},function(e){h.setDisposable(s.subscribe(t,function(t){n.onError(t)},function(){n.onCompleted()})),i.onNext(e)},function(){n.onCompleted()}))}});return new ie(a,p,h,ae(function(){r=!0}))})};var Le=function(t){function e(t,e){this.v=t,this.c=null==e?-1:e}function n(t){this.v=t.v,this.l=t.c}return Zt(e,t),e.prototype[xt]=function(){return new n(this)},n.prototype.next=function(){return 0===this.l?_t:(this.l>0&&this.l--,{done:!1,value:this.v})},e}(Ge),Be=Ge.repeat=function(t,e){return new Le(t,e)},Fe=function(t){function e(t,e,n){this.s=t,this.fn=e?At(e,n,3):null}function n(t){this.i=-1,this.s=t.s,this.l=this.s.length,this.fn=t.fn}return Zt(e,t),e.prototype[xt]=function(){return new n(this)},n.prototype.next=function(){return++this.i<this.l?{done:!1,value:this.fn?this.fn(this.s[this.i],this.i,this.s):this.s[this.i]}:_t},e}(Ge),Ue=Ge.of=function(t,e,n){return new Fe(t,e,n)};qe.observeOn=function(t){var e=this;return new qn(function(n){return e.subscribe(new $e(t,n))},e)},qe.subscribeOn=function(t){var e=this;return new qn(function(n){var r=new fe,o=new le;return o.setDisposable(r),r.setDisposable(t.schedule(function(){o.setDisposable(new E(t,e.subscribe(n)))})),o},e)};var He=function(t){function e(e){this.p=e,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){return this.p.then(function(e){t.onNext(e),t.onCompleted()},function(e){t.onError(e)}),ce},e}(ze),Xe=We.fromPromise=function(t){return new He(t)};qe.toPromise=function(t){if(t||(t=tt.config.Promise),!t)throw new bt("Promise type not provided nor in Rx.config.Promise");var e=this;return new t(function(t,n){var r,o=!1;e.subscribe(function(t){r=t,o=!0},n,function(){o&&t(r)})})};var Qe=function(t){function e(e){this.source=e,t.call(this)}function n(t){this.o=t,this.a=[],this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){return this.source.subscribe(new n(t))},n.prototype.onNext=function(t){this.isStopped||this.a.push(t)},n.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},n.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.o.onNext(this.a),this.o.onCompleted())},n.prototype.dispose=function(){this.isStopped=!0},n.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},e}(ze);qe.toArray=function(){return new Qe(this)},We.create=We.createWithDisposable=function(t,e){return new qn(t,e)};var Ke=(We.defer=function(t){return new qn(function(e){var n;try{n=t()}catch(r){return dn(r).subscribe(e)}return ut(n)&&(n=Xe(n)),n.subscribe(e)})},function(t){function e(e){this.scheduler=e,t.call(this)}function n(t,e){this.observer=t,this.parent=e}function r(t,e){e.onCompleted()}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new n(t,this);return e.run()},n.prototype.run=function(){return this.parent.scheduler.scheduleWithState(this.observer,r)},e}(ze)),Ye=We.empty=function(t){return me(t)||(t=xe),new Ke(t)},Ze=function(t){function e(e,n,r){this.iterable=e,this.mapper=n,this.scheduler=r,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new tn(t,this);return e.run()},e}(ze),tn=function(){function t(t,e){this.observer=t,this.parent=e}return t.prototype.run=function(){function t(t,e){try{var i=n.next()}catch(s){return r.onError(s)}if(i.done)return r.onCompleted();var u=i.value;if(o)try{u=o(u,t)}catch(s){return r.onError(s)}r.onNext(u),e(t+1)}var e=Object(this.parent.iterable),n=j(e),r=this.observer,o=this.parent.mapper;return this.parent.scheduler.scheduleRecursiveWithState(0,t)},t}(),en=Math.pow(2,53)-1;A.prototype[xt]=function(){return new N(this._s)},N.prototype[xt]=function(){return this},N.prototype.next=function(){return this._i<this._l?{done:!1,value:this._s.charAt(this._i++)}:_t},k.prototype[xt]=function(){return new O(this._a)},O.prototype[xt]=function(){return this},O.prototype.next=function(){return this._i<this._l?{done:!1,value:this._a[this._i++]}:_t};var nn=We.from=function(t,e,n,r){if(null==t)throw new Error("iterable cannot be null.");if(e&&!at(e))throw new Error("mapFn when provided must be a function");if(e)var o=At(e,n,2);return me(r)||(r=_e),new Ze(t,o,r)},rn=function(t){function e(e,n){this.args=e,this.scheduler=n,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new R(t,this);return e.run()},e}(ze);R.prototype.run=function(){function t(t,o){r>t?(e.onNext(n[t]),o(t+1)):e.onCompleted()}var e=this.observer,n=this.parent.args,r=n.length;return this.parent.scheduler.scheduleRecursiveWithState(0,t)};var on=We.fromArray=function(t,e){return me(e)||(e=_e),new rn(t,e)};We.generate=function(t,e,n,r,o){return me(o)||(o=_e),new qn(function(i){var s=!0;return o.scheduleRecursiveWithState(t,function(t,o){var u,a;try{s?s=!1:t=n(t),u=e(t),u&&(a=r(t))}catch(c){return i.onError(c)}u?(i.onNext(a),o(t)):i.onCompleted()})})};var sn=function(t){function e(){t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){return ce},e}(ze),un=We.never=function(){return new sn};We.of=function(){for(var t=arguments.length,e=new Array(t),n=0;t>n;n++)e[n]=arguments[n];return new rn(e,_e)},We.ofWithScheduler=function(t){for(var e=arguments.length,n=new Array(e-1),r=1;e>r;r++)n[r-1]=arguments[r];return new rn(n,t)};var an=function(t){function e(e,n){this.obj=e,this.keys=Object.keys(e),this.scheduler=n,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new T(t,this);return e.run()},e}(ze);T.prototype.run=function(){function t(t,i){if(o>t){var s=r[t];e.onNext([s,n[s]]),i(t+1)}else e.onCompleted()}var e=this.observer,n=this.parent.obj,r=this.parent.keys,o=r.length;return this.parent.scheduler.scheduleRecursiveWithState(0,t)},We.pairs=function(t,e){return e||(e=_e),new an(t,e)};var cn=function(t){function e(e,n,r){this.start=e,this.rangeCount=n,this.scheduler=r,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new pn(t,this);return e.run()},e}(ze),pn=function(){function t(t,e){this.observer=t,this.parent=e}return t.prototype.run=function(){function t(t,o){n>t?(r.onNext(e+t),o(t+1)):r.onCompleted()}var e=this.parent.start,n=this.parent.rangeCount,r=this.observer;return this.parent.scheduler.scheduleRecursiveWithState(0,t)},t}();We.range=function(t,e,n){return me(n)||(n=_e),new cn(t,e,n)};var hn=function(t){function e(e,n,r){this.value=e,this.repeatCount=null==n?-1:n,this.scheduler=r,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new V(t,this);return e.run()},e}(ze);V.prototype.run=function(){function t(t,r){return(-1===t||t>0)&&(e.onNext(n),t>0&&t--),0===t?e.onCompleted():void r(t)}var e=this.observer,n=this.parent.value;return this.parent.scheduler.scheduleRecursiveWithState(this.parent.repeatCount,t)},We.repeat=function(t,e,n){return me(n)||(n=_e),new hn(t,e,n)};var fn=function(t){function e(e,n){this.value=e,this.scheduler=n,t.call(this)}function n(t,e){this.observer=t,this.parent=e}function r(t,e){var n=e[0],r=e[1];r.onNext(n),r.onCompleted()}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new n(t,this);return e.run()},n.prototype.run=function(){return this.parent.scheduler.scheduleWithState([this.parent.value,this.observer],r)},e}(ze),ln=(We["return"]=We.just=We.returnValue=function(t,e){return me(e)||(e=xe),new fn(t,e)},function(t){function e(e,n){this.error=e,this.scheduler=n,t.call(this)}function n(t,e){this.o=t,this.p=e}function r(t,e){var n=e[0],r=e[1];r.onError(n)}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new n(t,this);return e.run()},n.prototype.run=function(){return this.p.scheduler.scheduleWithState([this.p.error,this.o],r)},e}(ze)),dn=We["throw"]=We.throwError=We.throwException=function(t,e){return me(e)||(e=xe),new ln(t,e)};We.using=function(t,e){return new qn(function(n){var r,o,i=ce;try{r=t(),r&&(i=r),o=e(r)}catch(s){return new ie(dn(s).subscribe(n),i)}return new ie(o.subscribe(n),i)})},qe.amb=function(t){var e=this;return new qn(function(n){function r(){i||(i=s,c.dispose())}function o(){i||(i=u,a.dispose())}var i,s="L",u="R",a=new fe,c=new fe;return ut(t)&&(t=Xe(t)),a.setDisposable(e.subscribe(function(t){r(),i===s&&n.onNext(t)},function(t){r(),i===s&&n.onError(t)},function(){r(),i===s&&n.onCompleted()})),c.setDisposable(t.subscribe(function(t){o(),i===u&&n.onNext(t)},function(t){o(),i===u&&n.onError(t)},function(){o(),i===u&&n.onCompleted()})),new ie(a,c)})},We.amb=function(){function t(t,e){return t.amb(e)}var e=un(),n=[];if(Array.isArray(arguments[0]))n=arguments[0];else for(var r=0,o=arguments.length;o>r;r++)n.push(arguments[r]);for(var r=0,o=n.length;o>r;r++)e=t(e,n[r]);return e},qe["catch"]=qe.catchError=qe.catchException=function(t){return"function"==typeof t?$(this,t):vn([this,t])};var vn=We.catchError=We["catch"]=We.catchException=function(){var t=[];if(Array.isArray(arguments[0]))t=arguments[0];else for(var e=0,n=arguments.length;n>e;e++)t.push(arguments[e]);return Ue(t).catchError()};qe.combineLatest=function(){for(var t=arguments.length,e=new Array(t),n=0;t>n;n++)e[n]=arguments[n];return Array.isArray(e[0])?e[0].unshift(this):e.unshift(this),yn.apply(this,e)};var yn=We.combineLatest=function(){for(var t=arguments.length,e=new Array(t),n=0;t>n;n++)e[n]=arguments[n];var r=e.pop();return Array.isArray(e[0])&&(e=e[0]),new qn(function(t){function n(e){if(u[e]=!0,a||(a=u.every(nt))){try{var n=r.apply(null,p)}catch(o){return t.onError(o)}t.onNext(n)}else c.filter(function(t,n){return n!==e}).every(nt)&&t.onCompleted()}function o(e){c[e]=!0,c.every(nt)&&t.onCompleted()}for(var i=e.length,s=function(){return!1},u=g(i,s),a=!1,c=g(i,s),p=new Array(i),h=new Array(i),f=0;i>f;f++)!function(r){var i=e[r],s=new fe;ut(i)&&(i=Xe(i)),s.setDisposable(i.subscribe(function(t){p[r]=t,n(r)},function(e){t.onError(e)},function(){o(r)})),h[r]=s}(f);return new ie(h)},this)};qe.concat=function(){for(var t=[],e=0,n=arguments.length;n>e;e++)t.push(arguments[e]);return t.unshift(this),mn.apply(null,t)};var bn=function(t){function e(e){this.sources=e,t.call(this)}function n(t,e){this.sources=t,this.o=e}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new n(this.sources,t);return e.run()},n.prototype.run=function(){var t,e=new le,n=this.sources,r=n.length,o=this.o,i=xe.scheduleRecursiveWithState(0,function(i,s){if(!t){if(i===r)return o.onCompleted();var u=n[i];ut(u)&&(u=Xe(u));var a=new fe;e.setDisposable(a),a.setDisposable(u.subscribe(function(t){o.onNext(t)},function(t){o.onError(t)},function(){s(i+1)}))}});return new ie(e,i,ae(function(){t=!0}))},e}(ze),mn=We.concat=function(){var t;if(Array.isArray(arguments[0]))t=arguments[0];else{t=new Array(arguments.length);for(var e=0,n=arguments.length;n>e;e++)t[e]=arguments[e]}return new bn(t)};qe.concatAll=qe.concatObservable=function(){return this.merge(1)};var gn=function(t){function e(e,n){this.source=e,this.maxConcurrent=n,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new ie;return e.add(this.source.subscribe(new wn(t,this.maxConcurrent,e))),e},e}(ze),wn=function(){function t(t,e,n){this.o=t,this.max=e,this.g=n,this.done=!1,this.q=[],this.activeCount=0,this.isStopped=!1}function e(t,e){this.parent=t,this.sad=e,this.isStopped=!1}return t.prototype.handleSubscribe=function(t){var n=new fe;this.g.add(n),ut(t)&&(t=Xe(t)),n.setDisposable(t.subscribe(new e(this,n)))},t.prototype.onNext=function(t){this.isStopped||(this.activeCount<this.max?(this.activeCount++,this.handleSubscribe(t)):this.q.push(t))},t.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},t.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.done=!0,0===this.activeCount&&this.o.onCompleted())},t.prototype.dispose=function(){this.isStopped=!0},t.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},e.prototype.onNext=function(t){this.isStopped||this.parent.o.onNext(t)},e.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.parent.o.onError(t))},e.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=!0;var t=this.parent;t.g.remove(this.sad),t.q.length>0?t.handleSubscribe(t.q.shift()):(t.activeCount--,t.done&&0===t.activeCount&&t.o.onCompleted())}},e.prototype.dispose=function(){this.isStopped=!0},e.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.parent.o.onError(t),!0)},t}();qe.merge=function(t){return"number"!=typeof t?xn(this,t):new gn(this,t)};var xn=We.merge=function(){var t,e,n=[],r=arguments.length;if(arguments[0])if(me(arguments[0]))for(t=arguments[0],e=1;r>e;e++)n.push(arguments[e]);else for(t=xe,e=0;r>e;e++)n.push(arguments[e]);else for(t=xe,e=1;r>e;e++)n.push(arguments[e]);return Array.isArray(n[0])&&(n=n[0]),M(t,n).mergeAll()},_n=tt.CompositeError=function(t){this.name="NotImplementedError",this.innerErrors=t,this.message="This contains multiple errors. Check the innerErrors",Error.call(this)};_n.prototype=Error.prototype,We.mergeDelayError=function(){var t;if(Array.isArray(arguments[0]))t=arguments[0];else{var e=arguments.length;t=new Array(e);for(var n=0;e>n;n++)t[n]=arguments[n]}var r=M(null,t);return new qn(function(t){function e(){0===s.length?t.onCompleted():1===s.length?t.onError(s[0]):t.onError(new _n(s))}var n=new ie,o=new fe,i=!1,s=[];return n.add(o),o.setDisposable(r.subscribe(function(r){var o=new fe;n.add(o),ut(r)&&(r=Xe(r)),o.setDisposable(r.subscribe(function(e){t.onNext(e)},function(t){s.push(t),n.remove(o),i&&1===n.length&&e()},function(){n.remove(o),i&&1===n.length&&e()}))},function(t){s.push(t),i=!0,1===n.length&&e()},function(){i=!0,1===n.length&&e()})),n})};var Sn=function(t){function e(e){this.source=e,t.call(this)}function n(t,e){this.o=t,this.g=e,this.isStopped=!1,this.done=!1}function r(t,e,n){this.parent=t,this.g=e,this.sad=n,this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new ie,r=new fe;return e.add(r),r.setDisposable(this.source.subscribe(new n(t,e))),e},n.prototype.onNext=function(t){if(!this.isStopped){var e=new fe;this.g.add(e),ut(t)&&(t=Xe(t)),e.setDisposable(t.subscribe(new r(this,this.g,e)))}},n.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},n.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.done=!0,1===this.g.length&&this.o.onCompleted())},n.prototype.dispose=function(){this.isStopped=!0},n.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},r.prototype.onNext=function(t){this.isStopped||this.parent.o.onNext(t)},r.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.parent.o.onError(t))},r.prototype.onCompleted=function(){if(!this.isStopped){var t=this.parent;this.isStopped=!0,t.g.remove(this.sad),t.done&&1===t.g.length&&t.o.onCompleted()}},r.prototype.dispose=function(){this.isStopped=!0},r.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.parent.o.onError(t),!0)},e}(ze);qe.mergeAll=qe.mergeObservable=function(){
3461 return new Sn(this)},qe.onErrorResumeNext=function(t){if(!t)throw new Error("Second observable is required");return En([this,t])};var En=We.onErrorResumeNext=function(){var t=[];if(Array.isArray(arguments[0]))t=arguments[0];else for(var e=0,n=arguments.length;n>e;e++)t.push(arguments[e]);return new qn(function(e){var n=0,r=new le,o=xe.scheduleRecursive(function(o){var i,s;n<t.length?(i=t[n++],ut(i)&&(i=Xe(i)),s=new fe,r.setDisposable(s),s.setDisposable(i.subscribe(e.onNext.bind(e),o,o))):e.onCompleted()});return new ie(r,o)})};qe.skipUntil=function(t){var e=this;return new qn(function(n){var r=!1,o=new ie(e.subscribe(function(t){r&&n.onNext(t)},function(t){n.onError(t)},function(){r&&n.onCompleted()}));ut(t)&&(t=Xe(t));var i=new fe;return o.add(i),i.setDisposable(t.subscribe(function(){r=!0,i.dispose()},function(t){n.onError(t)},function(){i.dispose()})),o},e)};var Cn=function(t){function e(e){this.source=e,t.call(this)}function n(t,e){this.o=t,this.inner=e,this.stopped=!1,this.latest=0,this.hasLatest=!1,this.isStopped=!1}function r(t,e){this.parent=t,this.id=e,this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){var e=new le,r=this.source.subscribe(new n(t,e));return new ie(r,e)},n.prototype.onNext=function(t){if(!this.isStopped){var e=new fe,n=++this.latest;this.hasLatest=!0,this.inner.setDisposable(e),ut(t)&&(t=Xe(t)),e.setDisposable(t.subscribe(new r(this,n)))}},n.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},n.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.stopped=!0,!this.hasLatest&&this.o.onCompleted())},n.prototype.dispose=function(){this.isStopped=!0},n.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},r.prototype.onNext=function(t){this.isStopped||this.parent.latest===this.id&&this.parent.o.onNext(t)},r.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.parent.latest===this.id&&this.parent.o.onError(t))},r.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.parent.latest===this.id&&(this.parent.hasLatest=!1,this.parent.isStopped&&this.parent.o.onCompleted()))},r.prototype.dispose=function(){this.isStopped=!0},r.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.parent.o.onError(t),!0)},e}(ze);qe["switch"]=qe.switchLatest=function(){return new Cn(this)};var An=function(t){function e(e,n){this.source=e,this.other=ut(n)?Xe(n):n,t.call(this)}function n(t){this.o=t,this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){return new ie(this.source.subscribe(t),this.other.subscribe(new n(t)))},n.prototype.onNext=function(t){this.isStopped||this.o.onCompleted()},n.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},n.prototype.onCompleted=function(){!this.isStopped&&(this.isStopped=!0)},n.prototype.dispose=function(){this.isStopped=!0},n.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},e}(ze);qe.takeUntil=function(t){return new An(this,t)},qe.withLatestFrom=function(){for(var t=arguments.length,e=new Array(t),n=0;t>n;n++)e[n]=arguments[n];var r=e.pop(),o=this;return Array.isArray(e[0])&&(e=e[0]),new qn(function(t){for(var n=e.length,i=g(n,W),s=!1,u=new Array(n),a=new Array(n+1),c=0;n>c;c++)!function(n){var r=e[n],o=new fe;ut(r)&&(r=Xe(r)),o.setDisposable(r.subscribe(function(t){u[n]=t,i[n]=!0,s=i.every(nt)},function(e){t.onError(e)},et)),a[n]=o}(c);var p=new fe;return p.setDisposable(o.subscribe(function(e){var n=[e].concat(u);if(s){var o=x(r).apply(null,n);return o===ne?t.onError(o.e):void t.onNext(o)}},function(e){t.onError(e)},function(){t.onCompleted()})),a[n]=p,new ie(a)},this)},qe.zip=function(){if(Array.isArray(arguments[0]))return z.apply(this,arguments);for(var t=arguments.length,e=new Array(t),n=0;t>n;n++)e[n]=arguments[n];var r=this,o=e.pop();return e.unshift(r),new qn(function(t){for(var n=e.length,i=g(n,G),s=g(n,W),u=new Array(n),a=0;n>a;a++)!function(n){var a=e[n],c=new fe;ut(a)&&(a=Xe(a)),c.setDisposable(a.subscribe(function(e){if(i[n].push(e),i.every(function(t){return t.length>0})){var u=i.map(function(t){return t.shift()}),a=x(o).apply(r,u);if(a===ne)return t.onError(a.e);t.onNext(a)}else s.filter(function(t,e){return e!==n}).every(nt)&&t.onCompleted()},function(e){t.onError(e)},function(){s[n]=!0,s.every(nt)&&t.onCompleted()})),u[n]=c}(a);return new ie(u)},r)},We.zip=function(){for(var t=arguments.length,e=new Array(t),n=0;t>n;n++)e[n]=arguments[n];var r=e.shift();return r.zip.apply(r,e)},We.zipArray=function(){var t;if(Array.isArray(arguments[0]))t=arguments[0];else{var e=arguments.length;t=new Array(e);for(var n=0;e>n;n++)t[n]=arguments[n]}return new qn(function(e){for(var n=t.length,r=g(n,J),o=g(n,W),i=new Array(n),s=0;n>s;s++)!function(n){i[n]=new fe,i[n].setDisposable(t[n].subscribe(function(t){if(r[n].push(t),r.every(function(t){return t.length>0})){var i=r.map(function(t){return t.shift()});e.onNext(i)}else if(o.filter(function(t,e){return e!==n}).every(nt))return e.onCompleted()},function(t){e.onError(t)},function(){o[n]=!0,o.every(nt)&&e.onCompleted()}))}(s);return new ie(i)})},qe.asObservable=function(){var t=this;return new qn(function(e){return t.subscribe(e)},t)},qe.bufferWithCount=function(t,e){return"number"!=typeof e&&(e=t),this.windowWithCount(t,e).selectMany(function(t){return t.toArray()}).where(function(t){return t.length>0})},qe.dematerialize=function(){var t=this;return new qn(function(e){return t.subscribe(function(t){return t.accept(e)},function(t){e.onError(t)},function(){e.onCompleted()})},this)},qe.distinctUntilChanged=function(t,e){var n=this;return e||(e=ot),new qn(function(r){var o,i=!1;return n.subscribe(function(n){var s=n;if(t&&(s=x(t)(n),s===ne))return r.onError(s.e);if(i){var u=x(e)(o,s);if(u===ne)return r.onError(u.e)}i&&u||(i=!0,o=s,r.onNext(n))},function(t){r.onError(t)},function(){r.onCompleted()})},this)};var Nn=function(t){function e(e,n,r,o){this.source=e,this.t=!n||at(n)?De(n||et,r||et,o||et):n,t.call(this)}function n(t,e){this.o=t,this.t=e,this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){return this.source.subscribe(new n(t,this.t))},n.prototype.onNext=function(t){if(!this.isStopped){var e=x(this.t.onNext).call(this.t,t);e===ne&&this.o.onError(e.e),this.o.onNext(t)}},n.prototype.onError=function(t){if(!this.isStopped){this.isStopped=!0;var e=x(this.t.onError).call(this.t,t);if(e===ne)return this.o.onError(e.e);this.o.onError(t)}},n.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=!0;var t=x(this.t.onCompleted).call(this.t);if(t===ne)return this.o.onError(t.e);this.o.onCompleted()}},n.prototype.dispose=function(){this.isStopped=!0},n.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},e}(ze);qe["do"]=qe.tap=qe.doAction=function(t,e,n){return new Nn(this,t,e,n)},qe.doOnNext=qe.tapOnNext=function(t,e){return this.tap("undefined"!=typeof e?function(n){t.call(e,n)}:t)},qe.doOnError=qe.tapOnError=function(t,e){return this.tap(et,"undefined"!=typeof e?function(n){t.call(e,n)}:t)},qe.doOnCompleted=qe.tapOnCompleted=function(t,e){return this.tap(et,null,"undefined"!=typeof e?function(){t.call(e)}:t)},qe["finally"]=qe.ensure=function(t){var e=this;return new qn(function(n){var r;try{r=e.subscribe(n)}catch(o){throw t(),o}return ae(function(){try{r.dispose()}catch(e){throw e}finally{t()}})},this)},qe.finallyAction=function(t){return this.ensure(t)};var kn=function(t){function e(e){this.source=e,t.call(this)}function n(t){this.o=t,this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){return this.source.subscribe(new n(t))},n.prototype.onNext=et,n.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},n.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.o.onCompleted())},n.prototype.dispose=function(){this.isStopped=!0},n.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.observer.onError(t),!0)},e}(ze);qe.ignoreElements=function(){return new kn(this)},qe.materialize=function(){var t=this;return new qn(function(e){return t.subscribe(function(t){e.onNext(ke(t))},function(t){e.onNext(Oe(t)),e.onCompleted()},function(){e.onNext(Pe()),e.onCompleted()})},t)},qe.repeat=function(t){return Be(this,t).concat()},qe.retry=function(t){return Be(this,t).catchError()},qe.retryWhen=function(t){return Be(this).catchErrorWhen(t)};var On=function(t){function e(e,n,r,o){this.source=e,this.accumulator=n,this.hasSeed=r,this.seed=o,t.call(this)}return Zt(e,t),e.prototype.subscribeCore=function(t){return this.source.subscribe(new I(t,this))},e}(ze);I.prototype.onNext=function(t){if(!this.isStopped){!this.hasValue&&(this.hasValue=!0);try{this.hasAccumulation?this.accumulation=this.accumulator(this.accumulation,t):(this.accumulation=this.hasSeed?this.accumulator(this.seed,t):t,this.hasAccumulation=!0)}catch(e){return this.observer.onError(e)}this.observer.onNext(this.accumulation)}},I.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.observer.onError(t))},I.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,!this.hasValue&&this.hasSeed&&this.observer.onNext(this.seed),this.observer.onCompleted())},I.prototype.dispose=function(){this.isStopped=!0},I.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.observer.onError(t),!0)},qe.scan=function(){var t,e,n=!1;return 2===arguments.length?(n=!0,t=arguments[0],e=arguments[1]):e=arguments[0],new On(this,e,n,t)},qe.skipLast=function(t){if(0>t)throw new yt;var e=this;return new qn(function(n){var r=[];return e.subscribe(function(e){r.push(e),r.length>t&&n.onNext(r.shift())},function(t){n.onError(t)},function(){n.onCompleted()})},e)},qe.startWith=function(){var t,e=0;arguments.length&&me(arguments[0])?(t=arguments[0],e=1):t=xe;for(var n=[],r=e,o=arguments.length;o>r;r++)n.push(arguments[r]);return Ue([on(n,t),this]).concat()},qe.takeLast=function(t){if(0>t)throw new yt;var e=this;return new qn(function(n){var r=[];return e.subscribe(function(e){r.push(e),r.length>t&&r.shift()},function(t){n.onError(t)},function(){for(;r.length>0;)n.onNext(r.shift());n.onCompleted()})},e)},qe.takeLastBuffer=function(t){var e=this;return new qn(function(n){var r=[];return e.subscribe(function(e){r.push(e),r.length>t&&r.shift()},function(t){n.onError(t)},function(){n.onNext(r),n.onCompleted()})},e)},qe.windowWithCount=function(t,e){var n=this;if(+t||(t=0),Math.abs(t)===1/0&&(t=0),0>=t)throw new yt;if(null==e&&(e=t),+e||(e=0),Math.abs(e)===1/0&&(e=0),0>=e)throw new yt;return new qn(function(r){function o(){var t=new Tn;a.push(t),r.onNext(ee(t,s))}var i=new fe,s=new de(i),u=0,a=[];return o(),i.setDisposable(n.subscribe(function(n){for(var r=0,i=a.length;i>r;r++)a[r].onNext(n);var s=u-t+1;s>=0&&s%e===0&&a.shift().onCompleted(),++u%e===0&&o()},function(t){for(;a.length>0;)a.shift().onError(t);r.onError(t)},function(){for(;a.length>0;)a.shift().onCompleted();r.onCompleted()})),s},n)},qe.selectConcat=qe.concatMap=function(t,e,n){return at(t)&&at(e)?this.concatMap(function(n,r){var o=t(n,r);return ut(o)&&(o=Xe(o)),(Et(o)||St(o))&&(o=nn(o)),o.map(function(t,o){return e(n,t,r,o)})}):at(t)?L(this,t,n):L(this,function(){return t})},qe.concatMapObserver=qe.selectConcatObserver=function(t,e,n,r){var o=this,i=At(t,r,2),s=At(e,r,1),u=At(n,r,0);return new qn(function(t){var e=0;return o.subscribe(function(n){var r;try{r=i(n,e++)}catch(o){return void t.onError(o)}ut(r)&&(r=Xe(r)),t.onNext(r)},function(e){var n;try{n=s(e)}catch(r){return void t.onError(r)}ut(n)&&(n=Xe(n)),t.onNext(n),t.onCompleted()},function(){var e;try{e=u()}catch(n){return void t.onError(n)}ut(e)&&(e=Xe(e)),t.onNext(e),t.onCompleted()})},this).concatAll()},qe.defaultIfEmpty=function(t){var e=this;return t===i&&(t=null),new qn(function(n){var r=!1;return e.subscribe(function(t){r=!0,n.onNext(t)},function(t){n.onError(t)},function(){!r&&n.onNext(t),n.onCompleted()})},e)},F.prototype.push=function(t){var e=-1===B(this.set,t,this.comparer);return e&&this.set.push(t),e},qe.distinct=function(t,e){var n=this;return e||(e=ot),new qn(function(r){var o=new F(e);return n.subscribe(function(e){var n=e;if(t)try{n=t(e)}catch(i){return void r.onError(i)}o.push(n)&&r.onNext(e)},function(t){r.onError(t)},function(){r.onCompleted()})},this)};var Pn=function(t){function e(e,n,r){this.source=e,this.selector=At(n,r,3),t.call(this)}function n(t,e){return function(n,r,o){return t.call(this,e.selector(n,r,o),r,o)}}function r(t,e,n){this.o=t,this.selector=e,this.source=n,this.i=0,this.isStopped=!1}return Zt(e,t),e.prototype.internalMap=function(t,r){return new e(this.source,n(t,this),r)},e.prototype.subscribeCore=function(t){return this.source.subscribe(new r(t,this.selector,this))},r.prototype.onNext=function(t){if(!this.isStopped){var e=x(this.selector)(t,this.i++,this.source);return e===ne?this.o.onError(e.e):void this.o.onNext(e)}},r.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},r.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.o.onCompleted())},r.prototype.dispose=function(){this.isStopped=!0},r.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},e}(ze);qe.map=qe.select=function(t,e){var n="function"==typeof t?t:function(){return t};return this instanceof Pn?this.internalMap(n,e):new Pn(this,n,e)},qe.pluck=function(){var t=arguments,e=arguments.length;if(0===e)throw new Error("List of properties cannot be empty.");return this.map(function(n){for(var r=n,o=0;e>o;o++){var s=r[t[o]];if("undefined"==typeof s)return i;r=s}return r})},qe.flatMapObserver=qe.selectManyObserver=function(t,e,n,r){var o=this;return new qn(function(i){var s=0;return o.subscribe(function(e){var n;try{n=t.call(r,e,s++)}catch(o){return void i.onError(o)}ut(n)&&(n=Xe(n)),i.onNext(n)},function(t){var n;try{n=e.call(r,t)}catch(o){return void i.onError(o)}ut(n)&&(n=Xe(n)),i.onNext(n),i.onCompleted()},function(){var t;try{t=n.call(r)}catch(e){return void i.onError(e)}ut(t)&&(t=Xe(t)),i.onNext(t),i.onCompleted()})},o).mergeAll()},qe.selectMany=qe.flatMap=function(t,e,n){return at(t)&&at(e)?this.flatMap(function(n,r){var o=t(n,r);return ut(o)&&(o=Xe(o)),(Et(o)||St(o))&&(o=nn(o)),o.map(function(t,o){return e(n,t,r,o)})},n):at(t)?U(this,t,n):U(this,function(){return t})},qe.selectSwitch=qe.flatMapLatest=qe.switchMap=function(t,e){return this.select(t,e).switchLatest()};var jn=function(t){function e(e,n){this.source=e,this.skipCount=n,t.call(this)}function n(t,e){this.c=e,this.r=e,this.o=t,this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){return this.source.subscribe(new n(t,this.skipCount))},n.prototype.onNext=function(t){this.isStopped||(this.r<=0?this.o.onNext(t):this.r--)},n.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},n.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.o.onCompleted())},n.prototype.dispose=function(){this.isStopped=!0},n.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},e}(ze);qe.skip=function(t){if(0>t)throw new yt;return new jn(this,t)},qe.skipWhile=function(t,e){var n=this,r=At(t,e,3);return new qn(function(t){var e=0,o=!1;return n.subscribe(function(i){if(!o)try{o=!r(i,e++,n)}catch(s){return void t.onError(s)}o&&t.onNext(i)},function(e){t.onError(e)},function(){t.onCompleted()})},n)},qe.take=function(t,e){if(0>t)throw new yt;if(0===t)return Ye(e);var n=this;return new qn(function(e){var r=t;return n.subscribe(function(t){r-- >0&&(e.onNext(t),0>=r&&e.onCompleted())},function(t){e.onError(t)},function(){e.onCompleted()})},n)},qe.takeWhile=function(t,e){var n=this,r=At(t,e,3);return new qn(function(t){var e=0,o=!0;return n.subscribe(function(i){if(o){try{o=r(i,e++,n)}catch(s){return void t.onError(s)}o?t.onNext(i):t.onCompleted()}},function(e){t.onError(e)},function(){t.onCompleted()})},n)};var Dn=function(t){function e(e,n,r){this.source=e,this.predicate=At(n,r,3),t.call(this)}function n(t,e){return function(n,r,o){return e.predicate(n,r,o)&&t.call(this,n,r,o)}}function r(t,e,n){this.o=t,this.predicate=e,this.source=n,this.i=0,this.isStopped=!1}return Zt(e,t),e.prototype.subscribeCore=function(t){return this.source.subscribe(new r(t,this.predicate,this))},e.prototype.internalFilter=function(t,r){return new e(this.source,n(t,this),r)},r.prototype.onNext=function(t){if(!this.isStopped){var e=x(this.predicate)(t,this.i++,this.source);return e===ne?this.o.onError(e.e):void(e&&this.o.onNext(t))}},r.prototype.onError=function(t){this.isStopped||(this.isStopped=!0,this.o.onError(t))},r.prototype.onCompleted=function(){this.isStopped||(this.isStopped=!0,this.o.onCompleted())},r.prototype.dispose=function(){this.isStopped=!0},r.prototype.fail=function(t){return this.isStopped?!1:(this.isStopped=!0,this.o.onError(t),!0)},e}(ze);qe.filter=qe.where=function(t,e){return this instanceof Dn?this.internalFilter(t,e):new Dn(this,t,e)},qe.transduce=function(t){function e(t){return{"@@transducer/init":function(){return t},"@@transducer/step":function(t,e){return t.onNext(e)},"@@transducer/result":function(t){return t.onCompleted()}}}var n=this;return new qn(function(r){var o=t(e(r));return n.subscribe(function(t){try{o["@@transducer/step"](r,t)}catch(e){r.onError(e)}},function(t){r.onError(t)},function(){o["@@transducer/result"](r)})},n)};var qn=tt.AnonymousObservable=function(t){function e(t){return t&&at(t.dispose)?t:at(t)?ae(t):ce}function n(t,n){var r=n[0],o=n[1],i=x(o)(r);return i!==ne||r.fail(ne.e)?void r.setDisposable(e(i)):_(ne.e)}function r(e,r){function o(t){var r=new Rn(t),o=[r,e];return _e.scheduleRequired()?_e.scheduleWithState(o,n):n(null,o),r}this.source=r,t.call(this,o)}return Zt(r,t),r}(We),Rn=function(t){function e(e){t.call(this),this.observer=e,this.m=new fe}Zt(e,t);var n=e.prototype;return n.next=function(t){var e=x(this.observer.onNext).call(this.observer,t);e===ne&&(this.dispose(),_(e.e))},n.error=function(t){var e=x(this.observer.onError).call(this.observer,t);this.dispose(),e===ne&&_(e.e)},n.completed=function(){var t=x(this.observer.onCompleted).call(this.observer);this.dispose(),t===ne&&_(t.e)},n.setDisposable=function(t){this.m.setDisposable(t)},n.getDisposable=function(){return this.m.getDisposable()},n.dispose=function(){t.prototype.dispose.call(this),this.m.dispose()},e}(Re),Mn=function(t,e){this.subject=t,this.observer=e};Mn.prototype.dispose=function(){if(!this.subject.isDisposed&&null!==this.observer){var t=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(t,1),this.observer=null}};var Tn=tt.Subject=function(t){function e(t){return he(this),this.isStopped?this.hasError?(t.onError(this.error),ce):(t.onCompleted(),ce):(this.observers.push(t),new Mn(this,t))}function n(){t.call(this,e),this.isDisposed=!1,this.isStopped=!1,this.observers=[],this.hasError=!1}return Zt(n,t),te(n.prototype,je.prototype,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){if(he(this),!this.isStopped){this.isStopped=!0;for(var t=0,e=u(this.observers),n=e.length;n>t;t++)e[t].onCompleted();this.observers.length=0}},onError:function(t){if(he(this),!this.isStopped){this.isStopped=!0,this.error=t,this.hasError=!0;for(var e=0,n=u(this.observers),r=n.length;r>e;e++)n[e].onError(t);this.observers.length=0}},onNext:function(t){if(he(this),!this.isStopped)for(var e=0,n=u(this.observers),r=n.length;r>e;e++)n[e].onNext(t)},dispose:function(){this.isDisposed=!0,this.observers=null}}),n.create=function(t,e){return new Vn(t,e)},n}(We),Vn=(tt.AsyncSubject=function(t){function e(t){return he(this),this.isStopped?(this.hasError?t.onError(this.error):this.hasValue?(t.onNext(this.value),t.onCompleted()):t.onCompleted(),ce):(this.observers.push(t),new Mn(this,t))}function n(){t.call(this,e),this.isDisposed=!1,this.isStopped=!1,this.hasValue=!1,this.observers=[],this.hasError=!1}return Zt(n,t),te(n.prototype,je,{hasObservers:function(){return he(this),this.observers.length>0},onCompleted:function(){var t,e;if(he(this),!this.isStopped){this.isStopped=!0;var n=u(this.observers),e=n.length;if(this.hasValue)for(t=0;e>t;t++){var r=n[t];r.onNext(this.value),r.onCompleted()}else for(t=0;e>t;t++)n[t].onCompleted();this.observers.length=0}},onError:function(t){if(he(this),!this.isStopped){this.isStopped=!0,this.hasError=!0,this.error=t;for(var e=0,n=u(this.observers),r=n.length;r>e;e++)n[e].onError(t);this.observers.length=0}},onNext:function(t){he(this),this.isStopped||(this.value=t,this.hasValue=!0)},dispose:function(){this.isDisposed=!0,this.observers=null,this.exception=null,this.value=null}}),n}(We),tt.AnonymousSubject=function(t){function e(t){return this.observable.subscribe(t)}function n(n,r){this.observer=n,this.observable=r,t.call(this,e)}return Zt(n,t),te(n.prototype,je.prototype,{onCompleted:function(){this.observer.onCompleted()},onError:function(t){this.observer.onError(t)},onNext:function(t){this.observer.onNext(t)}}),n}(We));"function"==typeof t&&"object"==typeof t.amd&&t.amd?(X.Rx=tt,t(function(){return tt})):Q&&K?Y?(K.exports=tt).Rx=tt:Q.Rx=tt:X.Rx=tt;var $n=f()}).call(this)}).call(this,e(150),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{150:150}]},{},[1])(1)});
3462 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3463
3464 },{}],16:[function(require,module,exports){
3465 (function (global){
3466 var topLevel = typeof global !== 'undefined' ? global :
3467     typeof window !== 'undefined' ? window : {}
3468 var minDoc = require('min-document');
3469
3470 var doccy;
3471
3472 if (typeof document !== 'undefined') {
3473     doccy = document;
3474 } else {
3475     doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'];
3476
3477     if (!doccy) {
3478         doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc;
3479     }
3480 }
3481
3482 module.exports = doccy;
3483
3484 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3485
3486 },{"min-document":4}],17:[function(require,module,exports){
3487 exports.read = function (buffer, offset, isLE, mLen, nBytes) {
3488   var e, m
3489   var eLen = nBytes * 8 - mLen - 1
3490   var eMax = (1 << eLen) - 1
3491   var eBias = eMax >> 1
3492   var nBits = -7
3493   var i = isLE ? (nBytes - 1) : 0
3494   var d = isLE ? -1 : 1
3495   var s = buffer[offset + i]
3496
3497   i += d
3498
3499   e = s & ((1 << (-nBits)) - 1)
3500   s >>= (-nBits)
3501   nBits += eLen
3502   for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
3503
3504   m = e & ((1 << (-nBits)) - 1)
3505   e >>= (-nBits)
3506   nBits += mLen
3507   for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
3508
3509   if (e === 0) {
3510     e = 1 - eBias
3511   } else if (e === eMax) {
3512     return m ? NaN : ((s ? -1 : 1) * Infinity)
3513   } else {
3514     m = m + Math.pow(2, mLen)
3515     e = e - eBias
3516   }
3517   return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
3518 }
3519
3520 exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
3521   var e, m, c
3522   var eLen = nBytes * 8 - mLen - 1
3523   var eMax = (1 << eLen) - 1
3524   var eBias = eMax >> 1
3525   var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
3526   var i = isLE ? 0 : (nBytes - 1)
3527   var d = isLE ? 1 : -1
3528   var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
3529
3530   value = Math.abs(value)
3531
3532   if (isNaN(value) || value === Infinity) {
3533     m = isNaN(value) ? 1 : 0
3534     e = eMax
3535   } else {
3536     e = Math.floor(Math.log(value) / Math.LN2)
3537     if (value * (c = Math.pow(2, -e)) < 1) {
3538       e--
3539       c *= 2
3540     }
3541     if (e + eBias >= 1) {
3542       value += rt / c
3543     } else {
3544       value += rt * Math.pow(2, 1 - eBias)
3545     }
3546     if (value * c >= 2) {
3547       e++
3548       c /= 2
3549     }
3550
3551     if (e + eBias >= eMax) {
3552       m = 0
3553       e = eMax
3554     } else if (e + eBias >= 1) {
3555       m = (value * c - 1) * Math.pow(2, mLen)
3556       e = e + eBias
3557     } else {
3558       m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
3559       e = 0
3560     }
3561   }
3562
3563   for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
3564
3565   e = (e << mLen) | m
3566   eLen += mLen
3567   for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
3568
3569   buffer[offset + i - d] |= s * 128
3570 }
3571
3572 },{}],18:[function(require,module,exports){
3573 (function (global){
3574 'use strict';
3575
3576 /*global window, global*/
3577
3578 var root = typeof window !== 'undefined' ?
3579     window : typeof global !== 'undefined' ?
3580     global : {};
3581
3582 module.exports = Individual;
3583
3584 function Individual(key, value) {
3585     if (key in root) {
3586         return root[key];
3587     }
3588
3589     root[key] = value;
3590
3591     return value;
3592 }
3593
3594 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
3595
3596 },{}],19:[function(require,module,exports){
3597 'use strict';
3598
3599 var Individual = require('./index.js');
3600
3601 module.exports = OneVersion;
3602
3603 function OneVersion(moduleName, version, defaultValue) {
3604     var key = '__INDIVIDUAL_ONE_VERSION_' + moduleName;
3605     var enforceKey = key + '_ENFORCE_SINGLETON';
3606
3607     var versionValue = Individual(enforceKey, version);
3608
3609     if (versionValue !== version) {
3610         throw new Error('Can only have one copy of ' +
3611             moduleName + '.\n' +
3612             'You already have version ' + versionValue +
3613             ' installed.\n' +
3614             'This means you cannot install version ' + version);
3615     }
3616
3617     return Individual(key, defaultValue);
3618 }
3619
3620 },{"./index.js":18}],20:[function(require,module,exports){
3621 "use strict";
3622
3623 module.exports = function isObject(x) {
3624         return typeof x === "object" && x !== null;
3625 };
3626
3627 },{}],21:[function(require,module,exports){
3628 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
3629 /* Geohash encoding/decoding and associated functions   (c) Chris Veness 2014-2016 / MIT Licence  */
3630 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
3631
3632 'use strict';
3633
3634
3635 /**
3636  * Geohash encode, decode, bounds, neighbours.
3637  *
3638  * @namespace
3639  */
3640 var Geohash = {};
3641
3642 /* (Geohash-specific) Base32 map */
3643 Geohash.base32 = '0123456789bcdefghjkmnpqrstuvwxyz';
3644
3645 /**
3646  * Encodes latitude/longitude to geohash, either to specified precision or to automatically
3647  * evaluated precision.
3648  *
3649  * @param   {number} lat - Latitude in degrees.
3650  * @param   {number} lon - Longitude in degrees.
3651  * @param   {number} [precision] - Number of characters in resulting geohash.
3652  * @returns {string} Geohash of supplied latitude/longitude.
3653  * @throws  Invalid geohash.
3654  *
3655  * @example
3656  *     var geohash = Geohash.encode(52.205, 0.119, 7); // geohash: 'u120fxw'
3657  */
3658 Geohash.encode = function(lat, lon, precision) {
3659     // infer precision?
3660     if (typeof precision == 'undefined') {
3661         // refine geohash until it matches precision of supplied lat/lon
3662         for (var p=1; p<=12; p++) {
3663             var hash = Geohash.encode(lat, lon, p);
3664             var posn = Geohash.decode(hash);
3665             if (posn.lat==lat && posn.lon==lon) return hash;
3666         }
3667         precision = 12; // set to maximum
3668     }
3669
3670     lat = Number(lat);
3671     lon = Number(lon);
3672     precision = Number(precision);
3673
3674     if (isNaN(lat) || isNaN(lon) || isNaN(precision)) throw new Error('Invalid geohash');
3675
3676     var idx = 0; // index into base32 map
3677     var bit = 0; // each char holds 5 bits
3678     var evenBit = true;
3679     var geohash = '';
3680
3681     var latMin =  -90, latMax =  90;
3682     var lonMin = -180, lonMax = 180;
3683
3684     while (geohash.length < precision) {
3685         if (evenBit) {
3686             // bisect E-W longitude
3687             var lonMid = (lonMin + lonMax) / 2;
3688             if (lon >= lonMid) {
3689                 idx = idx*2 + 1;
3690                 lonMin = lonMid;
3691             } else {
3692                 idx = idx*2;
3693                 lonMax = lonMid;
3694             }
3695         } else {
3696             // bisect N-S latitude
3697             var latMid = (latMin + latMax) / 2;
3698             if (lat >= latMid) {
3699                 idx = idx*2 + 1;
3700                 latMin = latMid;
3701             } else {
3702                 idx = idx*2;
3703                 latMax = latMid;
3704             }
3705         }
3706         evenBit = !evenBit;
3707
3708         if (++bit == 5) {
3709             // 5 bits gives us a character: append it and start over
3710             geohash += Geohash.base32.charAt(idx);
3711             bit = 0;
3712             idx = 0;
3713         }
3714     }
3715
3716     return geohash;
3717 };
3718
3719
3720 /**
3721  * Decode geohash to latitude/longitude (location is approximate centre of geohash cell,
3722  *     to reasonable precision).
3723  *
3724  * @param   {string} geohash - Geohash string to be converted to latitude/longitude.
3725  * @returns {{lat:number, lon:number}} (Center of) geohashed location.
3726  * @throws  Invalid geohash.
3727  *
3728  * @example
3729  *     var latlon = Geohash.decode('u120fxw'); // latlon: { lat: 52.205, lon: 0.1188 }
3730  */
3731 Geohash.decode = function(geohash) {
3732
3733     var bounds = Geohash.bounds(geohash); // <-- the hard work
3734     // now just determine the centre of the cell...
3735
3736     var latMin = bounds.sw.lat, lonMin = bounds.sw.lon;
3737     var latMax = bounds.ne.lat, lonMax = bounds.ne.lon;
3738
3739     // cell centre
3740     var lat = (latMin + latMax)/2;
3741     var lon = (lonMin + lonMax)/2;
3742
3743     // round to close to centre without excessive precision: ⌊2-log10(Δ°)⌋ decimal places
3744     lat = lat.toFixed(Math.floor(2-Math.log(latMax-latMin)/Math.LN10));
3745     lon = lon.toFixed(Math.floor(2-Math.log(lonMax-lonMin)/Math.LN10));
3746
3747     return { lat: Number(lat), lon: Number(lon) };
3748 };
3749
3750
3751 /**
3752  * Returns SW/NE latitude/longitude bounds of specified geohash.
3753  *
3754  * @param   {string} geohash - Cell that bounds are required of.
3755  * @returns {{sw: {lat: number, lon: number}, ne: {lat: number, lon: number}}}
3756  * @throws  Invalid geohash.
3757  */
3758 Geohash.bounds = function(geohash) {
3759     if (geohash.length === 0) throw new Error('Invalid geohash');
3760
3761     geohash = geohash.toLowerCase();
3762
3763     var evenBit = true;
3764     var latMin =  -90, latMax =  90;
3765     var lonMin = -180, lonMax = 180;
3766
3767     for (var i=0; i<geohash.length; i++) {
3768         var chr = geohash.charAt(i);
3769         var idx = Geohash.base32.indexOf(chr);
3770         if (idx == -1) throw new Error('Invalid geohash');
3771
3772         for (var n=4; n>=0; n--) {
3773             var bitN = idx >> n & 1;
3774             if (evenBit) {
3775                 // longitude
3776                 var lonMid = (lonMin+lonMax) / 2;
3777                 if (bitN == 1) {
3778                     lonMin = lonMid;
3779                 } else {
3780                     lonMax = lonMid;
3781                 }
3782             } else {
3783                 // latitude
3784                 var latMid = (latMin+latMax) / 2;
3785                 if (bitN == 1) {
3786                     latMin = latMid;
3787                 } else {
3788                     latMax = latMid;
3789                 }
3790             }
3791             evenBit = !evenBit;
3792         }
3793     }
3794
3795     var bounds = {
3796         sw: { lat: latMin, lon: lonMin },
3797         ne: { lat: latMax, lon: lonMax },
3798     };
3799
3800     return bounds;
3801 };
3802
3803
3804 /**
3805  * Determines adjacent cell in given direction.
3806  *
3807  * @param   geohash - Cell to which adjacent cell is required.
3808  * @param   direction - Direction from geohash (N/S/E/W).
3809  * @returns {string} Geocode of adjacent cell.
3810  * @throws  Invalid geohash.
3811  */
3812 Geohash.adjacent = function(geohash, direction) {
3813     // based on github.com/davetroy/geohash-js
3814
3815     geohash = geohash.toLowerCase();
3816     direction = direction.toLowerCase();
3817
3818     if (geohash.length === 0) throw new Error('Invalid geohash');
3819     if ('nsew'.indexOf(direction) == -1) throw new Error('Invalid direction');
3820
3821     var neighbour = {
3822         n: [ 'p0r21436x8zb9dcf5h7kjnmqesgutwvy', 'bc01fg45238967deuvhjyznpkmstqrwx' ],
3823         s: [ '14365h7k9dcfesgujnmqp0r2twvyx8zb', '238967debc01fg45kmstqrwxuvhjyznp' ],
3824         e: [ 'bc01fg45238967deuvhjyznpkmstqrwx', 'p0r21436x8zb9dcf5h7kjnmqesgutwvy' ],
3825         w: [ '238967debc01fg45kmstqrwxuvhjyznp', '14365h7k9dcfesgujnmqp0r2twvyx8zb' ],
3826     };
3827     var border = {
3828         n: [ 'prxz',     'bcfguvyz' ],
3829         s: [ '028b',     '0145hjnp' ],
3830         e: [ 'bcfguvyz', 'prxz'     ],
3831         w: [ '0145hjnp', '028b'     ],
3832     };
3833
3834     var lastCh = geohash.slice(-1);    // last character of hash
3835     var parent = geohash.slice(0, -1); // hash without last character
3836
3837     var type = geohash.length % 2;
3838
3839     // check for edge-cases which don't share common prefix
3840     if (border[direction][type].indexOf(lastCh) != -1 && parent !== '') {
3841         parent = Geohash.adjacent(parent, direction);
3842     }
3843
3844     // append letter for direction to parent
3845     return parent + Geohash.base32.charAt(neighbour[direction][type].indexOf(lastCh));
3846 };
3847
3848
3849 /**
3850  * Returns all 8 adjacent cells to specified geohash.
3851  *
3852  * @param   {string} geohash - Geohash neighbours are required of.
3853  * @returns {{n,ne,e,se,s,sw,w,nw: string}}
3854  * @throws  Invalid geohash.
3855  */
3856 Geohash.neighbours = function(geohash) {
3857     return {
3858         'n':  Geohash.adjacent(geohash, 'n'),
3859         'ne': Geohash.adjacent(Geohash.adjacent(geohash, 'n'), 'e'),
3860         'e':  Geohash.adjacent(geohash, 'e'),
3861         'se': Geohash.adjacent(Geohash.adjacent(geohash, 's'), 'e'),
3862         's':  Geohash.adjacent(geohash, 's'),
3863         'sw': Geohash.adjacent(Geohash.adjacent(geohash, 's'), 'w'),
3864         'w':  Geohash.adjacent(geohash, 'w'),
3865         'nw': Geohash.adjacent(Geohash.adjacent(geohash, 'n'), 'w'),
3866     };
3867 };
3868
3869
3870 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
3871 if (typeof module != 'undefined' && module.exports) module.exports = Geohash; // CommonJS, node.js
3872
3873 },{}],22:[function(require,module,exports){
3874 (function (process){
3875 // Copyright Joyent, Inc. and other Node contributors.
3876 //
3877 // Permission is hereby granted, free of charge, to any person obtaining a
3878 // copy of this software and associated documentation files (the
3879 // "Software"), to deal in the Software without restriction, including
3880 // without limitation the rights to use, copy, modify, merge, publish,
3881 // distribute, sublicense, and/or sell copies of the Software, and to permit
3882 // persons to whom the Software is furnished to do so, subject to the
3883 // following conditions:
3884 //
3885 // The above copyright notice and this permission notice shall be included
3886 // in all copies or substantial portions of the Software.
3887 //
3888 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
3889 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3890 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
3891 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
3892 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
3893 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
3894 // USE OR OTHER DEALINGS IN THE SOFTWARE.
3895
3896 // resolves . and .. elements in a path array with directory names there
3897 // must be no slashes, empty elements, or device names (c:\) in the array
3898 // (so also no leading and trailing slashes - it does not distinguish
3899 // relative and absolute paths)
3900 function normalizeArray(parts, allowAboveRoot) {
3901   // if the path tries to go above the root, `up` ends up > 0
3902   var up = 0;
3903   for (var i = parts.length - 1; i >= 0; i--) {
3904     var last = parts[i];
3905     if (last === '.') {
3906       parts.splice(i, 1);
3907     } else if (last === '..') {
3908       parts.splice(i, 1);
3909       up++;
3910     } else if (up) {
3911       parts.splice(i, 1);
3912       up--;
3913     }
3914   }
3915
3916   // if the path is allowed to go above the root, restore leading ..s
3917   if (allowAboveRoot) {
3918     for (; up--; up) {
3919       parts.unshift('..');
3920     }
3921   }
3922
3923   return parts;
3924 }
3925
3926 // Split a filename into [root, dir, basename, ext], unix version
3927 // 'root' is just a slash, or nothing.
3928 var splitPathRe =
3929     /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
3930 var splitPath = function(filename) {
3931   return splitPathRe.exec(filename).slice(1);
3932 };
3933
3934 // path.resolve([from ...], to)
3935 // posix version
3936 exports.resolve = function() {
3937   var resolvedPath = '',
3938       resolvedAbsolute = false;
3939
3940   for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
3941     var path = (i >= 0) ? arguments[i] : process.cwd();
3942
3943     // Skip empty and invalid entries
3944     if (typeof path !== 'string') {
3945       throw new TypeError('Arguments to path.resolve must be strings');
3946     } else if (!path) {
3947       continue;
3948     }
3949
3950     resolvedPath = path + '/' + resolvedPath;
3951     resolvedAbsolute = path.charAt(0) === '/';
3952   }
3953
3954   // At this point the path should be resolved to a full absolute path, but
3955   // handle relative paths to be safe (might happen when process.cwd() fails)
3956
3957   // Normalize the path
3958   resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
3959     return !!p;
3960   }), !resolvedAbsolute).join('/');
3961
3962   return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
3963 };
3964
3965 // path.normalize(path)
3966 // posix version
3967 exports.normalize = function(path) {
3968   var isAbsolute = exports.isAbsolute(path),
3969       trailingSlash = substr(path, -1) === '/';
3970
3971   // Normalize the path
3972   path = normalizeArray(filter(path.split('/'), function(p) {
3973     return !!p;
3974   }), !isAbsolute).join('/');
3975
3976   if (!path && !isAbsolute) {
3977     path = '.';
3978   }
3979   if (path && trailingSlash) {
3980     path += '/';
3981   }
3982
3983   return (isAbsolute ? '/' : '') + path;
3984 };
3985
3986 // posix version
3987 exports.isAbsolute = function(path) {
3988   return path.charAt(0) === '/';
3989 };
3990
3991 // posix version
3992 exports.join = function() {
3993   var paths = Array.prototype.slice.call(arguments, 0);
3994   return exports.normalize(filter(paths, function(p, index) {
3995     if (typeof p !== 'string') {
3996       throw new TypeError('Arguments to path.join must be strings');
3997     }
3998     return p;
3999   }).join('/'));
4000 };
4001
4002
4003 // path.relative(from, to)
4004 // posix version
4005 exports.relative = function(from, to) {
4006   from = exports.resolve(from).substr(1);
4007   to = exports.resolve(to).substr(1);
4008
4009   function trim(arr) {
4010     var start = 0;
4011     for (; start < arr.length; start++) {
4012       if (arr[start] !== '') break;
4013     }
4014
4015     var end = arr.length - 1;
4016     for (; end >= 0; end--) {
4017       if (arr[end] !== '') break;
4018     }
4019
4020     if (start > end) return [];
4021     return arr.slice(start, end - start + 1);
4022   }
4023
4024   var fromParts = trim(from.split('/'));
4025   var toParts = trim(to.split('/'));
4026
4027   var length = Math.min(fromParts.length, toParts.length);
4028   var samePartsLength = length;
4029   for (var i = 0; i < length; i++) {
4030     if (fromParts[i] !== toParts[i]) {
4031       samePartsLength = i;
4032       break;
4033     }
4034   }
4035
4036   var outputParts = [];
4037   for (var i = samePartsLength; i < fromParts.length; i++) {
4038     outputParts.push('..');
4039   }
4040
4041   outputParts = outputParts.concat(toParts.slice(samePartsLength));
4042
4043   return outputParts.join('/');
4044 };
4045
4046 exports.sep = '/';
4047 exports.delimiter = ':';
4048
4049 exports.dirname = function(path) {
4050   var result = splitPath(path),
4051       root = result[0],
4052       dir = result[1];
4053
4054   if (!root && !dir) {
4055     // No dirname whatsoever
4056     return '.';
4057   }
4058
4059   if (dir) {
4060     // It has a dirname, strip trailing slash
4061     dir = dir.substr(0, dir.length - 1);
4062   }
4063
4064   return root + dir;
4065 };
4066
4067
4068 exports.basename = function(path, ext) {
4069   var f = splitPath(path)[2];
4070   // TODO: make this comparison case-insensitive on windows?
4071   if (ext && f.substr(-1 * ext.length) === ext) {
4072     f = f.substr(0, f.length - ext.length);
4073   }
4074   return f;
4075 };
4076
4077
4078 exports.extname = function(path) {
4079   return splitPath(path)[3];
4080 };
4081
4082 function filter (xs, f) {
4083     if (xs.filter) return xs.filter(f);
4084     var res = [];
4085     for (var i = 0; i < xs.length; i++) {
4086         if (f(xs[i], i, xs)) res.push(xs[i]);
4087     }
4088     return res;
4089 }
4090
4091 // String.prototype.substr - negative index don't work in IE8
4092 var substr = 'ab'.substr(-1) === 'b'
4093     ? function (str, start, len) { return str.substr(start, len) }
4094     : function (str, start, len) {
4095         if (start < 0) start = str.length + start;
4096         return str.substr(start, len);
4097     }
4098 ;
4099
4100 }).call(this,require('_process'))
4101
4102 },{"_process":6}],23:[function(require,module,exports){
4103 'use strict';
4104
4105 module.exports = Pbf;
4106
4107 var ieee754 = require('ieee754');
4108
4109 function Pbf(buf) {
4110     this.buf = ArrayBuffer.isView && ArrayBuffer.isView(buf) ? buf : new Uint8Array(buf || 0);
4111     this.pos = 0;
4112     this.type = 0;
4113     this.length = this.buf.length;
4114 }
4115
4116 Pbf.Varint  = 0; // varint: int32, int64, uint32, uint64, sint32, sint64, bool, enum
4117 Pbf.Fixed64 = 1; // 64-bit: double, fixed64, sfixed64
4118 Pbf.Bytes   = 2; // length-delimited: string, bytes, embedded messages, packed repeated fields
4119 Pbf.Fixed32 = 5; // 32-bit: float, fixed32, sfixed32
4120
4121 var SHIFT_LEFT_32 = (1 << 16) * (1 << 16),
4122     SHIFT_RIGHT_32 = 1 / SHIFT_LEFT_32;
4123
4124 Pbf.prototype = {
4125
4126     destroy: function() {
4127         this.buf = null;
4128     },
4129
4130     // === READING =================================================================
4131
4132     readFields: function(readField, result, end) {
4133         end = end || this.length;
4134
4135         while (this.pos < end) {
4136             var val = this.readVarint(),
4137                 tag = val >> 3,
4138                 startPos = this.pos;
4139
4140             this.type = val & 0x7;
4141             readField(tag, result, this);
4142
4143             if (this.pos === startPos) this.skip(val);
4144         }
4145         return result;
4146     },
4147
4148     readMessage: function(readField, result) {
4149         return this.readFields(readField, result, this.readVarint() + this.pos);
4150     },
4151
4152     readFixed32: function() {
4153         var val = readUInt32(this.buf, this.pos);
4154         this.pos += 4;
4155         return val;
4156     },
4157
4158     readSFixed32: function() {
4159         var val = readInt32(this.buf, this.pos);
4160         this.pos += 4;
4161         return val;
4162     },
4163
4164     // 64-bit int handling is based on github.com/dpw/node-buffer-more-ints (MIT-licensed)
4165
4166     readFixed64: function() {
4167         var val = readUInt32(this.buf, this.pos) + readUInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32;
4168         this.pos += 8;
4169         return val;
4170     },
4171
4172     readSFixed64: function() {
4173         var val = readUInt32(this.buf, this.pos) + readInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32;
4174         this.pos += 8;
4175         return val;
4176     },
4177
4178     readFloat: function() {
4179         var val = ieee754.read(this.buf, this.pos, true, 23, 4);
4180         this.pos += 4;
4181         return val;
4182     },
4183
4184     readDouble: function() {
4185         var val = ieee754.read(this.buf, this.pos, true, 52, 8);
4186         this.pos += 8;
4187         return val;
4188     },
4189
4190     readVarint: function(isSigned) {
4191         var buf = this.buf,
4192             val, b;
4193
4194         b = buf[this.pos++]; val  =  b & 0x7f;        if (b < 0x80) return val;
4195         b = buf[this.pos++]; val |= (b & 0x7f) << 7;  if (b < 0x80) return val;
4196         b = buf[this.pos++]; val |= (b & 0x7f) << 14; if (b < 0x80) return val;
4197         b = buf[this.pos++]; val |= (b & 0x7f) << 21; if (b < 0x80) return val;
4198         b = buf[this.pos];   val |= (b & 0x0f) << 28;
4199
4200         return readVarintRemainder(val, isSigned, this);
4201     },
4202
4203     readVarint64: function() { // for compatibility with v2.0.1
4204         return this.readVarint(true);
4205     },
4206
4207     readSVarint: function() {
4208         var num = this.readVarint();
4209         return num % 2 === 1 ? (num + 1) / -2 : num / 2; // zigzag encoding
4210     },
4211
4212     readBoolean: function() {
4213         return Boolean(this.readVarint());
4214     },
4215
4216     readString: function() {
4217         var end = this.readVarint() + this.pos,
4218             str = readUtf8(this.buf, this.pos, end);
4219         this.pos = end;
4220         return str;
4221     },
4222
4223     readBytes: function() {
4224         var end = this.readVarint() + this.pos,
4225             buffer = this.buf.subarray(this.pos, end);
4226         this.pos = end;
4227         return buffer;
4228     },
4229
4230     // verbose for performance reasons; doesn't affect gzipped size
4231
4232     readPackedVarint: function(arr, isSigned) {
4233         var end = readPackedEnd(this);
4234         arr = arr || [];
4235         while (this.pos < end) arr.push(this.readVarint(isSigned));
4236         return arr;
4237     },
4238     readPackedSVarint: function(arr) {
4239         var end = readPackedEnd(this);
4240         arr = arr || [];
4241         while (this.pos < end) arr.push(this.readSVarint());
4242         return arr;
4243     },
4244     readPackedBoolean: function(arr) {
4245         var end = readPackedEnd(this);
4246         arr = arr || [];
4247         while (this.pos < end) arr.push(this.readBoolean());
4248         return arr;
4249     },
4250     readPackedFloat: function(arr) {
4251         var end = readPackedEnd(this);
4252         arr = arr || [];
4253         while (this.pos < end) arr.push(this.readFloat());
4254         return arr;
4255     },
4256     readPackedDouble: function(arr) {
4257         var end = readPackedEnd(this);
4258         arr = arr || [];
4259         while (this.pos < end) arr.push(this.readDouble());
4260         return arr;
4261     },
4262     readPackedFixed32: function(arr) {
4263         var end = readPackedEnd(this);
4264         arr = arr || [];
4265         while (this.pos < end) arr.push(this.readFixed32());
4266         return arr;
4267     },
4268     readPackedSFixed32: function(arr) {
4269         var end = readPackedEnd(this);
4270         arr = arr || [];
4271         while (this.pos < end) arr.push(this.readSFixed32());
4272         return arr;
4273     },
4274     readPackedFixed64: function(arr) {
4275         var end = readPackedEnd(this);
4276         arr = arr || [];
4277         while (this.pos < end) arr.push(this.readFixed64());
4278         return arr;
4279     },
4280     readPackedSFixed64: function(arr) {
4281         var end = readPackedEnd(this);
4282         arr = arr || [];
4283         while (this.pos < end) arr.push(this.readSFixed64());
4284         return arr;
4285     },
4286
4287     skip: function(val) {
4288         var type = val & 0x7;
4289         if (type === Pbf.Varint) while (this.buf[this.pos++] > 0x7f) {}
4290         else if (type === Pbf.Bytes) this.pos = this.readVarint() + this.pos;
4291         else if (type === Pbf.Fixed32) this.pos += 4;
4292         else if (type === Pbf.Fixed64) this.pos += 8;
4293         else throw new Error('Unimplemented type: ' + type);
4294     },
4295
4296     // === WRITING =================================================================
4297
4298     writeTag: function(tag, type) {
4299         this.writeVarint((tag << 3) | type);
4300     },
4301
4302     realloc: function(min) {
4303         var length = this.length || 16;
4304
4305         while (length < this.pos + min) length *= 2;
4306
4307         if (length !== this.length) {
4308             var buf = new Uint8Array(length);
4309             buf.set(this.buf);
4310             this.buf = buf;
4311             this.length = length;
4312         }
4313     },
4314
4315     finish: function() {
4316         this.length = this.pos;
4317         this.pos = 0;
4318         return this.buf.subarray(0, this.length);
4319     },
4320
4321     writeFixed32: function(val) {
4322         this.realloc(4);
4323         writeInt32(this.buf, val, this.pos);
4324         this.pos += 4;
4325     },
4326
4327     writeSFixed32: function(val) {
4328         this.realloc(4);
4329         writeInt32(this.buf, val, this.pos);
4330         this.pos += 4;
4331     },
4332
4333     writeFixed64: function(val) {
4334         this.realloc(8);
4335         writeInt32(this.buf, val & -1, this.pos);
4336         writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4);
4337         this.pos += 8;
4338     },
4339
4340     writeSFixed64: function(val) {
4341         this.realloc(8);
4342         writeInt32(this.buf, val & -1, this.pos);
4343         writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4);
4344         this.pos += 8;
4345     },
4346
4347     writeVarint: function(val) {
4348         val = +val || 0;
4349
4350         if (val > 0xfffffff || val < 0) {
4351             writeBigVarint(val, this);
4352             return;
4353         }
4354
4355         this.realloc(4);
4356
4357         this.buf[this.pos++] =           val & 0x7f  | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
4358         this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
4359         this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
4360         this.buf[this.pos++] =   (val >>> 7) & 0x7f;
4361     },
4362
4363     writeSVarint: function(val) {
4364         this.writeVarint(val < 0 ? -val * 2 - 1 : val * 2);
4365     },
4366
4367     writeBoolean: function(val) {
4368         this.writeVarint(Boolean(val));
4369     },
4370
4371     writeString: function(str) {
4372         str = String(str);
4373         this.realloc(str.length * 4);
4374
4375         this.pos++; // reserve 1 byte for short string length
4376
4377         var startPos = this.pos;
4378         // write the string directly to the buffer and see how much was written
4379         this.pos = writeUtf8(this.buf, str, this.pos);
4380         var len = this.pos - startPos;
4381
4382         if (len >= 0x80) makeRoomForExtraLength(startPos, len, this);
4383
4384         // finally, write the message length in the reserved place and restore the position
4385         this.pos = startPos - 1;
4386         this.writeVarint(len);
4387         this.pos += len;
4388     },
4389
4390     writeFloat: function(val) {
4391         this.realloc(4);
4392         ieee754.write(this.buf, val, this.pos, true, 23, 4);
4393         this.pos += 4;
4394     },
4395
4396     writeDouble: function(val) {
4397         this.realloc(8);
4398         ieee754.write(this.buf, val, this.pos, true, 52, 8);
4399         this.pos += 8;
4400     },
4401
4402     writeBytes: function(buffer) {
4403         var len = buffer.length;
4404         this.writeVarint(len);
4405         this.realloc(len);
4406         for (var i = 0; i < len; i++) this.buf[this.pos++] = buffer[i];
4407     },
4408
4409     writeRawMessage: function(fn, obj) {
4410         this.pos++; // reserve 1 byte for short message length
4411
4412         // write the message directly to the buffer and see how much was written
4413         var startPos = this.pos;
4414         fn(obj, this);
4415         var len = this.pos - startPos;
4416
4417         if (len >= 0x80) makeRoomForExtraLength(startPos, len, this);
4418
4419         // finally, write the message length in the reserved place and restore the position
4420         this.pos = startPos - 1;
4421         this.writeVarint(len);
4422         this.pos += len;
4423     },
4424
4425     writeMessage: function(tag, fn, obj) {
4426         this.writeTag(tag, Pbf.Bytes);
4427         this.writeRawMessage(fn, obj);
4428     },
4429
4430     writePackedVarint:   function(tag, arr) { this.writeMessage(tag, writePackedVarint, arr);   },
4431     writePackedSVarint:  function(tag, arr) { this.writeMessage(tag, writePackedSVarint, arr);  },
4432     writePackedBoolean:  function(tag, arr) { this.writeMessage(tag, writePackedBoolean, arr);  },
4433     writePackedFloat:    function(tag, arr) { this.writeMessage(tag, writePackedFloat, arr);    },
4434     writePackedDouble:   function(tag, arr) { this.writeMessage(tag, writePackedDouble, arr);   },
4435     writePackedFixed32:  function(tag, arr) { this.writeMessage(tag, writePackedFixed32, arr);  },
4436     writePackedSFixed32: function(tag, arr) { this.writeMessage(tag, writePackedSFixed32, arr); },
4437     writePackedFixed64:  function(tag, arr) { this.writeMessage(tag, writePackedFixed64, arr);  },
4438     writePackedSFixed64: function(tag, arr) { this.writeMessage(tag, writePackedSFixed64, arr); },
4439
4440     writeBytesField: function(tag, buffer) {
4441         this.writeTag(tag, Pbf.Bytes);
4442         this.writeBytes(buffer);
4443     },
4444     writeFixed32Field: function(tag, val) {
4445         this.writeTag(tag, Pbf.Fixed32);
4446         this.writeFixed32(val);
4447     },
4448     writeSFixed32Field: function(tag, val) {
4449         this.writeTag(tag, Pbf.Fixed32);
4450         this.writeSFixed32(val);
4451     },
4452     writeFixed64Field: function(tag, val) {
4453         this.writeTag(tag, Pbf.Fixed64);
4454         this.writeFixed64(val);
4455     },
4456     writeSFixed64Field: function(tag, val) {
4457         this.writeTag(tag, Pbf.Fixed64);
4458         this.writeSFixed64(val);
4459     },
4460     writeVarintField: function(tag, val) {
4461         this.writeTag(tag, Pbf.Varint);
4462         this.writeVarint(val);
4463     },
4464     writeSVarintField: function(tag, val) {
4465         this.writeTag(tag, Pbf.Varint);
4466         this.writeSVarint(val);
4467     },
4468     writeStringField: function(tag, str) {
4469         this.writeTag(tag, Pbf.Bytes);
4470         this.writeString(str);
4471     },
4472     writeFloatField: function(tag, val) {
4473         this.writeTag(tag, Pbf.Fixed32);
4474         this.writeFloat(val);
4475     },
4476     writeDoubleField: function(tag, val) {
4477         this.writeTag(tag, Pbf.Fixed64);
4478         this.writeDouble(val);
4479     },
4480     writeBooleanField: function(tag, val) {
4481         this.writeVarintField(tag, Boolean(val));
4482     }
4483 };
4484
4485 function readVarintRemainder(l, s, p) {
4486     var buf = p.buf,
4487         h, b;
4488
4489     b = buf[p.pos++]; h  = (b & 0x70) >> 4;  if (b < 0x80) return toNum(l, h, s);
4490     b = buf[p.pos++]; h |= (b & 0x7f) << 3;  if (b < 0x80) return toNum(l, h, s);
4491     b = buf[p.pos++]; h |= (b & 0x7f) << 10; if (b < 0x80) return toNum(l, h, s);
4492     b = buf[p.pos++]; h |= (b & 0x7f) << 17; if (b < 0x80) return toNum(l, h, s);
4493     b = buf[p.pos++]; h |= (b & 0x7f) << 24; if (b < 0x80) return toNum(l, h, s);
4494     b = buf[p.pos++]; h |= (b & 0x01) << 31; if (b < 0x80) return toNum(l, h, s);
4495
4496     throw new Error('Expected varint not more than 10 bytes');
4497 }
4498
4499 function readPackedEnd(pbf) {
4500     return pbf.type === Pbf.Bytes ?
4501         pbf.readVarint() + pbf.pos : pbf.pos + 1;
4502 }
4503
4504 function toNum(low, high, isSigned) {
4505     if (isSigned) {
4506         return high * 0x100000000 + (low >>> 0);
4507     }
4508
4509     return ((high >>> 0) * 0x100000000) + (low >>> 0);
4510 }
4511
4512 function writeBigVarint(val, pbf) {
4513     var low, high;
4514
4515     if (val >= 0) {
4516         low  = (val % 0x100000000) | 0;
4517         high = (val / 0x100000000) | 0;
4518     } else {
4519         low  = ~(-val % 0x100000000);
4520         high = ~(-val / 0x100000000);
4521
4522         if (low ^ 0xffffffff) {
4523             low = (low + 1) | 0;
4524         } else {
4525             low = 0;
4526             high = (high + 1) | 0;
4527         }
4528     }
4529
4530     if (val >= 0x10000000000000000 || val < -0x10000000000000000) {
4531         throw new Error('Given varint doesn\'t fit into 10 bytes');
4532     }
4533
4534     pbf.realloc(10);
4535
4536     writeBigVarintLow(low, high, pbf);
4537     writeBigVarintHigh(high, pbf);
4538 }
4539
4540 function writeBigVarintLow(low, high, pbf) {
4541     pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
4542     pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
4543     pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
4544     pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
4545     pbf.buf[pbf.pos]   = low & 0x7f;
4546 }
4547
4548 function writeBigVarintHigh(high, pbf) {
4549     var lsb = (high & 0x07) << 4;
4550
4551     pbf.buf[pbf.pos++] |= lsb         | ((high >>>= 3) ? 0x80 : 0); if (!high) return;
4552     pbf.buf[pbf.pos++]  = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
4553     pbf.buf[pbf.pos++]  = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
4554     pbf.buf[pbf.pos++]  = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
4555     pbf.buf[pbf.pos++]  = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
4556     pbf.buf[pbf.pos++]  = high & 0x7f;
4557 }
4558
4559 function makeRoomForExtraLength(startPos, len, pbf) {
4560     var extraLen =
4561         len <= 0x3fff ? 1 :
4562         len <= 0x1fffff ? 2 :
4563         len <= 0xfffffff ? 3 : Math.ceil(Math.log(len) / (Math.LN2 * 7));
4564
4565     // if 1 byte isn't enough for encoding message length, shift the data to the right
4566     pbf.realloc(extraLen);
4567     for (var i = pbf.pos - 1; i >= startPos; i--) pbf.buf[i + extraLen] = pbf.buf[i];
4568 }
4569
4570 function writePackedVarint(arr, pbf)   { for (var i = 0; i < arr.length; i++) pbf.writeVarint(arr[i]);   }
4571 function writePackedSVarint(arr, pbf)  { for (var i = 0; i < arr.length; i++) pbf.writeSVarint(arr[i]);  }
4572 function writePackedFloat(arr, pbf)    { for (var i = 0; i < arr.length; i++) pbf.writeFloat(arr[i]);    }
4573 function writePackedDouble(arr, pbf)   { for (var i = 0; i < arr.length; i++) pbf.writeDouble(arr[i]);   }
4574 function writePackedBoolean(arr, pbf)  { for (var i = 0; i < arr.length; i++) pbf.writeBoolean(arr[i]);  }
4575 function writePackedFixed32(arr, pbf)  { for (var i = 0; i < arr.length; i++) pbf.writeFixed32(arr[i]);  }
4576 function writePackedSFixed32(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed32(arr[i]); }
4577 function writePackedFixed64(arr, pbf)  { for (var i = 0; i < arr.length; i++) pbf.writeFixed64(arr[i]);  }
4578 function writePackedSFixed64(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed64(arr[i]); }
4579
4580 // Buffer code below from https://github.com/feross/buffer, MIT-licensed
4581
4582 function readUInt32(buf, pos) {
4583     return ((buf[pos]) |
4584         (buf[pos + 1] << 8) |
4585         (buf[pos + 2] << 16)) +
4586         (buf[pos + 3] * 0x1000000);
4587 }
4588
4589 function writeInt32(buf, val, pos) {
4590     buf[pos] = val;
4591     buf[pos + 1] = (val >>> 8);
4592     buf[pos + 2] = (val >>> 16);
4593     buf[pos + 3] = (val >>> 24);
4594 }
4595
4596 function readInt32(buf, pos) {
4597     return ((buf[pos]) |
4598         (buf[pos + 1] << 8) |
4599         (buf[pos + 2] << 16)) +
4600         (buf[pos + 3] << 24);
4601 }
4602
4603 function readUtf8(buf, pos, end) {
4604     var str = '';
4605     var i = pos;
4606
4607     while (i < end) {
4608         var b0 = buf[i];
4609         var c = null; // codepoint
4610         var bytesPerSequence =
4611             b0 > 0xEF ? 4 :
4612             b0 > 0xDF ? 3 :
4613             b0 > 0xBF ? 2 : 1;
4614
4615         if (i + bytesPerSequence > end) break;
4616
4617         var b1, b2, b3;
4618
4619         if (bytesPerSequence === 1) {
4620             if (b0 < 0x80) {
4621                 c = b0;
4622             }
4623         } else if (bytesPerSequence === 2) {
4624             b1 = buf[i + 1];
4625             if ((b1 & 0xC0) === 0x80) {
4626                 c = (b0 & 0x1F) << 0x6 | (b1 & 0x3F);
4627                 if (c <= 0x7F) {
4628                     c = null;
4629                 }
4630             }
4631         } else if (bytesPerSequence === 3) {
4632             b1 = buf[i + 1];
4633             b2 = buf[i + 2];
4634             if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80) {
4635                 c = (b0 & 0xF) << 0xC | (b1 & 0x3F) << 0x6 | (b2 & 0x3F);
4636                 if (c <= 0x7FF || (c >= 0xD800 && c <= 0xDFFF)) {
4637                     c = null;
4638                 }
4639             }
4640         } else if (bytesPerSequence === 4) {
4641             b1 = buf[i + 1];
4642             b2 = buf[i + 2];
4643             b3 = buf[i + 3];
4644             if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80) {
4645                 c = (b0 & 0xF) << 0x12 | (b1 & 0x3F) << 0xC | (b2 & 0x3F) << 0x6 | (b3 & 0x3F);
4646                 if (c <= 0xFFFF || c >= 0x110000) {
4647                     c = null;
4648                 }
4649             }
4650         }
4651
4652         if (c === null) {
4653             c = 0xFFFD;
4654             bytesPerSequence = 1;
4655
4656         } else if (c > 0xFFFF) {
4657             c -= 0x10000;
4658             str += String.fromCharCode(c >>> 10 & 0x3FF | 0xD800);
4659             c = 0xDC00 | c & 0x3FF;
4660         }
4661
4662         str += String.fromCharCode(c);
4663         i += bytesPerSequence;
4664     }
4665
4666     return str;
4667 }
4668
4669 function writeUtf8(buf, str, pos) {
4670     for (var i = 0, c, lead; i < str.length; i++) {
4671         c = str.charCodeAt(i); // code point
4672
4673         if (c > 0xD7FF && c < 0xE000) {
4674             if (lead) {
4675                 if (c < 0xDC00) {
4676                     buf[pos++] = 0xEF;
4677                     buf[pos++] = 0xBF;
4678                     buf[pos++] = 0xBD;
4679                     lead = c;
4680                     continue;
4681                 } else {
4682                     c = lead - 0xD800 << 10 | c - 0xDC00 | 0x10000;
4683                     lead = null;
4684                 }
4685             } else {
4686                 if (c > 0xDBFF || (i + 1 === str.length)) {
4687                     buf[pos++] = 0xEF;
4688                     buf[pos++] = 0xBF;
4689                     buf[pos++] = 0xBD;
4690                 } else {
4691                     lead = c;
4692                 }
4693                 continue;
4694             }
4695         } else if (lead) {
4696             buf[pos++] = 0xEF;
4697             buf[pos++] = 0xBF;
4698             buf[pos++] = 0xBD;
4699             lead = null;
4700         }
4701
4702         if (c < 0x80) {
4703             buf[pos++] = c;
4704         } else {
4705             if (c < 0x800) {
4706                 buf[pos++] = c >> 0x6 | 0xC0;
4707             } else {
4708                 if (c < 0x10000) {
4709                     buf[pos++] = c >> 0xC | 0xE0;
4710                 } else {
4711                     buf[pos++] = c >> 0x12 | 0xF0;
4712                     buf[pos++] = c >> 0xC & 0x3F | 0x80;
4713                 }
4714                 buf[pos++] = c >> 0x6 & 0x3F | 0x80;
4715             }
4716             buf[pos++] = c & 0x3F | 0x80;
4717         }
4718     }
4719     return pos;
4720 }
4721
4722 },{"ieee754":17}],24:[function(require,module,exports){
4723 'use strict';
4724
4725 module.exports = partialSort;
4726
4727 // Floyd-Rivest selection algorithm:
4728 // Rearrange items so that all items in the [left, k] range are smaller than all items in (k, right];
4729 // The k-th element will have the (k - left + 1)th smallest value in [left, right]
4730
4731 function partialSort(arr, k, left, right, compare) {
4732     left = left || 0;
4733     right = right || (arr.length - 1);
4734     compare = compare || defaultCompare;
4735
4736     while (right > left) {
4737         if (right - left > 600) {
4738             var n = right - left + 1;
4739             var m = k - left + 1;
4740             var z = Math.log(n);
4741             var s = 0.5 * Math.exp(2 * z / 3);
4742             var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
4743             var newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
4744             var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
4745             partialSort(arr, k, newLeft, newRight, compare);
4746         }
4747
4748         var t = arr[k];
4749         var i = left;
4750         var j = right;
4751
4752         swap(arr, left, k);
4753         if (compare(arr[right], t) > 0) swap(arr, left, right);
4754
4755         while (i < j) {
4756             swap(arr, i, j);
4757             i++;
4758             j--;
4759             while (compare(arr[i], t) < 0) i++;
4760             while (compare(arr[j], t) > 0) j--;
4761         }
4762
4763         if (compare(arr[left], t) === 0) swap(arr, left, j);
4764         else {
4765             j++;
4766             swap(arr, j, right);
4767         }
4768
4769         if (j <= k) left = j + 1;
4770         if (k <= j) right = j - 1;
4771     }
4772 }
4773
4774 function swap(arr, i, j) {
4775     var tmp = arr[i];
4776     arr[i] = arr[j];
4777     arr[j] = tmp;
4778 }
4779
4780 function defaultCompare(a, b) {
4781     return a < b ? -1 : a > b ? 1 : 0;
4782 }
4783
4784 },{}],25:[function(require,module,exports){
4785 'use strict';
4786
4787 module.exports = rbush;
4788
4789 var quickselect = require('quickselect');
4790
4791 function rbush(maxEntries, format) {
4792     if (!(this instanceof rbush)) return new rbush(maxEntries, format);
4793
4794     // max entries in a node is 9 by default; min node fill is 40% for best performance
4795     this._maxEntries = Math.max(4, maxEntries || 9);
4796     this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4));
4797
4798     if (format) {
4799         this._initFormat(format);
4800     }
4801
4802     this.clear();
4803 }
4804
4805 rbush.prototype = {
4806
4807     all: function () {
4808         return this._all(this.data, []);
4809     },
4810
4811     search: function (bbox) {
4812
4813         var node = this.data,
4814             result = [],
4815             toBBox = this.toBBox;
4816
4817         if (!intersects(bbox, node)) return result;
4818
4819         var nodesToSearch = [],
4820             i, len, child, childBBox;
4821
4822         while (node) {
4823             for (i = 0, len = node.children.length; i < len; i++) {
4824
4825                 child = node.children[i];
4826                 childBBox = node.leaf ? toBBox(child) : child;
4827
4828                 if (intersects(bbox, childBBox)) {
4829                     if (node.leaf) result.push(child);
4830                     else if (contains(bbox, childBBox)) this._all(child, result);
4831                     else nodesToSearch.push(child);
4832                 }
4833             }
4834             node = nodesToSearch.pop();
4835         }
4836
4837         return result;
4838     },
4839
4840     collides: function (bbox) {
4841
4842         var node = this.data,
4843             toBBox = this.toBBox;
4844
4845         if (!intersects(bbox, node)) return false;
4846
4847         var nodesToSearch = [],
4848             i, len, child, childBBox;
4849
4850         while (node) {
4851             for (i = 0, len = node.children.length; i < len; i++) {
4852
4853                 child = node.children[i];
4854                 childBBox = node.leaf ? toBBox(child) : child;
4855
4856                 if (intersects(bbox, childBBox)) {
4857                     if (node.leaf || contains(bbox, childBBox)) return true;
4858                     nodesToSearch.push(child);
4859                 }
4860             }
4861             node = nodesToSearch.pop();
4862         }
4863
4864         return false;
4865     },
4866
4867     load: function (data) {
4868         if (!(data && data.length)) return this;
4869
4870         if (data.length < this._minEntries) {
4871             for (var i = 0, len = data.length; i < len; i++) {
4872                 this.insert(data[i]);
4873             }
4874             return this;
4875         }
4876
4877         // recursively build the tree with the given data from stratch using OMT algorithm
4878         var node = this._build(data.slice(), 0, data.length - 1, 0);
4879
4880         if (!this.data.children.length) {
4881             // save as is if tree is empty
4882             this.data = node;
4883
4884         } else if (this.data.height === node.height) {
4885             // split root if trees have the same height
4886             this._splitRoot(this.data, node);
4887
4888         } else {
4889             if (this.data.height < node.height) {
4890                 // swap trees if inserted one is bigger
4891                 var tmpNode = this.data;
4892                 this.data = node;
4893                 node = tmpNode;
4894             }
4895
4896             // insert the small tree into the large tree at appropriate level
4897             this._insert(node, this.data.height - node.height - 1, true);
4898         }
4899
4900         return this;
4901     },
4902
4903     insert: function (item) {
4904         if (item) this._insert(item, this.data.height - 1);
4905         return this;
4906     },
4907
4908     clear: function () {
4909         this.data = createNode([]);
4910         return this;
4911     },
4912
4913     remove: function (item, equalsFn) {
4914         if (!item) return this;
4915
4916         var node = this.data,
4917             bbox = this.toBBox(item),
4918             path = [],
4919             indexes = [],
4920             i, parent, index, goingUp;
4921
4922         // depth-first iterative tree traversal
4923         while (node || path.length) {
4924
4925             if (!node) { // go up
4926                 node = path.pop();
4927                 parent = path[path.length - 1];
4928                 i = indexes.pop();
4929                 goingUp = true;
4930             }
4931
4932             if (node.leaf) { // check current node
4933                 index = findItem(item, node.children, equalsFn);
4934
4935                 if (index !== -1) {
4936                     // item found, remove the item and condense tree upwards
4937                     node.children.splice(index, 1);
4938                     path.push(node);
4939                     this._condense(path);
4940                     return this;
4941                 }
4942             }
4943
4944             if (!goingUp && !node.leaf && contains(node, bbox)) { // go down
4945                 path.push(node);
4946                 indexes.push(i);
4947                 i = 0;
4948                 parent = node;
4949                 node = node.children[0];
4950
4951             } else if (parent) { // go right
4952                 i++;
4953                 node = parent.children[i];
4954                 goingUp = false;
4955
4956             } else node = null; // nothing found
4957         }
4958
4959         return this;
4960     },
4961
4962     toBBox: function (item) { return item; },
4963
4964     compareMinX: compareNodeMinX,
4965     compareMinY: compareNodeMinY,
4966
4967     toJSON: function () { return this.data; },
4968
4969     fromJSON: function (data) {
4970         this.data = data;
4971         return this;
4972     },
4973
4974     _all: function (node, result) {
4975         var nodesToSearch = [];
4976         while (node) {
4977             if (node.leaf) result.push.apply(result, node.children);
4978             else nodesToSearch.push.apply(nodesToSearch, node.children);
4979
4980             node = nodesToSearch.pop();
4981         }
4982         return result;
4983     },
4984
4985     _build: function (items, left, right, height) {
4986
4987         var N = right - left + 1,
4988             M = this._maxEntries,
4989             node;
4990
4991         if (N <= M) {
4992             // reached leaf level; return leaf
4993             node = createNode(items.slice(left, right + 1));
4994             calcBBox(node, this.toBBox);
4995             return node;
4996         }
4997
4998         if (!height) {
4999             // target height of the bulk-loaded tree
5000             height = Math.ceil(Math.log(N) / Math.log(M));
5001
5002             // target number of root entries to maximize storage utilization
5003             M = Math.ceil(N / Math.pow(M, height - 1));
5004         }
5005
5006         node = createNode([]);
5007         node.leaf = false;
5008         node.height = height;
5009
5010         // split the items into M mostly square tiles
5011
5012         var N2 = Math.ceil(N / M),
5013             N1 = N2 * Math.ceil(Math.sqrt(M)),
5014             i, j, right2, right3;
5015
5016         multiSelect(items, left, right, N1, this.compareMinX);
5017
5018         for (i = left; i <= right; i += N1) {
5019
5020             right2 = Math.min(i + N1 - 1, right);
5021
5022             multiSelect(items, i, right2, N2, this.compareMinY);
5023
5024             for (j = i; j <= right2; j += N2) {
5025
5026                 right3 = Math.min(j + N2 - 1, right2);
5027
5028                 // pack each entry recursively
5029                 node.children.push(this._build(items, j, right3, height - 1));
5030             }
5031         }
5032
5033         calcBBox(node, this.toBBox);
5034
5035         return node;
5036     },
5037
5038     _chooseSubtree: function (bbox, node, level, path) {
5039
5040         var i, len, child, targetNode, area, enlargement, minArea, minEnlargement;
5041
5042         while (true) {
5043             path.push(node);
5044
5045             if (node.leaf || path.length - 1 === level) break;
5046
5047             minArea = minEnlargement = Infinity;
5048
5049             for (i = 0, len = node.children.length; i < len; i++) {
5050                 child = node.children[i];
5051                 area = bboxArea(child);
5052                 enlargement = enlargedArea(bbox, child) - area;
5053
5054                 // choose entry with the least area enlargement
5055                 if (enlargement < minEnlargement) {
5056                     minEnlargement = enlargement;
5057                     minArea = area < minArea ? area : minArea;
5058                     targetNode = child;
5059
5060                 } else if (enlargement === minEnlargement) {
5061                     // otherwise choose one with the smallest area
5062                     if (area < minArea) {
5063                         minArea = area;
5064                         targetNode = child;
5065                     }
5066                 }
5067             }
5068
5069             node = targetNode || node.children[0];
5070         }
5071
5072         return node;
5073     },
5074
5075     _insert: function (item, level, isNode) {
5076
5077         var toBBox = this.toBBox,
5078             bbox = isNode ? item : toBBox(item),
5079             insertPath = [];
5080
5081         // find the best node for accommodating the item, saving all nodes along the path too
5082         var node = this._chooseSubtree(bbox, this.data, level, insertPath);
5083
5084         // put the item into the node
5085         node.children.push(item);
5086         extend(node, bbox);
5087
5088         // split on node overflow; propagate upwards if necessary
5089         while (level >= 0) {
5090             if (insertPath[level].children.length > this._maxEntries) {
5091                 this._split(insertPath, level);
5092                 level--;
5093             } else break;
5094         }
5095
5096         // adjust bboxes along the insertion path
5097         this._adjustParentBBoxes(bbox, insertPath, level);
5098     },
5099
5100     // split overflowed node into two
5101     _split: function (insertPath, level) {
5102
5103         var node = insertPath[level],
5104             M = node.children.length,
5105             m = this._minEntries;
5106
5107         this._chooseSplitAxis(node, m, M);
5108
5109         var splitIndex = this._chooseSplitIndex(node, m, M);
5110
5111         var newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex));
5112         newNode.height = node.height;
5113         newNode.leaf = node.leaf;
5114
5115         calcBBox(node, this.toBBox);
5116         calcBBox(newNode, this.toBBox);
5117
5118         if (level) insertPath[level - 1].children.push(newNode);
5119         else this._splitRoot(node, newNode);
5120     },
5121
5122     _splitRoot: function (node, newNode) {
5123         // split root node
5124         this.data = createNode([node, newNode]);
5125         this.data.height = node.height + 1;
5126         this.data.leaf = false;
5127         calcBBox(this.data, this.toBBox);
5128     },
5129
5130     _chooseSplitIndex: function (node, m, M) {
5131
5132         var i, bbox1, bbox2, overlap, area, minOverlap, minArea, index;
5133
5134         minOverlap = minArea = Infinity;
5135
5136         for (i = m; i <= M - m; i++) {
5137             bbox1 = distBBox(node, 0, i, this.toBBox);
5138             bbox2 = distBBox(node, i, M, this.toBBox);
5139
5140             overlap = intersectionArea(bbox1, bbox2);
5141             area = bboxArea(bbox1) + bboxArea(bbox2);
5142
5143             // choose distribution with minimum overlap
5144             if (overlap < minOverlap) {
5145                 minOverlap = overlap;
5146                 index = i;
5147
5148                 minArea = area < minArea ? area : minArea;
5149
5150             } else if (overlap === minOverlap) {
5151                 // otherwise choose distribution with minimum area
5152                 if (area < minArea) {
5153                     minArea = area;
5154                     index = i;
5155                 }
5156             }
5157         }
5158
5159         return index;
5160     },
5161
5162     // sorts node children by the best axis for split
5163     _chooseSplitAxis: function (node, m, M) {
5164
5165         var compareMinX = node.leaf ? this.compareMinX : compareNodeMinX,
5166             compareMinY = node.leaf ? this.compareMinY : compareNodeMinY,
5167             xMargin = this._allDistMargin(node, m, M, compareMinX),
5168             yMargin = this._allDistMargin(node, m, M, compareMinY);
5169
5170         // if total distributions margin value is minimal for x, sort by minX,
5171         // otherwise it's already sorted by minY
5172         if (xMargin < yMargin) node.children.sort(compareMinX);
5173     },
5174
5175     // total margin of all possible split distributions where each node is at least m full
5176     _allDistMargin: function (node, m, M, compare) {
5177
5178         node.children.sort(compare);
5179
5180         var toBBox = this.toBBox,
5181             leftBBox = distBBox(node, 0, m, toBBox),
5182             rightBBox = distBBox(node, M - m, M, toBBox),
5183             margin = bboxMargin(leftBBox) + bboxMargin(rightBBox),
5184             i, child;
5185
5186         for (i = m; i < M - m; i++) {
5187             child = node.children[i];
5188             extend(leftBBox, node.leaf ? toBBox(child) : child);
5189             margin += bboxMargin(leftBBox);
5190         }
5191
5192         for (i = M - m - 1; i >= m; i--) {
5193             child = node.children[i];
5194             extend(rightBBox, node.leaf ? toBBox(child) : child);
5195             margin += bboxMargin(rightBBox);
5196         }
5197
5198         return margin;
5199     },
5200
5201     _adjustParentBBoxes: function (bbox, path, level) {
5202         // adjust bboxes along the given tree path
5203         for (var i = level; i >= 0; i--) {
5204             extend(path[i], bbox);
5205         }
5206     },
5207
5208     _condense: function (path) {
5209         // go through the path, removing empty nodes and updating bboxes
5210         for (var i = path.length - 1, siblings; i >= 0; i--) {
5211             if (path[i].children.length === 0) {
5212                 if (i > 0) {
5213                     siblings = path[i - 1].children;
5214                     siblings.splice(siblings.indexOf(path[i]), 1);
5215
5216                 } else this.clear();
5217
5218             } else calcBBox(path[i], this.toBBox);
5219         }
5220     },
5221
5222     _initFormat: function (format) {
5223         // data format (minX, minY, maxX, maxY accessors)
5224
5225         // uses eval-type function compilation instead of just accepting a toBBox function
5226         // because the algorithms are very sensitive to sorting functions performance,
5227         // so they should be dead simple and without inner calls
5228
5229         var compareArr = ['return a', ' - b', ';'];
5230
5231         this.compareMinX = new Function('a', 'b', compareArr.join(format[0]));
5232         this.compareMinY = new Function('a', 'b', compareArr.join(format[1]));
5233
5234         this.toBBox = new Function('a',
5235             'return {minX: a' + format[0] +
5236             ', minY: a' + format[1] +
5237             ', maxX: a' + format[2] +
5238             ', maxY: a' + format[3] + '};');
5239     }
5240 };
5241
5242 function findItem(item, items, equalsFn) {
5243     if (!equalsFn) return items.indexOf(item);
5244
5245     for (var i = 0; i < items.length; i++) {
5246         if (equalsFn(item, items[i])) return i;
5247     }
5248     return -1;
5249 }
5250
5251 // calculate node's bbox from bboxes of its children
5252 function calcBBox(node, toBBox) {
5253     distBBox(node, 0, node.children.length, toBBox, node);
5254 }
5255
5256 // min bounding rectangle of node children from k to p-1
5257 function distBBox(node, k, p, toBBox, destNode) {
5258     if (!destNode) destNode = createNode(null);
5259     destNode.minX = Infinity;
5260     destNode.minY = Infinity;
5261     destNode.maxX = -Infinity;
5262     destNode.maxY = -Infinity;
5263
5264     for (var i = k, child; i < p; i++) {
5265         child = node.children[i];
5266         extend(destNode, node.leaf ? toBBox(child) : child);
5267     }
5268
5269     return destNode;
5270 }
5271
5272 function extend(a, b) {
5273     a.minX = Math.min(a.minX, b.minX);
5274     a.minY = Math.min(a.minY, b.minY);
5275     a.maxX = Math.max(a.maxX, b.maxX);
5276     a.maxY = Math.max(a.maxY, b.maxY);
5277     return a;
5278 }
5279
5280 function compareNodeMinX(a, b) { return a.minX - b.minX; }
5281 function compareNodeMinY(a, b) { return a.minY - b.minY; }
5282
5283 function bboxArea(a)   { return (a.maxX - a.minX) * (a.maxY - a.minY); }
5284 function bboxMargin(a) { return (a.maxX - a.minX) + (a.maxY - a.minY); }
5285
5286 function enlargedArea(a, b) {
5287     return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) *
5288            (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY));
5289 }
5290
5291 function intersectionArea(a, b) {
5292     var minX = Math.max(a.minX, b.minX),
5293         minY = Math.max(a.minY, b.minY),
5294         maxX = Math.min(a.maxX, b.maxX),
5295         maxY = Math.min(a.maxY, b.maxY);
5296
5297     return Math.max(0, maxX - minX) *
5298            Math.max(0, maxY - minY);
5299 }
5300
5301 function contains(a, b) {
5302     return a.minX <= b.minX &&
5303            a.minY <= b.minY &&
5304            b.maxX <= a.maxX &&
5305            b.maxY <= a.maxY;
5306 }
5307
5308 function intersects(a, b) {
5309     return b.minX <= a.maxX &&
5310            b.minY <= a.maxY &&
5311            b.maxX >= a.minX &&
5312            b.maxY >= a.minY;
5313 }
5314
5315 function createNode(children) {
5316     return {
5317         children: children,
5318         height: 1,
5319         leaf: true,
5320         minX: Infinity,
5321         minY: Infinity,
5322         maxX: -Infinity,
5323         maxY: -Infinity
5324     };
5325 }
5326
5327 // sort an array so that items come in groups of n unsorted items, with groups sorted between each other;
5328 // combines selection algorithm with binary divide & conquer approach
5329
5330 function multiSelect(arr, left, right, n, compare) {
5331     var stack = [left, right],
5332         mid;
5333
5334     while (stack.length) {
5335         right = stack.pop();
5336         left = stack.pop();
5337
5338         if (right - left <= n) continue;
5339
5340         mid = left + Math.ceil((right - left) / n / 2) * n;
5341         quickselect(arr, mid, left, right, compare);
5342
5343         stack.push(left, mid, mid, right);
5344     }
5345 }
5346
5347 },{"quickselect":24}],26:[function(require,module,exports){
5348 "use strict";
5349 var __extends = (this && this.__extends) || function (d, b) {
5350     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5351     function __() { this.constructor = d; }
5352     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5353 };
5354 var Subject_1 = require('./Subject');
5355 var ObjectUnsubscribedError_1 = require('./util/ObjectUnsubscribedError');
5356 /**
5357  * @class BehaviorSubject<T>
5358  */
5359 var BehaviorSubject = (function (_super) {
5360     __extends(BehaviorSubject, _super);
5361     function BehaviorSubject(_value) {
5362         _super.call(this);
5363         this._value = _value;
5364     }
5365     Object.defineProperty(BehaviorSubject.prototype, "value", {
5366         get: function () {
5367             return this.getValue();
5368         },
5369         enumerable: true,
5370         configurable: true
5371     });
5372     BehaviorSubject.prototype._subscribe = function (subscriber) {
5373         var subscription = _super.prototype._subscribe.call(this, subscriber);
5374         if (subscription && !subscription.closed) {
5375             subscriber.next(this._value);
5376         }
5377         return subscription;
5378     };
5379     BehaviorSubject.prototype.getValue = function () {
5380         if (this.hasError) {
5381             throw this.thrownError;
5382         }
5383         else if (this.closed) {
5384             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5385         }
5386         else {
5387             return this._value;
5388         }
5389     };
5390     BehaviorSubject.prototype.next = function (value) {
5391         _super.prototype.next.call(this, this._value = value);
5392     };
5393     return BehaviorSubject;
5394 }(Subject_1.Subject));
5395 exports.BehaviorSubject = BehaviorSubject;
5396
5397 },{"./Subject":34,"./util/ObjectUnsubscribedError":221}],27:[function(require,module,exports){
5398 "use strict";
5399 var __extends = (this && this.__extends) || function (d, b) {
5400     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5401     function __() { this.constructor = d; }
5402     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5403 };
5404 var Subscriber_1 = require('./Subscriber');
5405 /**
5406  * We need this JSDoc comment for affecting ESDoc.
5407  * @ignore
5408  * @extends {Ignored}
5409  */
5410 var InnerSubscriber = (function (_super) {
5411     __extends(InnerSubscriber, _super);
5412     function InnerSubscriber(parent, outerValue, outerIndex) {
5413         _super.call(this);
5414         this.parent = parent;
5415         this.outerValue = outerValue;
5416         this.outerIndex = outerIndex;
5417         this.index = 0;
5418     }
5419     InnerSubscriber.prototype._next = function (value) {
5420         this.parent.notifyNext(this.outerValue, value, this.outerIndex, this.index++, this);
5421     };
5422     InnerSubscriber.prototype._error = function (error) {
5423         this.parent.notifyError(error, this);
5424         this.unsubscribe();
5425     };
5426     InnerSubscriber.prototype._complete = function () {
5427         this.parent.notifyComplete(this);
5428         this.unsubscribe();
5429     };
5430     return InnerSubscriber;
5431 }(Subscriber_1.Subscriber));
5432 exports.InnerSubscriber = InnerSubscriber;
5433
5434 },{"./Subscriber":36}],28:[function(require,module,exports){
5435 "use strict";
5436 var Observable_1 = require('./Observable');
5437 /**
5438  * Represents a push-based event or value that an {@link Observable} can emit.
5439  * This class is particularly useful for operators that manage notifications,
5440  * like {@link materialize}, {@link dematerialize}, {@link observeOn}, and
5441  * others. Besides wrapping the actual delivered value, it also annotates it
5442  * with metadata of, for instance, what type of push message it is (`next`,
5443  * `error`, or `complete`).
5444  *
5445  * @see {@link materialize}
5446  * @see {@link dematerialize}
5447  * @see {@link observeOn}
5448  *
5449  * @class Notification<T>
5450  */
5451 var Notification = (function () {
5452     function Notification(kind, value, error) {
5453         this.kind = kind;
5454         this.value = value;
5455         this.error = error;
5456         this.hasValue = kind === 'N';
5457     }
5458     /**
5459      * Delivers to the given `observer` the value wrapped by this Notification.
5460      * @param {Observer} observer
5461      * @return
5462      */
5463     Notification.prototype.observe = function (observer) {
5464         switch (this.kind) {
5465             case 'N':
5466                 return observer.next && observer.next(this.value);
5467             case 'E':
5468                 return observer.error && observer.error(this.error);
5469             case 'C':
5470                 return observer.complete && observer.complete();
5471         }
5472     };
5473     /**
5474      * Given some {@link Observer} callbacks, deliver the value represented by the
5475      * current Notification to the correctly corresponding callback.
5476      * @param {function(value: T): void} next An Observer `next` callback.
5477      * @param {function(err: any): void} [error] An Observer `error` callback.
5478      * @param {function(): void} [complete] An Observer `complete` callback.
5479      * @return {any}
5480      */
5481     Notification.prototype.do = function (next, error, complete) {
5482         var kind = this.kind;
5483         switch (kind) {
5484             case 'N':
5485                 return next && next(this.value);
5486             case 'E':
5487                 return error && error(this.error);
5488             case 'C':
5489                 return complete && complete();
5490         }
5491     };
5492     /**
5493      * Takes an Observer or its individual callback functions, and calls `observe`
5494      * or `do` methods accordingly.
5495      * @param {Observer|function(value: T): void} nextOrObserver An Observer or
5496      * the `next` callback.
5497      * @param {function(err: any): void} [error] An Observer `error` callback.
5498      * @param {function(): void} [complete] An Observer `complete` callback.
5499      * @return {any}
5500      */
5501     Notification.prototype.accept = function (nextOrObserver, error, complete) {
5502         if (nextOrObserver && typeof nextOrObserver.next === 'function') {
5503             return this.observe(nextOrObserver);
5504         }
5505         else {
5506             return this.do(nextOrObserver, error, complete);
5507         }
5508     };
5509     /**
5510      * Returns a simple Observable that just delivers the notification represented
5511      * by this Notification instance.
5512      * @return {any}
5513      */
5514     Notification.prototype.toObservable = function () {
5515         var kind = this.kind;
5516         switch (kind) {
5517             case 'N':
5518                 return Observable_1.Observable.of(this.value);
5519             case 'E':
5520                 return Observable_1.Observable.throw(this.error);
5521             case 'C':
5522                 return Observable_1.Observable.empty();
5523         }
5524         throw new Error('unexpected notification kind value');
5525     };
5526     /**
5527      * A shortcut to create a Notification instance of the type `next` from a
5528      * given value.
5529      * @param {T} value The `next` value.
5530      * @return {Notification<T>} The "next" Notification representing the
5531      * argument.
5532      */
5533     Notification.createNext = function (value) {
5534         if (typeof value !== 'undefined') {
5535             return new Notification('N', value);
5536         }
5537         return Notification.undefinedValueNotification;
5538     };
5539     /**
5540      * A shortcut to create a Notification instance of the type `error` from a
5541      * given error.
5542      * @param {any} [err] The `error` error.
5543      * @return {Notification<T>} The "error" Notification representing the
5544      * argument.
5545      */
5546     Notification.createError = function (err) {
5547         return new Notification('E', undefined, err);
5548     };
5549     /**
5550      * A shortcut to create a Notification instance of the type `complete`.
5551      * @return {Notification<any>} The valueless "complete" Notification.
5552      */
5553     Notification.createComplete = function () {
5554         return Notification.completeNotification;
5555     };
5556     Notification.completeNotification = new Notification('C');
5557     Notification.undefinedValueNotification = new Notification('N', undefined);
5558     return Notification;
5559 }());
5560 exports.Notification = Notification;
5561
5562 },{"./Observable":29}],29:[function(require,module,exports){
5563 "use strict";
5564 var root_1 = require('./util/root');
5565 var toSubscriber_1 = require('./util/toSubscriber');
5566 var observable_1 = require('./symbol/observable');
5567 var pipe_1 = require('./util/pipe');
5568 /**
5569  * A representation of any set of values over any amount of time. This is the most basic building block
5570  * of RxJS.
5571  *
5572  * @class Observable<T>
5573  */
5574 var Observable = (function () {
5575     /**
5576      * @constructor
5577      * @param {Function} subscribe the function that is called when the Observable is
5578      * initially subscribed to. This function is given a Subscriber, to which new values
5579      * can be `next`ed, or an `error` method can be called to raise an error, or
5580      * `complete` can be called to notify of a successful completion.
5581      */
5582     function Observable(subscribe) {
5583         this._isScalar = false;
5584         if (subscribe) {
5585             this._subscribe = subscribe;
5586         }
5587     }
5588     /**
5589      * Creates a new Observable, with this Observable as the source, and the passed
5590      * operator defined as the new observable's operator.
5591      * @method lift
5592      * @param {Operator} operator the operator defining the operation to take on the observable
5593      * @return {Observable} a new observable with the Operator applied
5594      */
5595     Observable.prototype.lift = function (operator) {
5596         var observable = new Observable();
5597         observable.source = this;
5598         observable.operator = operator;
5599         return observable;
5600     };
5601     /**
5602      * Invokes an execution of an Observable and registers Observer handlers for notifications it will emit.
5603      *
5604      * <span class="informal">Use it when you have all these Observables, but still nothing is happening.</span>
5605      *
5606      * `subscribe` is not a regular operator, but a method that calls Observable's internal `subscribe` function. It
5607      * might be for example a function that you passed to a {@link create} static factory, but most of the time it is
5608      * a library implementation, which defines what and when will be emitted by an Observable. This means that calling
5609      * `subscribe` is actually the moment when Observable starts its work, not when it is created, as it is often
5610      * thought.
5611      *
5612      * Apart from starting the execution of an Observable, this method allows you to listen for values
5613      * that an Observable emits, as well as for when it completes or errors. You can achieve this in two
5614      * following ways.
5615      *
5616      * The first way is creating an object that implements {@link Observer} interface. It should have methods
5617      * defined by that interface, but note that it should be just a regular JavaScript object, which you can create
5618      * yourself in any way you want (ES6 class, classic function constructor, object literal etc.). In particular do
5619      * not attempt to use any RxJS implementation details to create Observers - you don't need them. Remember also
5620      * that your object does not have to implement all methods. If you find yourself creating a method that doesn't
5621      * do anything, you can simply omit it. Note however, that if `error` method is not provided, all errors will
5622      * be left uncaught.
5623      *
5624      * The second way is to give up on Observer object altogether and simply provide callback functions in place of its methods.
5625      * This means you can provide three functions as arguments to `subscribe`, where first function is equivalent
5626      * of a `next` method, second of an `error` method and third of a `complete` method. Just as in case of Observer,
5627      * if you do not need to listen for something, you can omit a function, preferably by passing `undefined` or `null`,
5628      * since `subscribe` recognizes these functions by where they were placed in function call. When it comes
5629      * to `error` function, just as before, if not provided, errors emitted by an Observable will be thrown.
5630      *
5631      * Whatever style of calling `subscribe` you use, in both cases it returns a Subscription object.
5632      * This object allows you to call `unsubscribe` on it, which in turn will stop work that an Observable does and will clean
5633      * up all resources that an Observable used. Note that cancelling a subscription will not call `complete` callback
5634      * provided to `subscribe` function, which is reserved for a regular completion signal that comes from an Observable.
5635      *
5636      * Remember that callbacks provided to `subscribe` are not guaranteed to be called asynchronously.
5637      * It is an Observable itself that decides when these functions will be called. For example {@link of}
5638      * by default emits all its values synchronously. Always check documentation for how given Observable
5639      * will behave when subscribed and if its default behavior can be modified with a {@link Scheduler}.
5640      *
5641      * @example <caption>Subscribe with an Observer</caption>
5642      * const sumObserver = {
5643      *   sum: 0,
5644      *   next(value) {
5645      *     console.log('Adding: ' + value);
5646      *     this.sum = this.sum + value;
5647      *   },
5648      *   error() { // We actually could just remove this method,
5649      *   },        // since we do not really care about errors right now.
5650      *   complete() {
5651      *     console.log('Sum equals: ' + this.sum);
5652      *   }
5653      * };
5654      *
5655      * Rx.Observable.of(1, 2, 3) // Synchronously emits 1, 2, 3 and then completes.
5656      * .subscribe(sumObserver);
5657      *
5658      * // Logs:
5659      * // "Adding: 1"
5660      * // "Adding: 2"
5661      * // "Adding: 3"
5662      * // "Sum equals: 6"
5663      *
5664      *
5665      * @example <caption>Subscribe with functions</caption>
5666      * let sum = 0;
5667      *
5668      * Rx.Observable.of(1, 2, 3)
5669      * .subscribe(
5670      *   function(value) {
5671      *     console.log('Adding: ' + value);
5672      *     sum = sum + value;
5673      *   },
5674      *   undefined,
5675      *   function() {
5676      *     console.log('Sum equals: ' + sum);
5677      *   }
5678      * );
5679      *
5680      * // Logs:
5681      * // "Adding: 1"
5682      * // "Adding: 2"
5683      * // "Adding: 3"
5684      * // "Sum equals: 6"
5685      *
5686      *
5687      * @example <caption>Cancel a subscription</caption>
5688      * const subscription = Rx.Observable.interval(1000).subscribe(
5689      *   num => console.log(num),
5690      *   undefined,
5691      *   () => console.log('completed!') // Will not be called, even
5692      * );                                // when cancelling subscription
5693      *
5694      *
5695      * setTimeout(() => {
5696      *   subscription.unsubscribe();
5697      *   console.log('unsubscribed!');
5698      * }, 2500);
5699      *
5700      * // Logs:
5701      * // 0 after 1s
5702      * // 1 after 2s
5703      * // "unsubscribed!" after 2.5s
5704      *
5705      *
5706      * @param {Observer|Function} observerOrNext (optional) Either an observer with methods to be called,
5707      *  or the first of three possible handlers, which is the handler for each value emitted from the subscribed
5708      *  Observable.
5709      * @param {Function} error (optional) A handler for a terminal event resulting from an error. If no error handler is provided,
5710      *  the error will be thrown as unhandled.
5711      * @param {Function} complete (optional) A handler for a terminal event resulting from successful completion.
5712      * @return {ISubscription} a subscription reference to the registered handlers
5713      * @method subscribe
5714      */
5715     Observable.prototype.subscribe = function (observerOrNext, error, complete) {
5716         var operator = this.operator;
5717         var sink = toSubscriber_1.toSubscriber(observerOrNext, error, complete);
5718         if (operator) {
5719             operator.call(sink, this.source);
5720         }
5721         else {
5722             sink.add(this.source ? this._subscribe(sink) : this._trySubscribe(sink));
5723         }
5724         if (sink.syncErrorThrowable) {
5725             sink.syncErrorThrowable = false;
5726             if (sink.syncErrorThrown) {
5727                 throw sink.syncErrorValue;
5728             }
5729         }
5730         return sink;
5731     };
5732     Observable.prototype._trySubscribe = function (sink) {
5733         try {
5734             return this._subscribe(sink);
5735         }
5736         catch (err) {
5737             sink.syncErrorThrown = true;
5738             sink.syncErrorValue = err;
5739             sink.error(err);
5740         }
5741     };
5742     /**
5743      * @method forEach
5744      * @param {Function} next a handler for each value emitted by the observable
5745      * @param {PromiseConstructor} [PromiseCtor] a constructor function used to instantiate the Promise
5746      * @return {Promise} a promise that either resolves on observable completion or
5747      *  rejects with the handled error
5748      */
5749     Observable.prototype.forEach = function (next, PromiseCtor) {
5750         var _this = this;
5751         if (!PromiseCtor) {
5752             if (root_1.root.Rx && root_1.root.Rx.config && root_1.root.Rx.config.Promise) {
5753                 PromiseCtor = root_1.root.Rx.config.Promise;
5754             }
5755             else if (root_1.root.Promise) {
5756                 PromiseCtor = root_1.root.Promise;
5757             }
5758         }
5759         if (!PromiseCtor) {
5760             throw new Error('no Promise impl found');
5761         }
5762         return new PromiseCtor(function (resolve, reject) {
5763             // Must be declared in a separate statement to avoid a RefernceError when
5764             // accessing subscription below in the closure due to Temporal Dead Zone.
5765             var subscription;
5766             subscription = _this.subscribe(function (value) {
5767                 if (subscription) {
5768                     // if there is a subscription, then we can surmise
5769                     // the next handling is asynchronous. Any errors thrown
5770                     // need to be rejected explicitly and unsubscribe must be
5771                     // called manually
5772                     try {
5773                         next(value);
5774                     }
5775                     catch (err) {
5776                         reject(err);
5777                         subscription.unsubscribe();
5778                     }
5779                 }
5780                 else {
5781                     // if there is NO subscription, then we're getting a nexted
5782                     // value synchronously during subscription. We can just call it.
5783                     // If it errors, Observable's `subscribe` will ensure the
5784                     // unsubscription logic is called, then synchronously rethrow the error.
5785                     // After that, Promise will trap the error and send it
5786                     // down the rejection path.
5787                     next(value);
5788                 }
5789             }, reject, resolve);
5790         });
5791     };
5792     Observable.prototype._subscribe = function (subscriber) {
5793         return this.source.subscribe(subscriber);
5794     };
5795     /**
5796      * An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable
5797      * @method Symbol.observable
5798      * @return {Observable} this instance of the observable
5799      */
5800     Observable.prototype[observable_1.observable] = function () {
5801         return this;
5802     };
5803     /* tslint:enable:max-line-length */
5804     /**
5805      * Used to stitch together functional operators into a chain.
5806      * @method pipe
5807      * @return {Observable} the Observable result of all of the operators having
5808      * been called in the order they were passed in.
5809      *
5810      * @example
5811      *
5812      * import { map, filter, scan } from 'rxjs/operators';
5813      *
5814      * Rx.Observable.interval(1000)
5815      *   .pipe(
5816      *     filter(x => x % 2 === 0),
5817      *     map(x => x + x),
5818      *     scan((acc, x) => acc + x)
5819      *   )
5820      *   .subscribe(x => console.log(x))
5821      */
5822     Observable.prototype.pipe = function () {
5823         var operations = [];
5824         for (var _i = 0; _i < arguments.length; _i++) {
5825             operations[_i - 0] = arguments[_i];
5826         }
5827         if (operations.length === 0) {
5828             return this;
5829         }
5830         return pipe_1.pipeFromArray(operations)(this);
5831     };
5832     /* tslint:enable:max-line-length */
5833     Observable.prototype.toPromise = function (PromiseCtor) {
5834         var _this = this;
5835         if (!PromiseCtor) {
5836             if (root_1.root.Rx && root_1.root.Rx.config && root_1.root.Rx.config.Promise) {
5837                 PromiseCtor = root_1.root.Rx.config.Promise;
5838             }
5839             else if (root_1.root.Promise) {
5840                 PromiseCtor = root_1.root.Promise;
5841             }
5842         }
5843         if (!PromiseCtor) {
5844             throw new Error('no Promise impl found');
5845         }
5846         return new PromiseCtor(function (resolve, reject) {
5847             var value;
5848             _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); });
5849         });
5850     };
5851     // HACK: Since TypeScript inherits static properties too, we have to
5852     // fight against TypeScript here so Subject can have a different static create signature
5853     /**
5854      * Creates a new cold Observable by calling the Observable constructor
5855      * @static true
5856      * @owner Observable
5857      * @method create
5858      * @param {Function} subscribe? the subscriber function to be passed to the Observable constructor
5859      * @return {Observable} a new cold observable
5860      */
5861     Observable.create = function (subscribe) {
5862         return new Observable(subscribe);
5863     };
5864     return Observable;
5865 }());
5866 exports.Observable = Observable;
5867
5868 },{"./symbol/observable":216,"./util/pipe":236,"./util/root":237,"./util/toSubscriber":239}],30:[function(require,module,exports){
5869 "use strict";
5870 exports.empty = {
5871     closed: true,
5872     next: function (value) { },
5873     error: function (err) { throw err; },
5874     complete: function () { }
5875 };
5876
5877 },{}],31:[function(require,module,exports){
5878 "use strict";
5879 var __extends = (this && this.__extends) || function (d, b) {
5880     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5881     function __() { this.constructor = d; }
5882     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5883 };
5884 var Subscriber_1 = require('./Subscriber');
5885 /**
5886  * We need this JSDoc comment for affecting ESDoc.
5887  * @ignore
5888  * @extends {Ignored}
5889  */
5890 var OuterSubscriber = (function (_super) {
5891     __extends(OuterSubscriber, _super);
5892     function OuterSubscriber() {
5893         _super.apply(this, arguments);
5894     }
5895     OuterSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
5896         this.destination.next(innerValue);
5897     };
5898     OuterSubscriber.prototype.notifyError = function (error, innerSub) {
5899         this.destination.error(error);
5900     };
5901     OuterSubscriber.prototype.notifyComplete = function (innerSub) {
5902         this.destination.complete();
5903     };
5904     return OuterSubscriber;
5905 }(Subscriber_1.Subscriber));
5906 exports.OuterSubscriber = OuterSubscriber;
5907
5908 },{"./Subscriber":36}],32:[function(require,module,exports){
5909 "use strict";
5910 var __extends = (this && this.__extends) || function (d, b) {
5911     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5912     function __() { this.constructor = d; }
5913     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5914 };
5915 var Subject_1 = require('./Subject');
5916 var queue_1 = require('./scheduler/queue');
5917 var Subscription_1 = require('./Subscription');
5918 var observeOn_1 = require('./operators/observeOn');
5919 var ObjectUnsubscribedError_1 = require('./util/ObjectUnsubscribedError');
5920 var SubjectSubscription_1 = require('./SubjectSubscription');
5921 /**
5922  * @class ReplaySubject<T>
5923  */
5924 var ReplaySubject = (function (_super) {
5925     __extends(ReplaySubject, _super);
5926     function ReplaySubject(bufferSize, windowTime, scheduler) {
5927         if (bufferSize === void 0) { bufferSize = Number.POSITIVE_INFINITY; }
5928         if (windowTime === void 0) { windowTime = Number.POSITIVE_INFINITY; }
5929         _super.call(this);
5930         this.scheduler = scheduler;
5931         this._events = [];
5932         this._bufferSize = bufferSize < 1 ? 1 : bufferSize;
5933         this._windowTime = windowTime < 1 ? 1 : windowTime;
5934     }
5935     ReplaySubject.prototype.next = function (value) {
5936         var now = this._getNow();
5937         this._events.push(new ReplayEvent(now, value));
5938         this._trimBufferThenGetEvents();
5939         _super.prototype.next.call(this, value);
5940     };
5941     ReplaySubject.prototype._subscribe = function (subscriber) {
5942         var _events = this._trimBufferThenGetEvents();
5943         var scheduler = this.scheduler;
5944         var subscription;
5945         if (this.closed) {
5946             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
5947         }
5948         else if (this.hasError) {
5949             subscription = Subscription_1.Subscription.EMPTY;
5950         }
5951         else if (this.isStopped) {
5952             subscription = Subscription_1.Subscription.EMPTY;
5953         }
5954         else {
5955             this.observers.push(subscriber);
5956             subscription = new SubjectSubscription_1.SubjectSubscription(this, subscriber);
5957         }
5958         if (scheduler) {
5959             subscriber.add(subscriber = new observeOn_1.ObserveOnSubscriber(subscriber, scheduler));
5960         }
5961         var len = _events.length;
5962         for (var i = 0; i < len && !subscriber.closed; i++) {
5963             subscriber.next(_events[i].value);
5964         }
5965         if (this.hasError) {
5966             subscriber.error(this.thrownError);
5967         }
5968         else if (this.isStopped) {
5969             subscriber.complete();
5970         }
5971         return subscription;
5972     };
5973     ReplaySubject.prototype._getNow = function () {
5974         return (this.scheduler || queue_1.queue).now();
5975     };
5976     ReplaySubject.prototype._trimBufferThenGetEvents = function () {
5977         var now = this._getNow();
5978         var _bufferSize = this._bufferSize;
5979         var _windowTime = this._windowTime;
5980         var _events = this._events;
5981         var eventsCount = _events.length;
5982         var spliceCount = 0;
5983         // Trim events that fall out of the time window.
5984         // Start at the front of the list. Break early once
5985         // we encounter an event that falls within the window.
5986         while (spliceCount < eventsCount) {
5987             if ((now - _events[spliceCount].time) < _windowTime) {
5988                 break;
5989             }
5990             spliceCount++;
5991         }
5992         if (eventsCount > _bufferSize) {
5993             spliceCount = Math.max(spliceCount, eventsCount - _bufferSize);
5994         }
5995         if (spliceCount > 0) {
5996             _events.splice(0, spliceCount);
5997         }
5998         return _events;
5999     };
6000     return ReplaySubject;
6001 }(Subject_1.Subject));
6002 exports.ReplaySubject = ReplaySubject;
6003 var ReplayEvent = (function () {
6004     function ReplayEvent(time, value) {
6005         this.time = time;
6006         this.value = value;
6007     }
6008     return ReplayEvent;
6009 }());
6010
6011 },{"./Subject":34,"./SubjectSubscription":35,"./Subscription":37,"./operators/observeOn":182,"./scheduler/queue":214,"./util/ObjectUnsubscribedError":221}],33:[function(require,module,exports){
6012 "use strict";
6013 /**
6014  * An execution context and a data structure to order tasks and schedule their
6015  * execution. Provides a notion of (potentially virtual) time, through the
6016  * `now()` getter method.
6017  *
6018  * Each unit of work in a Scheduler is called an {@link Action}.
6019  *
6020  * ```ts
6021  * class Scheduler {
6022  *   now(): number;
6023  *   schedule(work, delay?, state?): Subscription;
6024  * }
6025  * ```
6026  *
6027  * @class Scheduler
6028  */
6029 var Scheduler = (function () {
6030     function Scheduler(SchedulerAction, now) {
6031         if (now === void 0) { now = Scheduler.now; }
6032         this.SchedulerAction = SchedulerAction;
6033         this.now = now;
6034     }
6035     /**
6036      * Schedules a function, `work`, for execution. May happen at some point in
6037      * the future, according to the `delay` parameter, if specified. May be passed
6038      * some context object, `state`, which will be passed to the `work` function.
6039      *
6040      * The given arguments will be processed an stored as an Action object in a
6041      * queue of actions.
6042      *
6043      * @param {function(state: ?T): ?Subscription} work A function representing a
6044      * task, or some unit of work to be executed by the Scheduler.
6045      * @param {number} [delay] Time to wait before executing the work, where the
6046      * time unit is implicit and defined by the Scheduler itself.
6047      * @param {T} [state] Some contextual data that the `work` function uses when
6048      * called by the Scheduler.
6049      * @return {Subscription} A subscription in order to be able to unsubscribe
6050      * the scheduled work.
6051      */
6052     Scheduler.prototype.schedule = function (work, delay, state) {
6053         if (delay === void 0) { delay = 0; }
6054         return new this.SchedulerAction(this, work).schedule(state, delay);
6055     };
6056     Scheduler.now = Date.now ? Date.now : function () { return +new Date(); };
6057     return Scheduler;
6058 }());
6059 exports.Scheduler = Scheduler;
6060
6061 },{}],34:[function(require,module,exports){
6062 "use strict";
6063 var __extends = (this && this.__extends) || function (d, b) {
6064     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6065     function __() { this.constructor = d; }
6066     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6067 };
6068 var Observable_1 = require('./Observable');
6069 var Subscriber_1 = require('./Subscriber');
6070 var Subscription_1 = require('./Subscription');
6071 var ObjectUnsubscribedError_1 = require('./util/ObjectUnsubscribedError');
6072 var SubjectSubscription_1 = require('./SubjectSubscription');
6073 var rxSubscriber_1 = require('./symbol/rxSubscriber');
6074 /**
6075  * @class SubjectSubscriber<T>
6076  */
6077 var SubjectSubscriber = (function (_super) {
6078     __extends(SubjectSubscriber, _super);
6079     function SubjectSubscriber(destination) {
6080         _super.call(this, destination);
6081         this.destination = destination;
6082     }
6083     return SubjectSubscriber;
6084 }(Subscriber_1.Subscriber));
6085 exports.SubjectSubscriber = SubjectSubscriber;
6086 /**
6087  * @class Subject<T>
6088  */
6089 var Subject = (function (_super) {
6090     __extends(Subject, _super);
6091     function Subject() {
6092         _super.call(this);
6093         this.observers = [];
6094         this.closed = false;
6095         this.isStopped = false;
6096         this.hasError = false;
6097         this.thrownError = null;
6098     }
6099     Subject.prototype[rxSubscriber_1.rxSubscriber] = function () {
6100         return new SubjectSubscriber(this);
6101     };
6102     Subject.prototype.lift = function (operator) {
6103         var subject = new AnonymousSubject(this, this);
6104         subject.operator = operator;
6105         return subject;
6106     };
6107     Subject.prototype.next = function (value) {
6108         if (this.closed) {
6109             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6110         }
6111         if (!this.isStopped) {
6112             var observers = this.observers;
6113             var len = observers.length;
6114             var copy = observers.slice();
6115             for (var i = 0; i < len; i++) {
6116                 copy[i].next(value);
6117             }
6118         }
6119     };
6120     Subject.prototype.error = function (err) {
6121         if (this.closed) {
6122             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6123         }
6124         this.hasError = true;
6125         this.thrownError = err;
6126         this.isStopped = true;
6127         var observers = this.observers;
6128         var len = observers.length;
6129         var copy = observers.slice();
6130         for (var i = 0; i < len; i++) {
6131             copy[i].error(err);
6132         }
6133         this.observers.length = 0;
6134     };
6135     Subject.prototype.complete = function () {
6136         if (this.closed) {
6137             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6138         }
6139         this.isStopped = true;
6140         var observers = this.observers;
6141         var len = observers.length;
6142         var copy = observers.slice();
6143         for (var i = 0; i < len; i++) {
6144             copy[i].complete();
6145         }
6146         this.observers.length = 0;
6147     };
6148     Subject.prototype.unsubscribe = function () {
6149         this.isStopped = true;
6150         this.closed = true;
6151         this.observers = null;
6152     };
6153     Subject.prototype._trySubscribe = function (subscriber) {
6154         if (this.closed) {
6155             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6156         }
6157         else {
6158             return _super.prototype._trySubscribe.call(this, subscriber);
6159         }
6160     };
6161     Subject.prototype._subscribe = function (subscriber) {
6162         if (this.closed) {
6163             throw new ObjectUnsubscribedError_1.ObjectUnsubscribedError();
6164         }
6165         else if (this.hasError) {
6166             subscriber.error(this.thrownError);
6167             return Subscription_1.Subscription.EMPTY;
6168         }
6169         else if (this.isStopped) {
6170             subscriber.complete();
6171             return Subscription_1.Subscription.EMPTY;
6172         }
6173         else {
6174             this.observers.push(subscriber);
6175             return new SubjectSubscription_1.SubjectSubscription(this, subscriber);
6176         }
6177     };
6178     Subject.prototype.asObservable = function () {
6179         var observable = new Observable_1.Observable();
6180         observable.source = this;
6181         return observable;
6182     };
6183     Subject.create = function (destination, source) {
6184         return new AnonymousSubject(destination, source);
6185     };
6186     return Subject;
6187 }(Observable_1.Observable));
6188 exports.Subject = Subject;
6189 /**
6190  * @class AnonymousSubject<T>
6191  */
6192 var AnonymousSubject = (function (_super) {
6193     __extends(AnonymousSubject, _super);
6194     function AnonymousSubject(destination, source) {
6195         _super.call(this);
6196         this.destination = destination;
6197         this.source = source;
6198     }
6199     AnonymousSubject.prototype.next = function (value) {
6200         var destination = this.destination;
6201         if (destination && destination.next) {
6202             destination.next(value);
6203         }
6204     };
6205     AnonymousSubject.prototype.error = function (err) {
6206         var destination = this.destination;
6207         if (destination && destination.error) {
6208             this.destination.error(err);
6209         }
6210     };
6211     AnonymousSubject.prototype.complete = function () {
6212         var destination = this.destination;
6213         if (destination && destination.complete) {
6214             this.destination.complete();
6215         }
6216     };
6217     AnonymousSubject.prototype._subscribe = function (subscriber) {
6218         var source = this.source;
6219         if (source) {
6220             return this.source.subscribe(subscriber);
6221         }
6222         else {
6223             return Subscription_1.Subscription.EMPTY;
6224         }
6225     };
6226     return AnonymousSubject;
6227 }(Subject));
6228 exports.AnonymousSubject = AnonymousSubject;
6229
6230 },{"./Observable":29,"./SubjectSubscription":35,"./Subscriber":36,"./Subscription":37,"./symbol/rxSubscriber":217,"./util/ObjectUnsubscribedError":221}],35:[function(require,module,exports){
6231 "use strict";
6232 var __extends = (this && this.__extends) || function (d, b) {
6233     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6234     function __() { this.constructor = d; }
6235     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6236 };
6237 var Subscription_1 = require('./Subscription');
6238 /**
6239  * We need this JSDoc comment for affecting ESDoc.
6240  * @ignore
6241  * @extends {Ignored}
6242  */
6243 var SubjectSubscription = (function (_super) {
6244     __extends(SubjectSubscription, _super);
6245     function SubjectSubscription(subject, subscriber) {
6246         _super.call(this);
6247         this.subject = subject;
6248         this.subscriber = subscriber;
6249         this.closed = false;
6250     }
6251     SubjectSubscription.prototype.unsubscribe = function () {
6252         if (this.closed) {
6253             return;
6254         }
6255         this.closed = true;
6256         var subject = this.subject;
6257         var observers = subject.observers;
6258         this.subject = null;
6259         if (!observers || observers.length === 0 || subject.isStopped || subject.closed) {
6260             return;
6261         }
6262         var subscriberIndex = observers.indexOf(this.subscriber);
6263         if (subscriberIndex !== -1) {
6264             observers.splice(subscriberIndex, 1);
6265         }
6266     };
6267     return SubjectSubscription;
6268 }(Subscription_1.Subscription));
6269 exports.SubjectSubscription = SubjectSubscription;
6270
6271 },{"./Subscription":37}],36:[function(require,module,exports){
6272 "use strict";
6273 var __extends = (this && this.__extends) || function (d, b) {
6274     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6275     function __() { this.constructor = d; }
6276     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6277 };
6278 var isFunction_1 = require('./util/isFunction');
6279 var Subscription_1 = require('./Subscription');
6280 var Observer_1 = require('./Observer');
6281 var rxSubscriber_1 = require('./symbol/rxSubscriber');
6282 /**
6283  * Implements the {@link Observer} interface and extends the
6284  * {@link Subscription} class. While the {@link Observer} is the public API for
6285  * consuming the values of an {@link Observable}, all Observers get converted to
6286  * a Subscriber, in order to provide Subscription-like capabilities such as
6287  * `unsubscribe`. Subscriber is a common type in RxJS, and crucial for
6288  * implementing operators, but it is rarely used as a public API.
6289  *
6290  * @class Subscriber<T>
6291  */
6292 var Subscriber = (function (_super) {
6293     __extends(Subscriber, _super);
6294     /**
6295      * @param {Observer|function(value: T): void} [destinationOrNext] A partially
6296      * defined Observer or a `next` callback function.
6297      * @param {function(e: ?any): void} [error] The `error` callback of an
6298      * Observer.
6299      * @param {function(): void} [complete] The `complete` callback of an
6300      * Observer.
6301      */
6302     function Subscriber(destinationOrNext, error, complete) {
6303         _super.call(this);
6304         this.syncErrorValue = null;
6305         this.syncErrorThrown = false;
6306         this.syncErrorThrowable = false;
6307         this.isStopped = false;
6308         switch (arguments.length) {
6309             case 0:
6310                 this.destination = Observer_1.empty;
6311                 break;
6312             case 1:
6313                 if (!destinationOrNext) {
6314                     this.destination = Observer_1.empty;
6315                     break;
6316                 }
6317                 if (typeof destinationOrNext === 'object') {
6318                     if (destinationOrNext instanceof Subscriber) {
6319                         this.destination = destinationOrNext;
6320                         this.destination.add(this);
6321                     }
6322                     else {
6323                         this.syncErrorThrowable = true;
6324                         this.destination = new SafeSubscriber(this, destinationOrNext);
6325                     }
6326                     break;
6327                 }
6328             default:
6329                 this.syncErrorThrowable = true;
6330                 this.destination = new SafeSubscriber(this, destinationOrNext, error, complete);
6331                 break;
6332         }
6333     }
6334     Subscriber.prototype[rxSubscriber_1.rxSubscriber] = function () { return this; };
6335     /**
6336      * A static factory for a Subscriber, given a (potentially partial) definition
6337      * of an Observer.
6338      * @param {function(x: ?T): void} [next] The `next` callback of an Observer.
6339      * @param {function(e: ?any): void} [error] The `error` callback of an
6340      * Observer.
6341      * @param {function(): void} [complete] The `complete` callback of an
6342      * Observer.
6343      * @return {Subscriber<T>} A Subscriber wrapping the (partially defined)
6344      * Observer represented by the given arguments.
6345      */
6346     Subscriber.create = function (next, error, complete) {
6347         var subscriber = new Subscriber(next, error, complete);
6348         subscriber.syncErrorThrowable = false;
6349         return subscriber;
6350     };
6351     /**
6352      * The {@link Observer} callback to receive notifications of type `next` from
6353      * the Observable, with a value. The Observable may call this method 0 or more
6354      * times.
6355      * @param {T} [value] The `next` value.
6356      * @return {void}
6357      */
6358     Subscriber.prototype.next = function (value) {
6359         if (!this.isStopped) {
6360             this._next(value);
6361         }
6362     };
6363     /**
6364      * The {@link Observer} callback to receive notifications of type `error` from
6365      * the Observable, with an attached {@link Error}. Notifies the Observer that
6366      * the Observable has experienced an error condition.
6367      * @param {any} [err] The `error` exception.
6368      * @return {void}
6369      */
6370     Subscriber.prototype.error = function (err) {
6371         if (!this.isStopped) {
6372             this.isStopped = true;
6373             this._error(err);
6374         }
6375     };
6376     /**
6377      * The {@link Observer} callback to receive a valueless notification of type
6378      * `complete` from the Observable. Notifies the Observer that the Observable
6379      * has finished sending push-based notifications.
6380      * @return {void}
6381      */
6382     Subscriber.prototype.complete = function () {
6383         if (!this.isStopped) {
6384             this.isStopped = true;
6385             this._complete();
6386         }
6387     };
6388     Subscriber.prototype.unsubscribe = function () {
6389         if (this.closed) {
6390             return;
6391         }
6392         this.isStopped = true;
6393         _super.prototype.unsubscribe.call(this);
6394     };
6395     Subscriber.prototype._next = function (value) {
6396         this.destination.next(value);
6397     };
6398     Subscriber.prototype._error = function (err) {
6399         this.destination.error(err);
6400         this.unsubscribe();
6401     };
6402     Subscriber.prototype._complete = function () {
6403         this.destination.complete();
6404         this.unsubscribe();
6405     };
6406     Subscriber.prototype._unsubscribeAndRecycle = function () {
6407         var _a = this, _parent = _a._parent, _parents = _a._parents;
6408         this._parent = null;
6409         this._parents = null;
6410         this.unsubscribe();
6411         this.closed = false;
6412         this.isStopped = false;
6413         this._parent = _parent;
6414         this._parents = _parents;
6415         return this;
6416     };
6417     return Subscriber;
6418 }(Subscription_1.Subscription));
6419 exports.Subscriber = Subscriber;
6420 /**
6421  * We need this JSDoc comment for affecting ESDoc.
6422  * @ignore
6423  * @extends {Ignored}
6424  */
6425 var SafeSubscriber = (function (_super) {
6426     __extends(SafeSubscriber, _super);
6427     function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) {
6428         _super.call(this);
6429         this._parentSubscriber = _parentSubscriber;
6430         var next;
6431         var context = this;
6432         if (isFunction_1.isFunction(observerOrNext)) {
6433             next = observerOrNext;
6434         }
6435         else if (observerOrNext) {
6436             next = observerOrNext.next;
6437             error = observerOrNext.error;
6438             complete = observerOrNext.complete;
6439             if (observerOrNext !== Observer_1.empty) {
6440                 context = Object.create(observerOrNext);
6441                 if (isFunction_1.isFunction(context.unsubscribe)) {
6442                     this.add(context.unsubscribe.bind(context));
6443                 }
6444                 context.unsubscribe = this.unsubscribe.bind(this);
6445             }
6446         }
6447         this._context = context;
6448         this._next = next;
6449         this._error = error;
6450         this._complete = complete;
6451     }
6452     SafeSubscriber.prototype.next = function (value) {
6453         if (!this.isStopped && this._next) {
6454             var _parentSubscriber = this._parentSubscriber;
6455             if (!_parentSubscriber.syncErrorThrowable) {
6456                 this.__tryOrUnsub(this._next, value);
6457             }
6458             else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {
6459                 this.unsubscribe();
6460             }
6461         }
6462     };
6463     SafeSubscriber.prototype.error = function (err) {
6464         if (!this.isStopped) {
6465             var _parentSubscriber = this._parentSubscriber;
6466             if (this._error) {
6467                 if (!_parentSubscriber.syncErrorThrowable) {
6468                     this.__tryOrUnsub(this._error, err);
6469                     this.unsubscribe();
6470                 }
6471                 else {
6472                     this.__tryOrSetError(_parentSubscriber, this._error, err);
6473                     this.unsubscribe();
6474                 }
6475             }
6476             else if (!_parentSubscriber.syncErrorThrowable) {
6477                 this.unsubscribe();
6478                 throw err;
6479             }
6480             else {
6481                 _parentSubscriber.syncErrorValue = err;
6482                 _parentSubscriber.syncErrorThrown = true;
6483                 this.unsubscribe();
6484             }
6485         }
6486     };
6487     SafeSubscriber.prototype.complete = function () {
6488         var _this = this;
6489         if (!this.isStopped) {
6490             var _parentSubscriber = this._parentSubscriber;
6491             if (this._complete) {
6492                 var wrappedComplete = function () { return _this._complete.call(_this._context); };
6493                 if (!_parentSubscriber.syncErrorThrowable) {
6494                     this.__tryOrUnsub(wrappedComplete);
6495                     this.unsubscribe();
6496                 }
6497                 else {
6498                     this.__tryOrSetError(_parentSubscriber, wrappedComplete);
6499                     this.unsubscribe();
6500                 }
6501             }
6502             else {
6503                 this.unsubscribe();
6504             }
6505         }
6506     };
6507     SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) {
6508         try {
6509             fn.call(this._context, value);
6510         }
6511         catch (err) {
6512             this.unsubscribe();
6513             throw err;
6514         }
6515     };
6516     SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) {
6517         try {
6518             fn.call(this._context, value);
6519         }
6520         catch (err) {
6521             parent.syncErrorValue = err;
6522             parent.syncErrorThrown = true;
6523             return true;
6524         }
6525         return false;
6526     };
6527     SafeSubscriber.prototype._unsubscribe = function () {
6528         var _parentSubscriber = this._parentSubscriber;
6529         this._context = null;
6530         this._parentSubscriber = null;
6531         _parentSubscriber.unsubscribe();
6532     };
6533     return SafeSubscriber;
6534 }(Subscriber));
6535
6536 },{"./Observer":30,"./Subscription":37,"./symbol/rxSubscriber":217,"./util/isFunction":230}],37:[function(require,module,exports){
6537 "use strict";
6538 var isArray_1 = require('./util/isArray');
6539 var isObject_1 = require('./util/isObject');
6540 var isFunction_1 = require('./util/isFunction');
6541 var tryCatch_1 = require('./util/tryCatch');
6542 var errorObject_1 = require('./util/errorObject');
6543 var UnsubscriptionError_1 = require('./util/UnsubscriptionError');
6544 /**
6545  * Represents a disposable resource, such as the execution of an Observable. A
6546  * Subscription has one important method, `unsubscribe`, that takes no argument
6547  * and just disposes the resource held by the subscription.
6548  *
6549  * Additionally, subscriptions may be grouped together through the `add()`
6550  * method, which will attach a child Subscription to the current Subscription.
6551  * When a Subscription is unsubscribed, all its children (and its grandchildren)
6552  * will be unsubscribed as well.
6553  *
6554  * @class Subscription
6555  */
6556 var Subscription = (function () {
6557     /**
6558      * @param {function(): void} [unsubscribe] A function describing how to
6559      * perform the disposal of resources when the `unsubscribe` method is called.
6560      */
6561     function Subscription(unsubscribe) {
6562         /**
6563          * A flag to indicate whether this Subscription has already been unsubscribed.
6564          * @type {boolean}
6565          */
6566         this.closed = false;
6567         this._parent = null;
6568         this._parents = null;
6569         this._subscriptions = null;
6570         if (unsubscribe) {
6571             this._unsubscribe = unsubscribe;
6572         }
6573     }
6574     /**
6575      * Disposes the resources held by the subscription. May, for instance, cancel
6576      * an ongoing Observable execution or cancel any other type of work that
6577      * started when the Subscription was created.
6578      * @return {void}
6579      */
6580     Subscription.prototype.unsubscribe = function () {
6581         var hasErrors = false;
6582         var errors;
6583         if (this.closed) {
6584             return;
6585         }
6586         var _a = this, _parent = _a._parent, _parents = _a._parents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions;
6587         this.closed = true;
6588         this._parent = null;
6589         this._parents = null;
6590         // null out _subscriptions first so any child subscriptions that attempt
6591         // to remove themselves from this subscription will noop
6592         this._subscriptions = null;
6593         var index = -1;
6594         var len = _parents ? _parents.length : 0;
6595         // if this._parent is null, then so is this._parents, and we
6596         // don't have to remove ourselves from any parent subscriptions.
6597         while (_parent) {
6598             _parent.remove(this);
6599             // if this._parents is null or index >= len,
6600             // then _parent is set to null, and the loop exits
6601             _parent = ++index < len && _parents[index] || null;
6602         }
6603         if (isFunction_1.isFunction(_unsubscribe)) {
6604             var trial = tryCatch_1.tryCatch(_unsubscribe).call(this);
6605             if (trial === errorObject_1.errorObject) {
6606                 hasErrors = true;
6607                 errors = errors || (errorObject_1.errorObject.e instanceof UnsubscriptionError_1.UnsubscriptionError ?
6608                     flattenUnsubscriptionErrors(errorObject_1.errorObject.e.errors) : [errorObject_1.errorObject.e]);
6609             }
6610         }
6611         if (isArray_1.isArray(_subscriptions)) {
6612             index = -1;
6613             len = _subscriptions.length;
6614             while (++index < len) {
6615                 var sub = _subscriptions[index];
6616                 if (isObject_1.isObject(sub)) {
6617                     var trial = tryCatch_1.tryCatch(sub.unsubscribe).call(sub);
6618                     if (trial === errorObject_1.errorObject) {
6619                         hasErrors = true;
6620                         errors = errors || [];
6621                         var err = errorObject_1.errorObject.e;
6622                         if (err instanceof UnsubscriptionError_1.UnsubscriptionError) {
6623                             errors = errors.concat(flattenUnsubscriptionErrors(err.errors));
6624                         }
6625                         else {
6626                             errors.push(err);
6627                         }
6628                     }
6629                 }
6630             }
6631         }
6632         if (hasErrors) {
6633             throw new UnsubscriptionError_1.UnsubscriptionError(errors);
6634         }
6635     };
6636     /**
6637      * Adds a tear down to be called during the unsubscribe() of this
6638      * Subscription.
6639      *
6640      * If the tear down being added is a subscription that is already
6641      * unsubscribed, is the same reference `add` is being called on, or is
6642      * `Subscription.EMPTY`, it will not be added.
6643      *
6644      * If this subscription is already in an `closed` state, the passed
6645      * tear down logic will be executed immediately.
6646      *
6647      * @param {TeardownLogic} teardown The additional logic to execute on
6648      * teardown.
6649      * @return {Subscription} Returns the Subscription used or created to be
6650      * added to the inner subscriptions list. This Subscription can be used with
6651      * `remove()` to remove the passed teardown logic from the inner subscriptions
6652      * list.
6653      */
6654     Subscription.prototype.add = function (teardown) {
6655         if (!teardown || (teardown === Subscription.EMPTY)) {
6656             return Subscription.EMPTY;
6657         }
6658         if (teardown === this) {
6659             return this;
6660         }
6661         var subscription = teardown;
6662         switch (typeof teardown) {
6663             case 'function':
6664                 subscription = new Subscription(teardown);
6665             case 'object':
6666                 if (subscription.closed || typeof subscription.unsubscribe !== 'function') {
6667                     return subscription;
6668                 }
6669                 else if (this.closed) {
6670                     subscription.unsubscribe();
6671                     return subscription;
6672                 }
6673                 else if (typeof subscription._addParent !== 'function' /* quack quack */) {
6674                     var tmp = subscription;
6675                     subscription = new Subscription();
6676                     subscription._subscriptions = [tmp];
6677                 }
6678                 break;
6679             default:
6680                 throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');
6681         }
6682         var subscriptions = this._subscriptions || (this._subscriptions = []);
6683         subscriptions.push(subscription);
6684         subscription._addParent(this);
6685         return subscription;
6686     };
6687     /**
6688      * Removes a Subscription from the internal list of subscriptions that will
6689      * unsubscribe during the unsubscribe process of this Subscription.
6690      * @param {Subscription} subscription The subscription to remove.
6691      * @return {void}
6692      */
6693     Subscription.prototype.remove = function (subscription) {
6694         var subscriptions = this._subscriptions;
6695         if (subscriptions) {
6696             var subscriptionIndex = subscriptions.indexOf(subscription);
6697             if (subscriptionIndex !== -1) {
6698                 subscriptions.splice(subscriptionIndex, 1);
6699             }
6700         }
6701     };
6702     Subscription.prototype._addParent = function (parent) {
6703         var _a = this, _parent = _a._parent, _parents = _a._parents;
6704         if (!_parent || _parent === parent) {
6705             // If we don't have a parent, or the new parent is the same as the
6706             // current parent, then set this._parent to the new parent.
6707             this._parent = parent;
6708         }
6709         else if (!_parents) {
6710             // If there's already one parent, but not multiple, allocate an Array to
6711             // store the rest of the parent Subscriptions.
6712             this._parents = [parent];
6713         }
6714         else if (_parents.indexOf(parent) === -1) {
6715             // Only add the new parent to the _parents list if it's not already there.
6716             _parents.push(parent);
6717         }
6718     };
6719     Subscription.EMPTY = (function (empty) {
6720         empty.closed = true;
6721         return empty;
6722     }(new Subscription()));
6723     return Subscription;
6724 }());
6725 exports.Subscription = Subscription;
6726 function flattenUnsubscriptionErrors(errors) {
6727     return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError_1.UnsubscriptionError) ? err.errors : err); }, []);
6728 }
6729
6730 },{"./util/UnsubscriptionError":224,"./util/errorObject":225,"./util/isArray":227,"./util/isFunction":230,"./util/isObject":232,"./util/tryCatch":240}],38:[function(require,module,exports){
6731 "use strict";
6732 var Observable_1 = require('../../Observable');
6733 var combineLatest_1 = require('../../observable/combineLatest');
6734 Observable_1.Observable.combineLatest = combineLatest_1.combineLatest;
6735
6736 },{"../../Observable":29,"../../observable/combineLatest":104}],39:[function(require,module,exports){
6737 "use strict";
6738 var Observable_1 = require('../../Observable');
6739 var concat_1 = require('../../observable/concat');
6740 Observable_1.Observable.concat = concat_1.concat;
6741
6742 },{"../../Observable":29,"../../observable/concat":105}],40:[function(require,module,exports){
6743 "use strict";
6744 var Observable_1 = require('../../Observable');
6745 var defer_1 = require('../../observable/defer');
6746 Observable_1.Observable.defer = defer_1.defer;
6747
6748 },{"../../Observable":29,"../../observable/defer":106}],41:[function(require,module,exports){
6749 "use strict";
6750 var Observable_1 = require('../../Observable');
6751 var empty_1 = require('../../observable/empty');
6752 Observable_1.Observable.empty = empty_1.empty;
6753
6754 },{"../../Observable":29,"../../observable/empty":107}],42:[function(require,module,exports){
6755 "use strict";
6756 var Observable_1 = require('../../Observable');
6757 var from_1 = require('../../observable/from');
6758 Observable_1.Observable.from = from_1.from;
6759
6760 },{"../../Observable":29,"../../observable/from":108}],43:[function(require,module,exports){
6761 "use strict";
6762 var Observable_1 = require('../../Observable');
6763 var fromEvent_1 = require('../../observable/fromEvent');
6764 Observable_1.Observable.fromEvent = fromEvent_1.fromEvent;
6765
6766 },{"../../Observable":29,"../../observable/fromEvent":109}],44:[function(require,module,exports){
6767 "use strict";
6768 var Observable_1 = require('../../Observable');
6769 var fromPromise_1 = require('../../observable/fromPromise');
6770 Observable_1.Observable.fromPromise = fromPromise_1.fromPromise;
6771
6772 },{"../../Observable":29,"../../observable/fromPromise":110}],45:[function(require,module,exports){
6773 "use strict";
6774 var Observable_1 = require('../../Observable');
6775 var merge_1 = require('../../observable/merge');
6776 Observable_1.Observable.merge = merge_1.merge;
6777
6778 },{"../../Observable":29,"../../observable/merge":111}],46:[function(require,module,exports){
6779 "use strict";
6780 var Observable_1 = require('../../Observable');
6781 var of_1 = require('../../observable/of');
6782 Observable_1.Observable.of = of_1.of;
6783
6784 },{"../../Observable":29,"../../observable/of":112}],47:[function(require,module,exports){
6785 "use strict";
6786 var Observable_1 = require('../../Observable');
6787 var throw_1 = require('../../observable/throw');
6788 Observable_1.Observable.throw = throw_1._throw;
6789
6790 },{"../../Observable":29,"../../observable/throw":113}],48:[function(require,module,exports){
6791 "use strict";
6792 var Observable_1 = require('../../Observable');
6793 var timer_1 = require('../../observable/timer');
6794 Observable_1.Observable.timer = timer_1.timer;
6795
6796 },{"../../Observable":29,"../../observable/timer":114}],49:[function(require,module,exports){
6797 "use strict";
6798 var Observable_1 = require('../../Observable');
6799 var zip_1 = require('../../observable/zip');
6800 Observable_1.Observable.zip = zip_1.zip;
6801
6802 },{"../../Observable":29,"../../observable/zip":115}],50:[function(require,module,exports){
6803 "use strict";
6804 var Observable_1 = require('../../Observable');
6805 var auditTime_1 = require('../../operator/auditTime');
6806 Observable_1.Observable.prototype.auditTime = auditTime_1.auditTime;
6807
6808 },{"../../Observable":29,"../../operator/auditTime":116}],51:[function(require,module,exports){
6809 "use strict";
6810 var Observable_1 = require('../../Observable');
6811 var buffer_1 = require('../../operator/buffer');
6812 Observable_1.Observable.prototype.buffer = buffer_1.buffer;
6813
6814 },{"../../Observable":29,"../../operator/buffer":117}],52:[function(require,module,exports){
6815 "use strict";
6816 var Observable_1 = require('../../Observable');
6817 var bufferCount_1 = require('../../operator/bufferCount');
6818 Observable_1.Observable.prototype.bufferCount = bufferCount_1.bufferCount;
6819
6820 },{"../../Observable":29,"../../operator/bufferCount":118}],53:[function(require,module,exports){
6821 "use strict";
6822 var Observable_1 = require('../../Observable');
6823 var bufferWhen_1 = require('../../operator/bufferWhen');
6824 Observable_1.Observable.prototype.bufferWhen = bufferWhen_1.bufferWhen;
6825
6826 },{"../../Observable":29,"../../operator/bufferWhen":119}],54:[function(require,module,exports){
6827 "use strict";
6828 var Observable_1 = require('../../Observable');
6829 var catch_1 = require('../../operator/catch');
6830 Observable_1.Observable.prototype.catch = catch_1._catch;
6831 Observable_1.Observable.prototype._catch = catch_1._catch;
6832
6833 },{"../../Observable":29,"../../operator/catch":120}],55:[function(require,module,exports){
6834 "use strict";
6835 var Observable_1 = require('../../Observable');
6836 var combineLatest_1 = require('../../operator/combineLatest');
6837 Observable_1.Observable.prototype.combineLatest = combineLatest_1.combineLatest;
6838
6839 },{"../../Observable":29,"../../operator/combineLatest":121}],56:[function(require,module,exports){
6840 "use strict";
6841 var Observable_1 = require('../../Observable');
6842 var concat_1 = require('../../operator/concat');
6843 Observable_1.Observable.prototype.concat = concat_1.concat;
6844
6845 },{"../../Observable":29,"../../operator/concat":122}],57:[function(require,module,exports){
6846 "use strict";
6847 var Observable_1 = require('../../Observable');
6848 var debounceTime_1 = require('../../operator/debounceTime');
6849 Observable_1.Observable.prototype.debounceTime = debounceTime_1.debounceTime;
6850
6851 },{"../../Observable":29,"../../operator/debounceTime":123}],58:[function(require,module,exports){
6852 "use strict";
6853 var Observable_1 = require('../../Observable');
6854 var delay_1 = require('../../operator/delay');
6855 Observable_1.Observable.prototype.delay = delay_1.delay;
6856
6857 },{"../../Observable":29,"../../operator/delay":124}],59:[function(require,module,exports){
6858 "use strict";
6859 var Observable_1 = require('../../Observable');
6860 var distinct_1 = require('../../operator/distinct');
6861 Observable_1.Observable.prototype.distinct = distinct_1.distinct;
6862
6863 },{"../../Observable":29,"../../operator/distinct":125}],60:[function(require,module,exports){
6864 "use strict";
6865 var Observable_1 = require('../../Observable');
6866 var distinctUntilChanged_1 = require('../../operator/distinctUntilChanged');
6867 Observable_1.Observable.prototype.distinctUntilChanged = distinctUntilChanged_1.distinctUntilChanged;
6868
6869 },{"../../Observable":29,"../../operator/distinctUntilChanged":126}],61:[function(require,module,exports){
6870 "use strict";
6871 var Observable_1 = require('../../Observable');
6872 var do_1 = require('../../operator/do');
6873 Observable_1.Observable.prototype.do = do_1._do;
6874 Observable_1.Observable.prototype._do = do_1._do;
6875
6876 },{"../../Observable":29,"../../operator/do":127}],62:[function(require,module,exports){
6877 "use strict";
6878 var Observable_1 = require('../../Observable');
6879 var expand_1 = require('../../operator/expand');
6880 Observable_1.Observable.prototype.expand = expand_1.expand;
6881
6882 },{"../../Observable":29,"../../operator/expand":128}],63:[function(require,module,exports){
6883 "use strict";
6884 var Observable_1 = require('../../Observable');
6885 var filter_1 = require('../../operator/filter');
6886 Observable_1.Observable.prototype.filter = filter_1.filter;
6887
6888 },{"../../Observable":29,"../../operator/filter":129}],64:[function(require,module,exports){
6889 "use strict";
6890 var Observable_1 = require('../../Observable');
6891 var finally_1 = require('../../operator/finally');
6892 Observable_1.Observable.prototype.finally = finally_1._finally;
6893 Observable_1.Observable.prototype._finally = finally_1._finally;
6894
6895 },{"../../Observable":29,"../../operator/finally":130}],65:[function(require,module,exports){
6896 "use strict";
6897 var Observable_1 = require('../../Observable');
6898 var first_1 = require('../../operator/first');
6899 Observable_1.Observable.prototype.first = first_1.first;
6900
6901 },{"../../Observable":29,"../../operator/first":131}],66:[function(require,module,exports){
6902 "use strict";
6903 var Observable_1 = require('../../Observable');
6904 var last_1 = require('../../operator/last');
6905 Observable_1.Observable.prototype.last = last_1.last;
6906
6907 },{"../../Observable":29,"../../operator/last":132}],67:[function(require,module,exports){
6908 "use strict";
6909 var Observable_1 = require('../../Observable');
6910 var map_1 = require('../../operator/map');
6911 Observable_1.Observable.prototype.map = map_1.map;
6912
6913 },{"../../Observable":29,"../../operator/map":133}],68:[function(require,module,exports){
6914 "use strict";
6915 var Observable_1 = require('../../Observable');
6916 var merge_1 = require('../../operator/merge');
6917 Observable_1.Observable.prototype.merge = merge_1.merge;
6918
6919 },{"../../Observable":29,"../../operator/merge":134}],69:[function(require,module,exports){
6920 "use strict";
6921 var Observable_1 = require('../../Observable');
6922 var mergeAll_1 = require('../../operator/mergeAll');
6923 Observable_1.Observable.prototype.mergeAll = mergeAll_1.mergeAll;
6924
6925 },{"../../Observable":29,"../../operator/mergeAll":135}],70:[function(require,module,exports){
6926 "use strict";
6927 var Observable_1 = require('../../Observable');
6928 var mergeMap_1 = require('../../operator/mergeMap');
6929 Observable_1.Observable.prototype.mergeMap = mergeMap_1.mergeMap;
6930 Observable_1.Observable.prototype.flatMap = mergeMap_1.mergeMap;
6931
6932 },{"../../Observable":29,"../../operator/mergeMap":136}],71:[function(require,module,exports){
6933 "use strict";
6934 var Observable_1 = require('../../Observable');
6935 var pairwise_1 = require('../../operator/pairwise');
6936 Observable_1.Observable.prototype.pairwise = pairwise_1.pairwise;
6937
6938 },{"../../Observable":29,"../../operator/pairwise":137}],72:[function(require,module,exports){
6939 "use strict";
6940 var Observable_1 = require('../../Observable');
6941 var pluck_1 = require('../../operator/pluck');
6942 Observable_1.Observable.prototype.pluck = pluck_1.pluck;
6943
6944 },{"../../Observable":29,"../../operator/pluck":138}],73:[function(require,module,exports){
6945 "use strict";
6946 var Observable_1 = require('../../Observable');
6947 var publish_1 = require('../../operator/publish');
6948 Observable_1.Observable.prototype.publish = publish_1.publish;
6949
6950 },{"../../Observable":29,"../../operator/publish":139}],74:[function(require,module,exports){
6951 "use strict";
6952 var Observable_1 = require('../../Observable');
6953 var publishReplay_1 = require('../../operator/publishReplay');
6954 Observable_1.Observable.prototype.publishReplay = publishReplay_1.publishReplay;
6955
6956 },{"../../Observable":29,"../../operator/publishReplay":140}],75:[function(require,module,exports){
6957 "use strict";
6958 var Observable_1 = require('../../Observable');
6959 var reduce_1 = require('../../operator/reduce');
6960 Observable_1.Observable.prototype.reduce = reduce_1.reduce;
6961
6962 },{"../../Observable":29,"../../operator/reduce":141}],76:[function(require,module,exports){
6963 "use strict";
6964 var Observable_1 = require('../../Observable');
6965 var retry_1 = require('../../operator/retry');
6966 Observable_1.Observable.prototype.retry = retry_1.retry;
6967
6968 },{"../../Observable":29,"../../operator/retry":142}],77:[function(require,module,exports){
6969 "use strict";
6970 var Observable_1 = require('../../Observable');
6971 var sample_1 = require('../../operator/sample');
6972 Observable_1.Observable.prototype.sample = sample_1.sample;
6973
6974 },{"../../Observable":29,"../../operator/sample":143}],78:[function(require,module,exports){
6975 "use strict";
6976 var Observable_1 = require('../../Observable');
6977 var scan_1 = require('../../operator/scan');
6978 Observable_1.Observable.prototype.scan = scan_1.scan;
6979
6980 },{"../../Observable":29,"../../operator/scan":144}],79:[function(require,module,exports){
6981 "use strict";
6982 var Observable_1 = require('../../Observable');
6983 var share_1 = require('../../operator/share');
6984 Observable_1.Observable.prototype.share = share_1.share;
6985
6986 },{"../../Observable":29,"../../operator/share":145}],80:[function(require,module,exports){
6987 "use strict";
6988 var Observable_1 = require('../../Observable');
6989 var skip_1 = require('../../operator/skip');
6990 Observable_1.Observable.prototype.skip = skip_1.skip;
6991
6992 },{"../../Observable":29,"../../operator/skip":146}],81:[function(require,module,exports){
6993 "use strict";
6994 var Observable_1 = require('../../Observable');
6995 var skipUntil_1 = require('../../operator/skipUntil');
6996 Observable_1.Observable.prototype.skipUntil = skipUntil_1.skipUntil;
6997
6998 },{"../../Observable":29,"../../operator/skipUntil":147}],82:[function(require,module,exports){
6999 "use strict";
7000 var Observable_1 = require('../../Observable');
7001 var skipWhile_1 = require('../../operator/skipWhile');
7002 Observable_1.Observable.prototype.skipWhile = skipWhile_1.skipWhile;
7003
7004 },{"../../Observable":29,"../../operator/skipWhile":148}],83:[function(require,module,exports){
7005 "use strict";
7006 var Observable_1 = require('../../Observable');
7007 var startWith_1 = require('../../operator/startWith');
7008 Observable_1.Observable.prototype.startWith = startWith_1.startWith;
7009
7010 },{"../../Observable":29,"../../operator/startWith":149}],84:[function(require,module,exports){
7011 "use strict";
7012 var Observable_1 = require('../../Observable');
7013 var switchMap_1 = require('../../operator/switchMap');
7014 Observable_1.Observable.prototype.switchMap = switchMap_1.switchMap;
7015
7016 },{"../../Observable":29,"../../operator/switchMap":150}],85:[function(require,module,exports){
7017 "use strict";
7018 var Observable_1 = require('../../Observable');
7019 var take_1 = require('../../operator/take');
7020 Observable_1.Observable.prototype.take = take_1.take;
7021
7022 },{"../../Observable":29,"../../operator/take":151}],86:[function(require,module,exports){
7023 "use strict";
7024 var Observable_1 = require('../../Observable');
7025 var takeUntil_1 = require('../../operator/takeUntil');
7026 Observable_1.Observable.prototype.takeUntil = takeUntil_1.takeUntil;
7027
7028 },{"../../Observable":29,"../../operator/takeUntil":152}],87:[function(require,module,exports){
7029 "use strict";
7030 var Observable_1 = require('../../Observable');
7031 var takeWhile_1 = require('../../operator/takeWhile');
7032 Observable_1.Observable.prototype.takeWhile = takeWhile_1.takeWhile;
7033
7034 },{"../../Observable":29,"../../operator/takeWhile":153}],88:[function(require,module,exports){
7035 "use strict";
7036 var Observable_1 = require('../../Observable');
7037 var throttleTime_1 = require('../../operator/throttleTime');
7038 Observable_1.Observable.prototype.throttleTime = throttleTime_1.throttleTime;
7039
7040 },{"../../Observable":29,"../../operator/throttleTime":154}],89:[function(require,module,exports){
7041 "use strict";
7042 var Observable_1 = require('../../Observable');
7043 var timeout_1 = require('../../operator/timeout');
7044 Observable_1.Observable.prototype.timeout = timeout_1.timeout;
7045
7046 },{"../../Observable":29,"../../operator/timeout":155}],90:[function(require,module,exports){
7047 "use strict";
7048 var Observable_1 = require('../../Observable');
7049 var withLatestFrom_1 = require('../../operator/withLatestFrom');
7050 Observable_1.Observable.prototype.withLatestFrom = withLatestFrom_1.withLatestFrom;
7051
7052 },{"../../Observable":29,"../../operator/withLatestFrom":156}],91:[function(require,module,exports){
7053 "use strict";
7054 var Observable_1 = require('../../Observable');
7055 var zip_1 = require('../../operator/zip');
7056 Observable_1.Observable.prototype.zip = zip_1.zipProto;
7057
7058 },{"../../Observable":29,"../../operator/zip":157}],92:[function(require,module,exports){
7059 "use strict";
7060 var __extends = (this && this.__extends) || function (d, b) {
7061     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7062     function __() { this.constructor = d; }
7063     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7064 };
7065 var Observable_1 = require('../Observable');
7066 var ScalarObservable_1 = require('./ScalarObservable');
7067 var EmptyObservable_1 = require('./EmptyObservable');
7068 /**
7069  * We need this JSDoc comment for affecting ESDoc.
7070  * @extends {Ignored}
7071  * @hide true
7072  */
7073 var ArrayLikeObservable = (function (_super) {
7074     __extends(ArrayLikeObservable, _super);
7075     function ArrayLikeObservable(arrayLike, scheduler) {
7076         _super.call(this);
7077         this.arrayLike = arrayLike;
7078         this.scheduler = scheduler;
7079         if (!scheduler && arrayLike.length === 1) {
7080             this._isScalar = true;
7081             this.value = arrayLike[0];
7082         }
7083     }
7084     ArrayLikeObservable.create = function (arrayLike, scheduler) {
7085         var length = arrayLike.length;
7086         if (length === 0) {
7087             return new EmptyObservable_1.EmptyObservable();
7088         }
7089         else if (length === 1) {
7090             return new ScalarObservable_1.ScalarObservable(arrayLike[0], scheduler);
7091         }
7092         else {
7093             return new ArrayLikeObservable(arrayLike, scheduler);
7094         }
7095     };
7096     ArrayLikeObservable.dispatch = function (state) {
7097         var arrayLike = state.arrayLike, index = state.index, length = state.length, subscriber = state.subscriber;
7098         if (subscriber.closed) {
7099             return;
7100         }
7101         if (index >= length) {
7102             subscriber.complete();
7103             return;
7104         }
7105         subscriber.next(arrayLike[index]);
7106         state.index = index + 1;
7107         this.schedule(state);
7108     };
7109     ArrayLikeObservable.prototype._subscribe = function (subscriber) {
7110         var index = 0;
7111         var _a = this, arrayLike = _a.arrayLike, scheduler = _a.scheduler;
7112         var length = arrayLike.length;
7113         if (scheduler) {
7114             return scheduler.schedule(ArrayLikeObservable.dispatch, 0, {
7115                 arrayLike: arrayLike, index: index, length: length, subscriber: subscriber
7116             });
7117         }
7118         else {
7119             for (var i = 0; i < length && !subscriber.closed; i++) {
7120                 subscriber.next(arrayLike[i]);
7121             }
7122             subscriber.complete();
7123         }
7124     };
7125     return ArrayLikeObservable;
7126 }(Observable_1.Observable));
7127 exports.ArrayLikeObservable = ArrayLikeObservable;
7128
7129 },{"../Observable":29,"./EmptyObservable":96,"./ScalarObservable":102}],93:[function(require,module,exports){
7130 "use strict";
7131 var __extends = (this && this.__extends) || function (d, b) {
7132     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7133     function __() { this.constructor = d; }
7134     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7135 };
7136 var Observable_1 = require('../Observable');
7137 var ScalarObservable_1 = require('./ScalarObservable');
7138 var EmptyObservable_1 = require('./EmptyObservable');
7139 var isScheduler_1 = require('../util/isScheduler');
7140 /**
7141  * We need this JSDoc comment for affecting ESDoc.
7142  * @extends {Ignored}
7143  * @hide true
7144  */
7145 var ArrayObservable = (function (_super) {
7146     __extends(ArrayObservable, _super);
7147     function ArrayObservable(array, scheduler) {
7148         _super.call(this);
7149         this.array = array;
7150         this.scheduler = scheduler;
7151         if (!scheduler && array.length === 1) {
7152             this._isScalar = true;
7153             this.value = array[0];
7154         }
7155     }
7156     ArrayObservable.create = function (array, scheduler) {
7157         return new ArrayObservable(array, scheduler);
7158     };
7159     /**
7160      * Creates an Observable that emits some values you specify as arguments,
7161      * immediately one after the other, and then emits a complete notification.
7162      *
7163      * <span class="informal">Emits the arguments you provide, then completes.
7164      * </span>
7165      *
7166      * <img src="./img/of.png" width="100%">
7167      *
7168      * This static operator is useful for creating a simple Observable that only
7169      * emits the arguments given, and the complete notification thereafter. It can
7170      * be used for composing with other Observables, such as with {@link concat}.
7171      * By default, it uses a `null` IScheduler, which means the `next`
7172      * notifications are sent synchronously, although with a different IScheduler
7173      * it is possible to determine when those notifications will be delivered.
7174      *
7175      * @example <caption>Emit 10, 20, 30, then 'a', 'b', 'c', then start ticking every second.</caption>
7176      * var numbers = Rx.Observable.of(10, 20, 30);
7177      * var letters = Rx.Observable.of('a', 'b', 'c');
7178      * var interval = Rx.Observable.interval(1000);
7179      * var result = numbers.concat(letters).concat(interval);
7180      * result.subscribe(x => console.log(x));
7181      *
7182      * @see {@link create}
7183      * @see {@link empty}
7184      * @see {@link never}
7185      * @see {@link throw}
7186      *
7187      * @param {...T} values Arguments that represent `next` values to be emitted.
7188      * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
7189      * the emissions of the `next` notifications.
7190      * @return {Observable<T>} An Observable that emits each given input value.
7191      * @static true
7192      * @name of
7193      * @owner Observable
7194      */
7195     ArrayObservable.of = function () {
7196         var array = [];
7197         for (var _i = 0; _i < arguments.length; _i++) {
7198             array[_i - 0] = arguments[_i];
7199         }
7200         var scheduler = array[array.length - 1];
7201         if (isScheduler_1.isScheduler(scheduler)) {
7202             array.pop();
7203         }
7204         else {
7205             scheduler = null;
7206         }
7207         var len = array.length;
7208         if (len > 1) {
7209             return new ArrayObservable(array, scheduler);
7210         }
7211         else if (len === 1) {
7212             return new ScalarObservable_1.ScalarObservable(array[0], scheduler);
7213         }
7214         else {
7215             return new EmptyObservable_1.EmptyObservable(scheduler);
7216         }
7217     };
7218     ArrayObservable.dispatch = function (state) {
7219         var array = state.array, index = state.index, count = state.count, subscriber = state.subscriber;
7220         if (index >= count) {
7221             subscriber.complete();
7222             return;
7223         }
7224         subscriber.next(array[index]);
7225         if (subscriber.closed) {
7226             return;
7227         }
7228         state.index = index + 1;
7229         this.schedule(state);
7230     };
7231     ArrayObservable.prototype._subscribe = function (subscriber) {
7232         var index = 0;
7233         var array = this.array;
7234         var count = array.length;
7235         var scheduler = this.scheduler;
7236         if (scheduler) {
7237             return scheduler.schedule(ArrayObservable.dispatch, 0, {
7238                 array: array, index: index, count: count, subscriber: subscriber
7239             });
7240         }
7241         else {
7242             for (var i = 0; i < count && !subscriber.closed; i++) {
7243                 subscriber.next(array[i]);
7244             }
7245             subscriber.complete();
7246         }
7247     };
7248     return ArrayObservable;
7249 }(Observable_1.Observable));
7250 exports.ArrayObservable = ArrayObservable;
7251
7252 },{"../Observable":29,"../util/isScheduler":234,"./EmptyObservable":96,"./ScalarObservable":102}],94:[function(require,module,exports){
7253 "use strict";
7254 var __extends = (this && this.__extends) || function (d, b) {
7255     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7256     function __() { this.constructor = d; }
7257     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7258 };
7259 var Subject_1 = require('../Subject');
7260 var Observable_1 = require('../Observable');
7261 var Subscriber_1 = require('../Subscriber');
7262 var Subscription_1 = require('../Subscription');
7263 var refCount_1 = require('../operators/refCount');
7264 /**
7265  * @class ConnectableObservable<T>
7266  */
7267 var ConnectableObservable = (function (_super) {
7268     __extends(ConnectableObservable, _super);
7269     function ConnectableObservable(source, subjectFactory) {
7270         _super.call(this);
7271         this.source = source;
7272         this.subjectFactory = subjectFactory;
7273         this._refCount = 0;
7274         this._isComplete = false;
7275     }
7276     ConnectableObservable.prototype._subscribe = function (subscriber) {
7277         return this.getSubject().subscribe(subscriber);
7278     };
7279     ConnectableObservable.prototype.getSubject = function () {
7280         var subject = this._subject;
7281         if (!subject || subject.isStopped) {
7282             this._subject = this.subjectFactory();
7283         }
7284         return this._subject;
7285     };
7286     ConnectableObservable.prototype.connect = function () {
7287         var connection = this._connection;
7288         if (!connection) {
7289             this._isComplete = false;
7290             connection = this._connection = new Subscription_1.Subscription();
7291             connection.add(this.source
7292                 .subscribe(new ConnectableSubscriber(this.getSubject(), this)));
7293             if (connection.closed) {
7294                 this._connection = null;
7295                 connection = Subscription_1.Subscription.EMPTY;
7296             }
7297             else {
7298                 this._connection = connection;
7299             }
7300         }
7301         return connection;
7302     };
7303     ConnectableObservable.prototype.refCount = function () {
7304         return refCount_1.refCount()(this);
7305     };
7306     return ConnectableObservable;
7307 }(Observable_1.Observable));
7308 exports.ConnectableObservable = ConnectableObservable;
7309 var connectableProto = ConnectableObservable.prototype;
7310 exports.connectableObservableDescriptor = {
7311     operator: { value: null },
7312     _refCount: { value: 0, writable: true },
7313     _subject: { value: null, writable: true },
7314     _connection: { value: null, writable: true },
7315     _subscribe: { value: connectableProto._subscribe },
7316     _isComplete: { value: connectableProto._isComplete, writable: true },
7317     getSubject: { value: connectableProto.getSubject },
7318     connect: { value: connectableProto.connect },
7319     refCount: { value: connectableProto.refCount }
7320 };
7321 var ConnectableSubscriber = (function (_super) {
7322     __extends(ConnectableSubscriber, _super);
7323     function ConnectableSubscriber(destination, connectable) {
7324         _super.call(this, destination);
7325         this.connectable = connectable;
7326     }
7327     ConnectableSubscriber.prototype._error = function (err) {
7328         this._unsubscribe();
7329         _super.prototype._error.call(this, err);
7330     };
7331     ConnectableSubscriber.prototype._complete = function () {
7332         this.connectable._isComplete = true;
7333         this._unsubscribe();
7334         _super.prototype._complete.call(this);
7335     };
7336     ConnectableSubscriber.prototype._unsubscribe = function () {
7337         var connectable = this.connectable;
7338         if (connectable) {
7339             this.connectable = null;
7340             var connection = connectable._connection;
7341             connectable._refCount = 0;
7342             connectable._subject = null;
7343             connectable._connection = null;
7344             if (connection) {
7345                 connection.unsubscribe();
7346             }
7347         }
7348     };
7349     return ConnectableSubscriber;
7350 }(Subject_1.SubjectSubscriber));
7351 var RefCountOperator = (function () {
7352     function RefCountOperator(connectable) {
7353         this.connectable = connectable;
7354     }
7355     RefCountOperator.prototype.call = function (subscriber, source) {
7356         var connectable = this.connectable;
7357         connectable._refCount++;
7358         var refCounter = new RefCountSubscriber(subscriber, connectable);
7359         var subscription = source.subscribe(refCounter);
7360         if (!refCounter.closed) {
7361             refCounter.connection = connectable.connect();
7362         }
7363         return subscription;
7364     };
7365     return RefCountOperator;
7366 }());
7367 var RefCountSubscriber = (function (_super) {
7368     __extends(RefCountSubscriber, _super);
7369     function RefCountSubscriber(destination, connectable) {
7370         _super.call(this, destination);
7371         this.connectable = connectable;
7372     }
7373     RefCountSubscriber.prototype._unsubscribe = function () {
7374         var connectable = this.connectable;
7375         if (!connectable) {
7376             this.connection = null;
7377             return;
7378         }
7379         this.connectable = null;
7380         var refCount = connectable._refCount;
7381         if (refCount <= 0) {
7382             this.connection = null;
7383             return;
7384         }
7385         connectable._refCount = refCount - 1;
7386         if (refCount > 1) {
7387             this.connection = null;
7388             return;
7389         }
7390         ///
7391         // Compare the local RefCountSubscriber's connection Subscription to the
7392         // connection Subscription on the shared ConnectableObservable. In cases
7393         // where the ConnectableObservable source synchronously emits values, and
7394         // the RefCountSubscriber's downstream Observers synchronously unsubscribe,
7395         // execution continues to here before the RefCountOperator has a chance to
7396         // supply the RefCountSubscriber with the shared connection Subscription.
7397         // For example:
7398         // ```
7399         // Observable.range(0, 10)
7400         //   .publish()
7401         //   .refCount()
7402         //   .take(5)
7403         //   .subscribe();
7404         // ```
7405         // In order to account for this case, RefCountSubscriber should only dispose
7406         // the ConnectableObservable's shared connection Subscription if the
7407         // connection Subscription exists, *and* either:
7408         //   a. RefCountSubscriber doesn't have a reference to the shared connection
7409         //      Subscription yet, or,
7410         //   b. RefCountSubscriber's connection Subscription reference is identical
7411         //      to the shared connection Subscription
7412         ///
7413         var connection = this.connection;
7414         var sharedConnection = connectable._connection;
7415         this.connection = null;
7416         if (sharedConnection && (!connection || sharedConnection === connection)) {
7417             sharedConnection.unsubscribe();
7418         }
7419     };
7420     return RefCountSubscriber;
7421 }(Subscriber_1.Subscriber));
7422
7423 },{"../Observable":29,"../Subject":34,"../Subscriber":36,"../Subscription":37,"../operators/refCount":188}],95:[function(require,module,exports){
7424 "use strict";
7425 var __extends = (this && this.__extends) || function (d, b) {
7426     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7427     function __() { this.constructor = d; }
7428     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7429 };
7430 var Observable_1 = require('../Observable');
7431 var subscribeToResult_1 = require('../util/subscribeToResult');
7432 var OuterSubscriber_1 = require('../OuterSubscriber');
7433 /**
7434  * We need this JSDoc comment for affecting ESDoc.
7435  * @extends {Ignored}
7436  * @hide true
7437  */
7438 var DeferObservable = (function (_super) {
7439     __extends(DeferObservable, _super);
7440     function DeferObservable(observableFactory) {
7441         _super.call(this);
7442         this.observableFactory = observableFactory;
7443     }
7444     /**
7445      * Creates an Observable that, on subscribe, calls an Observable factory to
7446      * make an Observable for each new Observer.
7447      *
7448      * <span class="informal">Creates the Observable lazily, that is, only when it
7449      * is subscribed.
7450      * </span>
7451      *
7452      * <img src="./img/defer.png" width="100%">
7453      *
7454      * `defer` allows you to create the Observable only when the Observer
7455      * subscribes, and create a fresh Observable for each Observer. It waits until
7456      * an Observer subscribes to it, and then it generates an Observable,
7457      * typically with an Observable factory function. It does this afresh for each
7458      * subscriber, so although each subscriber may think it is subscribing to the
7459      * same Observable, in fact each subscriber gets its own individual
7460      * Observable.
7461      *
7462      * @example <caption>Subscribe to either an Observable of clicks or an Observable of interval, at random</caption>
7463      * var clicksOrInterval = Rx.Observable.defer(function () {
7464      *   if (Math.random() > 0.5) {
7465      *     return Rx.Observable.fromEvent(document, 'click');
7466      *   } else {
7467      *     return Rx.Observable.interval(1000);
7468      *   }
7469      * });
7470      * clicksOrInterval.subscribe(x => console.log(x));
7471      *
7472      * // Results in the following behavior:
7473      * // If the result of Math.random() is greater than 0.5 it will listen
7474      * // for clicks anywhere on the "document"; when document is clicked it
7475      * // will log a MouseEvent object to the console. If the result is less
7476      * // than 0.5 it will emit ascending numbers, one every second(1000ms).
7477      *
7478      * @see {@link create}
7479      *
7480      * @param {function(): SubscribableOrPromise} observableFactory The Observable
7481      * factory function to invoke for each Observer that subscribes to the output
7482      * Observable. May also return a Promise, which will be converted on the fly
7483      * to an Observable.
7484      * @return {Observable} An Observable whose Observers' subscriptions trigger
7485      * an invocation of the given Observable factory function.
7486      * @static true
7487      * @name defer
7488      * @owner Observable
7489      */
7490     DeferObservable.create = function (observableFactory) {
7491         return new DeferObservable(observableFactory);
7492     };
7493     DeferObservable.prototype._subscribe = function (subscriber) {
7494         return new DeferSubscriber(subscriber, this.observableFactory);
7495     };
7496     return DeferObservable;
7497 }(Observable_1.Observable));
7498 exports.DeferObservable = DeferObservable;
7499 var DeferSubscriber = (function (_super) {
7500     __extends(DeferSubscriber, _super);
7501     function DeferSubscriber(destination, factory) {
7502         _super.call(this, destination);
7503         this.factory = factory;
7504         this.tryDefer();
7505     }
7506     DeferSubscriber.prototype.tryDefer = function () {
7507         try {
7508             this._callFactory();
7509         }
7510         catch (err) {
7511             this._error(err);
7512         }
7513     };
7514     DeferSubscriber.prototype._callFactory = function () {
7515         var result = this.factory();
7516         if (result) {
7517             this.add(subscribeToResult_1.subscribeToResult(this, result));
7518         }
7519     };
7520     return DeferSubscriber;
7521 }(OuterSubscriber_1.OuterSubscriber));
7522
7523 },{"../Observable":29,"../OuterSubscriber":31,"../util/subscribeToResult":238}],96:[function(require,module,exports){
7524 "use strict";
7525 var __extends = (this && this.__extends) || function (d, b) {
7526     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7527     function __() { this.constructor = d; }
7528     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7529 };
7530 var Observable_1 = require('../Observable');
7531 /**
7532  * We need this JSDoc comment for affecting ESDoc.
7533  * @extends {Ignored}
7534  * @hide true
7535  */
7536 var EmptyObservable = (function (_super) {
7537     __extends(EmptyObservable, _super);
7538     function EmptyObservable(scheduler) {
7539         _super.call(this);
7540         this.scheduler = scheduler;
7541     }
7542     /**
7543      * Creates an Observable that emits no items to the Observer and immediately
7544      * emits a complete notification.
7545      *
7546      * <span class="informal">Just emits 'complete', and nothing else.
7547      * </span>
7548      *
7549      * <img src="./img/empty.png" width="100%">
7550      *
7551      * This static operator is useful for creating a simple Observable that only
7552      * emits the complete notification. It can be used for composing with other
7553      * Observables, such as in a {@link mergeMap}.
7554      *
7555      * @example <caption>Emit the number 7, then complete.</caption>
7556      * var result = Rx.Observable.empty().startWith(7);
7557      * result.subscribe(x => console.log(x));
7558      *
7559      * @example <caption>Map and flatten only odd numbers to the sequence 'a', 'b', 'c'</caption>
7560      * var interval = Rx.Observable.interval(1000);
7561      * var result = interval.mergeMap(x =>
7562      *   x % 2 === 1 ? Rx.Observable.of('a', 'b', 'c') : Rx.Observable.empty()
7563      * );
7564      * result.subscribe(x => console.log(x));
7565      *
7566      * // Results in the following to the console:
7567      * // x is equal to the count on the interval eg(0,1,2,3,...)
7568      * // x will occur every 1000ms
7569      * // if x % 2 is equal to 1 print abc
7570      * // if x % 2 is not equal to 1 nothing will be output
7571      *
7572      * @see {@link create}
7573      * @see {@link never}
7574      * @see {@link of}
7575      * @see {@link throw}
7576      *
7577      * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
7578      * the emission of the complete notification.
7579      * @return {Observable} An "empty" Observable: emits only the complete
7580      * notification.
7581      * @static true
7582      * @name empty
7583      * @owner Observable
7584      */
7585     EmptyObservable.create = function (scheduler) {
7586         return new EmptyObservable(scheduler);
7587     };
7588     EmptyObservable.dispatch = function (arg) {
7589         var subscriber = arg.subscriber;
7590         subscriber.complete();
7591     };
7592     EmptyObservable.prototype._subscribe = function (subscriber) {
7593         var scheduler = this.scheduler;
7594         if (scheduler) {
7595             return scheduler.schedule(EmptyObservable.dispatch, 0, { subscriber: subscriber });
7596         }
7597         else {
7598             subscriber.complete();
7599         }
7600     };
7601     return EmptyObservable;
7602 }(Observable_1.Observable));
7603 exports.EmptyObservable = EmptyObservable;
7604
7605 },{"../Observable":29}],97:[function(require,module,exports){
7606 "use strict";
7607 var __extends = (this && this.__extends) || function (d, b) {
7608     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7609     function __() { this.constructor = d; }
7610     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7611 };
7612 var Observable_1 = require('../Observable');
7613 /**
7614  * We need this JSDoc comment for affecting ESDoc.
7615  * @extends {Ignored}
7616  * @hide true
7617  */
7618 var ErrorObservable = (function (_super) {
7619     __extends(ErrorObservable, _super);
7620     function ErrorObservable(error, scheduler) {
7621         _super.call(this);
7622         this.error = error;
7623         this.scheduler = scheduler;
7624     }
7625     /**
7626      * Creates an Observable that emits no items to the Observer and immediately
7627      * emits an error notification.
7628      *
7629      * <span class="informal">Just emits 'error', and nothing else.
7630      * </span>
7631      *
7632      * <img src="./img/throw.png" width="100%">
7633      *
7634      * This static operator is useful for creating a simple Observable that only
7635      * emits the error notification. It can be used for composing with other
7636      * Observables, such as in a {@link mergeMap}.
7637      *
7638      * @example <caption>Emit the number 7, then emit an error.</caption>
7639      * var result = Rx.Observable.throw(new Error('oops!')).startWith(7);
7640      * result.subscribe(x => console.log(x), e => console.error(e));
7641      *
7642      * @example <caption>Map and flatten numbers to the sequence 'a', 'b', 'c', but throw an error for 13</caption>
7643      * var interval = Rx.Observable.interval(1000);
7644      * var result = interval.mergeMap(x =>
7645      *   x === 13 ?
7646      *     Rx.Observable.throw('Thirteens are bad') :
7647      *     Rx.Observable.of('a', 'b', 'c')
7648      * );
7649      * result.subscribe(x => console.log(x), e => console.error(e));
7650      *
7651      * @see {@link create}
7652      * @see {@link empty}
7653      * @see {@link never}
7654      * @see {@link of}
7655      *
7656      * @param {any} error The particular Error to pass to the error notification.
7657      * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling
7658      * the emission of the error notification.
7659      * @return {Observable} An error Observable: emits only the error notification
7660      * using the given error argument.
7661      * @static true
7662      * @name throw
7663      * @owner Observable
7664      */
7665     ErrorObservable.create = function (error, scheduler) {
7666         return new ErrorObservable(error, scheduler);
7667     };
7668     ErrorObservable.dispatch = function (arg) {
7669         var error = arg.error, subscriber = arg.subscriber;
7670         subscriber.error(error);
7671     };
7672     ErrorObservable.prototype._subscribe = function (subscriber) {
7673         var error = this.error;
7674         var scheduler = this.scheduler;
7675         subscriber.syncErrorThrowable = true;
7676         if (scheduler) {
7677             return scheduler.schedule(ErrorObservable.dispatch, 0, {
7678                 error: error, subscriber: subscriber
7679             });
7680         }
7681         else {
7682             subscriber.error(error);
7683         }
7684     };
7685     return ErrorObservable;
7686 }(Observable_1.Observable));
7687 exports.ErrorObservable = ErrorObservable;
7688
7689 },{"../Observable":29}],98:[function(require,module,exports){
7690 "use strict";
7691 var __extends = (this && this.__extends) || function (d, b) {
7692     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7693     function __() { this.constructor = d; }
7694     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7695 };
7696 var Observable_1 = require('../Observable');
7697 var tryCatch_1 = require('../util/tryCatch');
7698 var isFunction_1 = require('../util/isFunction');
7699 var errorObject_1 = require('../util/errorObject');
7700 var Subscription_1 = require('../Subscription');
7701 var toString = Object.prototype.toString;
7702 function isNodeStyleEventEmitter(sourceObj) {
7703     return !!sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function';
7704 }
7705 function isJQueryStyleEventEmitter(sourceObj) {
7706     return !!sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function';
7707 }
7708 function isNodeList(sourceObj) {
7709     return !!sourceObj && toString.call(sourceObj) === '[object NodeList]';
7710 }
7711 function isHTMLCollection(sourceObj) {
7712     return !!sourceObj && toString.call(sourceObj) === '[object HTMLCollection]';
7713 }
7714 function isEventTarget(sourceObj) {
7715     return !!sourceObj && typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function';
7716 }
7717 /**
7718  * We need this JSDoc comment for affecting ESDoc.
7719  * @extends {Ignored}
7720  * @hide true
7721  */
7722 var FromEventObservable = (function (_super) {
7723     __extends(FromEventObservable, _super);
7724     function FromEventObservable(sourceObj, eventName, selector, options) {
7725         _super.call(this);
7726         this.sourceObj = sourceObj;
7727         this.eventName = eventName;
7728         this.selector = selector;
7729         this.options = options;
7730     }
7731     /* tslint:enable:max-line-length */
7732     /**
7733      * Creates an Observable that emits events of a specific type coming from the
7734      * given event target.
7735      *
7736      * <span class="informal">Creates an Observable from DOM events, or Node.js
7737      * EventEmitter events or others.</span>
7738      *
7739      * <img src="./img/fromEvent.png" width="100%">
7740      *
7741      * `fromEvent` accepts as a first argument event target, which is an object with methods
7742      * for registering event handler functions. As a second argument it takes string that indicates
7743      * type of event we want to listen for. `fromEvent` supports selected types of event targets,
7744      * which are described in detail below. If your event target does not match any of the ones listed,
7745      * you should use {@link fromEventPattern}, which can be used on arbitrary APIs.
7746      * When it comes to APIs supported by `fromEvent`, their methods for adding and removing event
7747      * handler functions have different names, but they all accept a string describing event type
7748      * and function itself, which will be called whenever said event happens.
7749      *
7750      * Every time resulting Observable is subscribed, event handler function will be registered
7751      * to event target on given event type. When that event fires, value
7752      * passed as a first argument to registered function will be emitted by output Observable.
7753      * When Observable is unsubscribed, function will be unregistered from event target.
7754      *
7755      * Note that if event target calls registered function with more than one argument, second
7756      * and following arguments will not appear in resulting stream. In order to get access to them,
7757      * you can pass to `fromEvent` optional project function, which will be called with all arguments
7758      * passed to event handler. Output Observable will then emit value returned by project function,
7759      * instead of the usual value.
7760      *
7761      * Remember that event targets listed below are checked via duck typing. It means that
7762      * no matter what kind of object you have and no matter what environment you work in,
7763      * you can safely use `fromEvent` on that object if it exposes described methods (provided
7764      * of course they behave as was described above). So for example if Node.js library exposes
7765      * event target which has the same method names as DOM EventTarget, `fromEvent` is still
7766      * a good choice.
7767      *
7768      * If the API you use is more callback then event handler oriented (subscribed
7769      * callback function fires only once and thus there is no need to manually
7770      * unregister it), you should use {@link bindCallback} or {@link bindNodeCallback}
7771      * instead.
7772      *
7773      * `fromEvent` supports following types of event targets:
7774      *
7775      * **DOM EventTarget**
7776      *
7777      * This is an object with `addEventListener` and `removeEventListener` methods.
7778      *
7779      * In the browser, `addEventListener` accepts - apart from event type string and event
7780      * handler function arguments - optional third parameter, which is either an object or boolean,
7781      * both used for additional configuration how and when passed function will be called. When
7782      * `fromEvent` is used with event target of that type, you can provide this values
7783      * as third parameter as well.
7784      *
7785      * **Node.js EventEmitter**
7786      *
7787      * An object with `addListener` and `removeListener` methods.
7788      *
7789      * **JQuery-style event target**
7790      *
7791      * An object with `on` and `off` methods
7792      *
7793      * **DOM NodeList**
7794      *
7795      * List of DOM Nodes, returned for example by `document.querySelectorAll` or `Node.childNodes`.
7796      *
7797      * Although this collection is not event target in itself, `fromEvent` will iterate over all Nodes
7798      * it contains and install event handler function in every of them. When returned Observable
7799      * is unsubscribed, function will be removed from all Nodes.
7800      *
7801      * **DOM HtmlCollection**
7802      *
7803      * Just as in case of NodeList it is a collection of DOM nodes. Here as well event handler function is
7804      * installed and removed in each of elements.
7805      *
7806      *
7807      * @example <caption>Emits clicks happening on the DOM document</caption>
7808      * var clicks = Rx.Observable.fromEvent(document, 'click');
7809      * clicks.subscribe(x => console.log(x));
7810      *
7811      * // Results in:
7812      * // MouseEvent object logged to console every time a click
7813      * // occurs on the document.
7814      *
7815      *
7816      * @example <caption>Use addEventListener with capture option</caption>
7817      * var clicksInDocument = Rx.Observable.fromEvent(document, 'click', true); // note optional configuration parameter
7818      *                                                                          // which will be passed to addEventListener
7819      * var clicksInDiv = Rx.Observable.fromEvent(someDivInDocument, 'click');
7820      *
7821      * clicksInDocument.subscribe(() => console.log('document'));
7822      * clicksInDiv.subscribe(() => console.log('div'));
7823      *
7824      * // By default events bubble UP in DOM tree, so normally
7825      * // when we would click on div in document
7826      * // "div" would be logged first and then "document".
7827      * // Since we specified optional `capture` option, document
7828      * // will catch event when it goes DOWN DOM tree, so console
7829      * // will log "document" and then "div".
7830      *
7831      * @see {@link bindCallback}
7832      * @see {@link bindNodeCallback}
7833      * @see {@link fromEventPattern}
7834      *
7835      * @param {EventTargetLike} target The DOM EventTarget, Node.js
7836      * EventEmitter, JQuery-like event target, NodeList or HTMLCollection to attach the event handler to.
7837      * @param {string} eventName The event name of interest, being emitted by the
7838      * `target`.
7839      * @param {EventListenerOptions} [options] Options to pass through to addEventListener
7840      * @param {SelectorMethodSignature<T>} [selector] An optional function to
7841      * post-process results. It takes the arguments from the event handler and
7842      * should return a single value.
7843      * @return {Observable<T>}
7844      * @static true
7845      * @name fromEvent
7846      * @owner Observable
7847      */
7848     FromEventObservable.create = function (target, eventName, options, selector) {
7849         if (isFunction_1.isFunction(options)) {
7850             selector = options;
7851             options = undefined;
7852         }
7853         return new FromEventObservable(target, eventName, selector, options);
7854     };
7855     FromEventObservable.setupSubscription = function (sourceObj, eventName, handler, subscriber, options) {
7856         var unsubscribe;
7857         if (isNodeList(sourceObj) || isHTMLCollection(sourceObj)) {
7858             for (var i = 0, len = sourceObj.length; i < len; i++) {
7859                 FromEventObservable.setupSubscription(sourceObj[i], eventName, handler, subscriber, options);
7860             }
7861         }
7862         else if (isEventTarget(sourceObj)) {
7863             var source_1 = sourceObj;
7864             sourceObj.addEventListener(eventName, handler, options);
7865             unsubscribe = function () { return source_1.removeEventListener(eventName, handler); };
7866         }
7867         else if (isJQueryStyleEventEmitter(sourceObj)) {
7868             var source_2 = sourceObj;
7869             sourceObj.on(eventName, handler);
7870             unsubscribe = function () { return source_2.off(eventName, handler); };
7871         }
7872         else if (isNodeStyleEventEmitter(sourceObj)) {
7873             var source_3 = sourceObj;
7874             sourceObj.addListener(eventName, handler);
7875             unsubscribe = function () { return source_3.removeListener(eventName, handler); };
7876         }
7877         else {
7878             throw new TypeError('Invalid event target');
7879         }
7880         subscriber.add(new Subscription_1.Subscription(unsubscribe));
7881     };
7882     FromEventObservable.prototype._subscribe = function (subscriber) {
7883         var sourceObj = this.sourceObj;
7884         var eventName = this.eventName;
7885         var options = this.options;
7886         var selector = this.selector;
7887         var handler = selector ? function () {
7888             var args = [];
7889             for (var _i = 0; _i < arguments.length; _i++) {
7890                 args[_i - 0] = arguments[_i];
7891             }
7892             var result = tryCatch_1.tryCatch(selector).apply(void 0, args);
7893             if (result === errorObject_1.errorObject) {
7894                 subscriber.error(errorObject_1.errorObject.e);
7895             }
7896             else {
7897                 subscriber.next(result);
7898             }
7899         } : function (e) { return subscriber.next(e); };
7900         FromEventObservable.setupSubscription(sourceObj, eventName, handler, subscriber, options);
7901     };
7902     return FromEventObservable;
7903 }(Observable_1.Observable));
7904 exports.FromEventObservable = FromEventObservable;
7905
7906 },{"../Observable":29,"../Subscription":37,"../util/errorObject":225,"../util/isFunction":230,"../util/tryCatch":240}],99:[function(require,module,exports){
7907 "use strict";
7908 var __extends = (this && this.__extends) || function (d, b) {
7909     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7910     function __() { this.constructor = d; }
7911     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7912 };
7913 var isArray_1 = require('../util/isArray');
7914 var isArrayLike_1 = require('../util/isArrayLike');
7915 var isPromise_1 = require('../util/isPromise');
7916 var PromiseObservable_1 = require('./PromiseObservable');
7917 var IteratorObservable_1 = require('./IteratorObservable');
7918 var ArrayObservable_1 = require('./ArrayObservable');
7919 var ArrayLikeObservable_1 = require('./ArrayLikeObservable');
7920 var iterator_1 = require('../symbol/iterator');
7921 var Observable_1 = require('../Observable');
7922 var observeOn_1 = require('../operators/observeOn');
7923 var observable_1 = require('../symbol/observable');
7924 /**
7925  * We need this JSDoc comment for affecting ESDoc.
7926  * @extends {Ignored}
7927  * @hide true
7928  */
7929 var FromObservable = (function (_super) {
7930     __extends(FromObservable, _super);
7931     function FromObservable(ish, scheduler) {
7932         _super.call(this, null);
7933         this.ish = ish;
7934         this.scheduler = scheduler;
7935     }
7936     /**
7937      * Creates an Observable from an Array, an array-like object, a Promise, an
7938      * iterable object, or an Observable-like object.
7939      *
7940      * <span class="informal">Converts almost anything to an Observable.</span>
7941      *
7942      * <img src="./img/from.png" width="100%">
7943      *
7944      * Convert various other objects and data types into Observables. `from`
7945      * converts a Promise or an array-like or an
7946      * [iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable)
7947      * object into an Observable that emits the items in that promise or array or
7948      * iterable. A String, in this context, is treated as an array of characters.
7949      * Observable-like objects (contains a function named with the ES2015 Symbol
7950      * for Observable) can also be converted through this operator.
7951      *
7952      * @example <caption>Converts an array to an Observable</caption>
7953      * var array = [10, 20, 30];
7954      * var result = Rx.Observable.from(array);
7955      * result.subscribe(x => console.log(x));
7956      *
7957      * // Results in the following:
7958      * // 10 20 30
7959      *
7960      * @example <caption>Convert an infinite iterable (from a generator) to an Observable</caption>
7961      * function* generateDoubles(seed) {
7962      *   var i = seed;
7963      *   while (true) {
7964      *     yield i;
7965      *     i = 2 * i; // double it
7966      *   }
7967      * }
7968      *
7969      * var iterator = generateDoubles(3);
7970      * var result = Rx.Observable.from(iterator).take(10);
7971      * result.subscribe(x => console.log(x));
7972      *
7973      * // Results in the following:
7974      * // 3 6 12 24 48 96 192 384 768 1536
7975      *
7976      * @see {@link create}
7977      * @see {@link fromEvent}
7978      * @see {@link fromEventPattern}
7979      * @see {@link fromPromise}
7980      *
7981      * @param {ObservableInput<T>} ish A subscribable object, a Promise, an
7982      * Observable-like, an Array, an iterable or an array-like object to be
7983      * converted.
7984      * @param {Scheduler} [scheduler] The scheduler on which to schedule the
7985      * emissions of values.
7986      * @return {Observable<T>} The Observable whose values are originally from the
7987      * input object that was converted.
7988      * @static true
7989      * @name from
7990      * @owner Observable
7991      */
7992     FromObservable.create = function (ish, scheduler) {
7993         if (ish != null) {
7994             if (typeof ish[observable_1.observable] === 'function') {
7995                 if (ish instanceof Observable_1.Observable && !scheduler) {
7996                     return ish;
7997                 }
7998                 return new FromObservable(ish, scheduler);
7999             }
8000             else if (isArray_1.isArray(ish)) {
8001                 return new ArrayObservable_1.ArrayObservable(ish, scheduler);
8002             }
8003             else if (isPromise_1.isPromise(ish)) {
8004                 return new PromiseObservable_1.PromiseObservable(ish, scheduler);
8005             }
8006             else if (typeof ish[iterator_1.iterator] === 'function' || typeof ish === 'string') {
8007                 return new IteratorObservable_1.IteratorObservable(ish, scheduler);
8008             }
8009             else if (isArrayLike_1.isArrayLike(ish)) {
8010                 return new ArrayLikeObservable_1.ArrayLikeObservable(ish, scheduler);
8011             }
8012         }
8013         throw new TypeError((ish !== null && typeof ish || ish) + ' is not observable');
8014     };
8015     FromObservable.prototype._subscribe = function (subscriber) {
8016         var ish = this.ish;
8017         var scheduler = this.scheduler;
8018         if (scheduler == null) {
8019             return ish[observable_1.observable]().subscribe(subscriber);
8020         }
8021         else {
8022             return ish[observable_1.observable]().subscribe(new observeOn_1.ObserveOnSubscriber(subscriber, scheduler, 0));
8023         }
8024     };
8025     return FromObservable;
8026 }(Observable_1.Observable));
8027 exports.FromObservable = FromObservable;
8028
8029 },{"../Observable":29,"../operators/observeOn":182,"../symbol/iterator":215,"../symbol/observable":216,"../util/isArray":227,"../util/isArrayLike":228,"../util/isPromise":233,"./ArrayLikeObservable":92,"./ArrayObservable":93,"./IteratorObservable":100,"./PromiseObservable":101}],100:[function(require,module,exports){
8030 "use strict";
8031 var __extends = (this && this.__extends) || function (d, b) {
8032     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8033     function __() { this.constructor = d; }
8034     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8035 };
8036 var root_1 = require('../util/root');
8037 var Observable_1 = require('../Observable');
8038 var iterator_1 = require('../symbol/iterator');
8039 /**
8040  * We need this JSDoc comment for affecting ESDoc.
8041  * @extends {Ignored}
8042  * @hide true
8043  */
8044 var IteratorObservable = (function (_super) {
8045     __extends(IteratorObservable, _super);
8046     function IteratorObservable(iterator, scheduler) {
8047         _super.call(this);
8048         this.scheduler = scheduler;
8049         if (iterator == null) {
8050             throw new Error('iterator cannot be null.');
8051         }
8052         this.iterator = getIterator(iterator);
8053     }
8054     IteratorObservable.create = function (iterator, scheduler) {
8055         return new IteratorObservable(iterator, scheduler);
8056     };
8057     IteratorObservable.dispatch = function (state) {
8058         var index = state.index, hasError = state.hasError, iterator = state.iterator, subscriber = state.subscriber;
8059         if (hasError) {
8060             subscriber.error(state.error);
8061             return;
8062         }
8063         var result = iterator.next();
8064         if (result.done) {
8065             subscriber.complete();
8066             return;
8067         }
8068         subscriber.next(result.value);
8069         state.index = index + 1;
8070         if (subscriber.closed) {
8071             if (typeof iterator.return === 'function') {
8072                 iterator.return();
8073             }
8074             return;
8075         }
8076         this.schedule(state);
8077     };
8078     IteratorObservable.prototype._subscribe = function (subscriber) {
8079         var index = 0;
8080         var _a = this, iterator = _a.iterator, scheduler = _a.scheduler;
8081         if (scheduler) {
8082             return scheduler.schedule(IteratorObservable.dispatch, 0, {
8083                 index: index, iterator: iterator, subscriber: subscriber
8084             });
8085         }
8086         else {
8087             do {
8088                 var result = iterator.next();
8089                 if (result.done) {
8090                     subscriber.complete();
8091                     break;
8092                 }
8093                 else {
8094                     subscriber.next(result.value);
8095                 }
8096                 if (subscriber.closed) {
8097                     if (typeof iterator.return === 'function') {
8098                         iterator.return();
8099                     }
8100                     break;
8101                 }
8102             } while (true);
8103         }
8104     };
8105     return IteratorObservable;
8106 }(Observable_1.Observable));
8107 exports.IteratorObservable = IteratorObservable;
8108 var StringIterator = (function () {
8109     function StringIterator(str, idx, len) {
8110         if (idx === void 0) { idx = 0; }
8111         if (len === void 0) { len = str.length; }
8112         this.str = str;
8113         this.idx = idx;
8114         this.len = len;
8115     }
8116     StringIterator.prototype[iterator_1.iterator] = function () { return (this); };
8117     StringIterator.prototype.next = function () {
8118         return this.idx < this.len ? {
8119             done: false,
8120             value: this.str.charAt(this.idx++)
8121         } : {
8122             done: true,
8123             value: undefined
8124         };
8125     };
8126     return StringIterator;
8127 }());
8128 var ArrayIterator = (function () {
8129     function ArrayIterator(arr, idx, len) {
8130         if (idx === void 0) { idx = 0; }
8131         if (len === void 0) { len = toLength(arr); }
8132         this.arr = arr;
8133         this.idx = idx;
8134         this.len = len;
8135     }
8136     ArrayIterator.prototype[iterator_1.iterator] = function () { return this; };
8137     ArrayIterator.prototype.next = function () {
8138         return this.idx < this.len ? {
8139             done: false,
8140             value: this.arr[this.idx++]
8141         } : {
8142             done: true,
8143             value: undefined
8144         };
8145     };
8146     return ArrayIterator;
8147 }());
8148 function getIterator(obj) {
8149     var i = obj[iterator_1.iterator];
8150     if (!i && typeof obj === 'string') {
8151         return new StringIterator(obj);
8152     }
8153     if (!i && obj.length !== undefined) {
8154         return new ArrayIterator(obj);
8155     }
8156     if (!i) {
8157         throw new TypeError('object is not iterable');
8158     }
8159     return obj[iterator_1.iterator]();
8160 }
8161 var maxSafeInteger = Math.pow(2, 53) - 1;
8162 function toLength(o) {
8163     var len = +o.length;
8164     if (isNaN(len)) {
8165         return 0;
8166     }
8167     if (len === 0 || !numberIsFinite(len)) {
8168         return len;
8169     }
8170     len = sign(len) * Math.floor(Math.abs(len));
8171     if (len <= 0) {
8172         return 0;
8173     }
8174     if (len > maxSafeInteger) {
8175         return maxSafeInteger;
8176     }
8177     return len;
8178 }
8179 function numberIsFinite(value) {
8180     return typeof value === 'number' && root_1.root.isFinite(value);
8181 }
8182 function sign(value) {
8183     var valueAsNumber = +value;
8184     if (valueAsNumber === 0) {
8185         return valueAsNumber;
8186     }
8187     if (isNaN(valueAsNumber)) {
8188         return valueAsNumber;
8189     }
8190     return valueAsNumber < 0 ? -1 : 1;
8191 }
8192
8193 },{"../Observable":29,"../symbol/iterator":215,"../util/root":237}],101:[function(require,module,exports){
8194 "use strict";
8195 var __extends = (this && this.__extends) || function (d, b) {
8196     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8197     function __() { this.constructor = d; }
8198     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8199 };
8200 var root_1 = require('../util/root');
8201 var Observable_1 = require('../Observable');
8202 /**
8203  * We need this JSDoc comment for affecting ESDoc.
8204  * @extends {Ignored}
8205  * @hide true
8206  */
8207 var PromiseObservable = (function (_super) {
8208     __extends(PromiseObservable, _super);
8209     function PromiseObservable(promise, scheduler) {
8210         _super.call(this);
8211         this.promise = promise;
8212         this.scheduler = scheduler;
8213     }
8214     /**
8215      * Converts a Promise to an Observable.
8216      *
8217      * <span class="informal">Returns an Observable that just emits the Promise's
8218      * resolved value, then completes.</span>
8219      *
8220      * Converts an ES2015 Promise or a Promises/A+ spec compliant Promise to an
8221      * Observable. If the Promise resolves with a value, the output Observable
8222      * emits that resolved value as a `next`, and then completes. If the Promise
8223      * is rejected, then the output Observable emits the corresponding Error.
8224      *
8225      * @example <caption>Convert the Promise returned by Fetch to an Observable</caption>
8226      * var result = Rx.Observable.fromPromise(fetch('http://myserver.com/'));
8227      * result.subscribe(x => console.log(x), e => console.error(e));
8228      *
8229      * @see {@link bindCallback}
8230      * @see {@link from}
8231      *
8232      * @param {PromiseLike<T>} promise The promise to be converted.
8233      * @param {Scheduler} [scheduler] An optional IScheduler to use for scheduling
8234      * the delivery of the resolved value (or the rejection).
8235      * @return {Observable<T>} An Observable which wraps the Promise.
8236      * @static true
8237      * @name fromPromise
8238      * @owner Observable
8239      */
8240     PromiseObservable.create = function (promise, scheduler) {
8241         return new PromiseObservable(promise, scheduler);
8242     };
8243     PromiseObservable.prototype._subscribe = function (subscriber) {
8244         var _this = this;
8245         var promise = this.promise;
8246         var scheduler = this.scheduler;
8247         if (scheduler == null) {
8248             if (this._isScalar) {
8249                 if (!subscriber.closed) {
8250                     subscriber.next(this.value);
8251                     subscriber.complete();
8252                 }
8253             }
8254             else {
8255                 promise.then(function (value) {
8256                     _this.value = value;
8257                     _this._isScalar = true;
8258                     if (!subscriber.closed) {
8259                         subscriber.next(value);
8260                         subscriber.complete();
8261                     }
8262                 }, function (err) {
8263                     if (!subscriber.closed) {
8264                         subscriber.error(err);
8265                     }
8266                 })
8267                     .then(null, function (err) {
8268                     // escape the promise trap, throw unhandled errors
8269                     root_1.root.setTimeout(function () { throw err; });
8270                 });
8271             }
8272         }
8273         else {
8274             if (this._isScalar) {
8275                 if (!subscriber.closed) {
8276                     return scheduler.schedule(dispatchNext, 0, { value: this.value, subscriber: subscriber });
8277                 }
8278             }
8279             else {
8280                 promise.then(function (value) {
8281                     _this.value = value;
8282                     _this._isScalar = true;
8283                     if (!subscriber.closed) {
8284                         subscriber.add(scheduler.schedule(dispatchNext, 0, { value: value, subscriber: subscriber }));
8285                     }
8286                 }, function (err) {
8287                     if (!subscriber.closed) {
8288                         subscriber.add(scheduler.schedule(dispatchError, 0, { err: err, subscriber: subscriber }));
8289                     }
8290                 })
8291                     .then(null, function (err) {
8292                     // escape the promise trap, throw unhandled errors
8293                     root_1.root.setTimeout(function () { throw err; });
8294                 });
8295             }
8296         }
8297     };
8298     return PromiseObservable;
8299 }(Observable_1.Observable));
8300 exports.PromiseObservable = PromiseObservable;
8301 function dispatchNext(arg) {
8302     var value = arg.value, subscriber = arg.subscriber;
8303     if (!subscriber.closed) {
8304         subscriber.next(value);
8305         subscriber.complete();
8306     }
8307 }
8308 function dispatchError(arg) {
8309     var err = arg.err, subscriber = arg.subscriber;
8310     if (!subscriber.closed) {
8311         subscriber.error(err);
8312     }
8313 }
8314
8315 },{"../Observable":29,"../util/root":237}],102:[function(require,module,exports){
8316 "use strict";
8317 var __extends = (this && this.__extends) || function (d, b) {
8318     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8319     function __() { this.constructor = d; }
8320     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8321 };
8322 var Observable_1 = require('../Observable');
8323 /**
8324  * We need this JSDoc comment for affecting ESDoc.
8325  * @extends {Ignored}
8326  * @hide true
8327  */
8328 var ScalarObservable = (function (_super) {
8329     __extends(ScalarObservable, _super);
8330     function ScalarObservable(value, scheduler) {
8331         _super.call(this);
8332         this.value = value;
8333         this.scheduler = scheduler;
8334         this._isScalar = true;
8335         if (scheduler) {
8336             this._isScalar = false;
8337         }
8338     }
8339     ScalarObservable.create = function (value, scheduler) {
8340         return new ScalarObservable(value, scheduler);
8341     };
8342     ScalarObservable.dispatch = function (state) {
8343         var done = state.done, value = state.value, subscriber = state.subscriber;
8344         if (done) {
8345             subscriber.complete();
8346             return;
8347         }
8348         subscriber.next(value);
8349         if (subscriber.closed) {
8350             return;
8351         }
8352         state.done = true;
8353         this.schedule(state);
8354     };
8355     ScalarObservable.prototype._subscribe = function (subscriber) {
8356         var value = this.value;
8357         var scheduler = this.scheduler;
8358         if (scheduler) {
8359             return scheduler.schedule(ScalarObservable.dispatch, 0, {
8360                 done: false, value: value, subscriber: subscriber
8361             });
8362         }
8363         else {
8364             subscriber.next(value);
8365             if (!subscriber.closed) {
8366                 subscriber.complete();
8367             }
8368         }
8369     };
8370     return ScalarObservable;
8371 }(Observable_1.Observable));
8372 exports.ScalarObservable = ScalarObservable;
8373
8374 },{"../Observable":29}],103:[function(require,module,exports){
8375 "use strict";
8376 var __extends = (this && this.__extends) || function (d, b) {
8377     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
8378     function __() { this.constructor = d; }
8379     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
8380 };
8381 var isNumeric_1 = require('../util/isNumeric');
8382 var Observable_1 = require('../Observable');
8383 var async_1 = require('../scheduler/async');
8384 var isScheduler_1 = require('../util/isScheduler');
8385 var isDate_1 = require('../util/isDate');
8386 /**
8387  * We need this JSDoc comment for affecting ESDoc.
8388  * @extends {Ignored}
8389  * @hide true
8390  */
8391 var TimerObservable = (function (_super) {
8392     __extends(TimerObservable, _super);
8393     function TimerObservable(dueTime, period, scheduler) {
8394         if (dueTime === void 0) { dueTime = 0; }
8395         _super.call(this);
8396         this.period = -1;
8397         this.dueTime = 0;
8398         if (isNumeric_1.isNumeric(period)) {
8399             this.period = Number(period) < 1 && 1 || Number(period);
8400         }
8401         else if (isScheduler_1.isScheduler(period)) {
8402             scheduler = period;
8403         }
8404         if (!isScheduler_1.isScheduler(scheduler)) {
8405             scheduler = async_1.async;
8406         }
8407         this.scheduler = scheduler;
8408         this.dueTime = isDate_1.isDate(dueTime) ?
8409             (+dueTime - this.scheduler.now()) :
8410             dueTime;
8411     }
8412     /**
8413      * Creates an Observable that starts emitting after an `initialDelay` and
8414      * emits ever increasing numbers after each `period` of time thereafter.
8415      *
8416      * <span class="informal">Its like {@link interval}, but you can specify when
8417      * should the emissions start.</span>
8418      *
8419      * <img src="./img/timer.png" width="100%">
8420      *
8421      * `timer` returns an Observable that emits an infinite sequence of ascending
8422      * integers, with a constant interval of time, `period` of your choosing
8423      * between those emissions. The first emission happens after the specified
8424      * `initialDelay`. The initial delay may be a {@link Date}. By default, this
8425      * operator uses the `async` IScheduler to provide a notion of time, but you
8426      * may pass any IScheduler to it. If `period` is not specified, the output
8427      * Observable emits only one value, `0`. Otherwise, it emits an infinite
8428      * sequence.
8429      *
8430      * @example <caption>Emits ascending numbers, one every second (1000ms), starting after 3 seconds</caption>
8431      * var numbers = Rx.Observable.timer(3000, 1000);
8432      * numbers.subscribe(x => console.log(x));
8433      *
8434      * @example <caption>Emits one number after five seconds</caption>
8435      * var numbers = Rx.Observable.timer(5000);
8436      * numbers.subscribe(x => console.log(x));
8437      *
8438      * @see {@link interval}
8439      * @see {@link delay}
8440      *
8441      * @param {number|Date} initialDelay The initial delay time to wait before
8442      * emitting the first value of `0`.
8443      * @param {number} [period] The period of time between emissions of the
8444      * subsequent numbers.
8445      * @param {Scheduler} [scheduler=async] The IScheduler to use for scheduling
8446      * the emission of values, and providing a notion of "time".
8447      * @return {Observable} An Observable that emits a `0` after the
8448      * `initialDelay` and ever increasing numbers after each `period` of time
8449      * thereafter.
8450      * @static true
8451      * @name timer
8452      * @owner Observable
8453      */
8454     TimerObservable.create = function (initialDelay, period, scheduler) {
8455         if (initialDelay === void 0) { initialDelay = 0; }
8456         return new TimerObservable(initialDelay, period, scheduler);
8457     };
8458     TimerObservable.dispatch = function (state) {
8459         var index = state.index, period = state.period, subscriber = state.subscriber;
8460         var action = this;
8461         subscriber.next(index);
8462         if (subscriber.closed) {
8463             return;
8464         }
8465         else if (period === -1) {
8466             return subscriber.complete();
8467         }
8468         state.index = index + 1;
8469         action.schedule(state, period);
8470     };
8471     TimerObservable.prototype._subscribe = function (subscriber) {
8472         var index = 0;
8473         var _a = this, period = _a.period, dueTime = _a.dueTime, scheduler = _a.scheduler;
8474         return scheduler.schedule(TimerObservable.dispatch, dueTime, {
8475             index: index, period: period, subscriber: subscriber
8476         });
8477     };
8478     return TimerObservable;
8479 }(Observable_1.Observable));
8480 exports.TimerObservable = TimerObservable;
8481
8482 },{"../Observable":29,"../scheduler/async":213,"../util/isDate":229,"../util/isNumeric":231,"../util/isScheduler":234}],104:[function(require,module,exports){
8483 "use strict";
8484 var isScheduler_1 = require('../util/isScheduler');
8485 var isArray_1 = require('../util/isArray');
8486 var ArrayObservable_1 = require('./ArrayObservable');
8487 var combineLatest_1 = require('../operators/combineLatest');
8488 /* tslint:enable:max-line-length */
8489 /**
8490  * Combines multiple Observables to create an Observable whose values are
8491  * calculated from the latest values of each of its input Observables.
8492  *
8493  * <span class="informal">Whenever any input Observable emits a value, it
8494  * computes a formula using the latest values from all the inputs, then emits
8495  * the output of that formula.</span>
8496  *
8497  * <img src="./img/combineLatest.png" width="100%">
8498  *
8499  * `combineLatest` combines the values from all the Observables passed as
8500  * arguments. This is done by subscribing to each Observable in order and,
8501  * whenever any Observable emits, collecting an array of the most recent
8502  * values from each Observable. So if you pass `n` Observables to operator,
8503  * returned Observable will always emit an array of `n` values, in order
8504  * corresponding to order of passed Observables (value from the first Observable
8505  * on the first place and so on).
8506  *
8507  * Static version of `combineLatest` accepts either an array of Observables
8508  * or each Observable can be put directly as an argument. Note that array of
8509  * Observables is good choice, if you don't know beforehand how many Observables
8510  * you will combine. Passing empty array will result in Observable that
8511  * completes immediately.
8512  *
8513  * To ensure output array has always the same length, `combineLatest` will
8514  * actually wait for all input Observables to emit at least once,
8515  * before it starts emitting results. This means if some Observable emits
8516  * values before other Observables started emitting, all that values but last
8517  * will be lost. On the other hand, is some Observable does not emit value but
8518  * completes, resulting Observable will complete at the same moment without
8519  * emitting anything, since it will be now impossible to include value from
8520  * completed Observable in resulting array. Also, if some input Observable does
8521  * not emit any value and never completes, `combineLatest` will also never emit
8522  * and never complete, since, again, it will wait for all streams to emit some
8523  * value.
8524  *
8525  * If at least one Observable was passed to `combineLatest` and all passed Observables
8526  * emitted something, resulting Observable will complete when all combined
8527  * streams complete. So even if some Observable completes, result of
8528  * `combineLatest` will still emit values when other Observables do. In case
8529  * of completed Observable, its value from now on will always be the last
8530  * emitted value. On the other hand, if any Observable errors, `combineLatest`
8531  * will error immediately as well, and all other Observables will be unsubscribed.
8532  *
8533  * `combineLatest` accepts as optional parameter `project` function, which takes
8534  * as arguments all values that would normally be emitted by resulting Observable.
8535  * `project` can return any kind of value, which will be then emitted by Observable
8536  * instead of default array. Note that `project` does not take as argument that array
8537  * of values, but values themselves. That means default `project` can be imagined
8538  * as function that takes all its arguments and puts them into an array.
8539  *
8540  *
8541  * @example <caption>Combine two timer Observables</caption>
8542  * const firstTimer = Rx.Observable.timer(0, 1000); // emit 0, 1, 2... after every second, starting from now
8543  * const secondTimer = Rx.Observable.timer(500, 1000); // emit 0, 1, 2... after every second, starting 0,5s from now
8544  * const combinedTimers = Rx.Observable.combineLatest(firstTimer, secondTimer);
8545  * combinedTimers.subscribe(value => console.log(value));
8546  * // Logs
8547  * // [0, 0] after 0.5s
8548  * // [1, 0] after 1s
8549  * // [1, 1] after 1.5s
8550  * // [2, 1] after 2s
8551  *
8552  *
8553  * @example <caption>Combine an array of Observables</caption>
8554  * const observables = [1, 5, 10].map(
8555  *   n => Rx.Observable.of(n).delay(n * 1000).startWith(0) // emit 0 and then emit n after n seconds
8556  * );
8557  * const combined = Rx.Observable.combineLatest(observables);
8558  * combined.subscribe(value => console.log(value));
8559  * // Logs
8560  * // [0, 0, 0] immediately
8561  * // [1, 0, 0] after 1s
8562  * // [1, 5, 0] after 5s
8563  * // [1, 5, 10] after 10s
8564  *
8565  *
8566  * @example <caption>Use project function to dynamically calculate the Body-Mass Index</caption>
8567  * var weight = Rx.Observable.of(70, 72, 76, 79, 75);
8568  * var height = Rx.Observable.of(1.76, 1.77, 1.78);
8569  * var bmi = Rx.Observable.combineLatest(weight, height, (w, h) => w / (h * h));
8570  * bmi.subscribe(x => console.log('BMI is ' + x));
8571  *
8572  * // With output to console:
8573  * // BMI is 24.212293388429753
8574  * // BMI is 23.93948099205209
8575  * // BMI is 23.671253629592222
8576  *
8577  *
8578  * @see {@link combineAll}
8579  * @see {@link merge}
8580  * @see {@link withLatestFrom}
8581  *
8582  * @param {ObservableInput} observable1 An input Observable to combine with other Observables.
8583  * @param {ObservableInput} observable2 An input Observable to combine with other Observables.
8584  * More than one input Observables may be given as arguments
8585  * or an array of Observables may be given as the first argument.
8586  * @param {function} [project] An optional function to project the values from
8587  * the combined latest values into a new value on the output Observable.
8588  * @param {Scheduler} [scheduler=null] The IScheduler to use for subscribing to
8589  * each input Observable.
8590  * @return {Observable} An Observable of projected values from the most recent
8591  * values from each input Observable, or an array of the most recent values from
8592  * each input Observable.
8593  * @static true
8594  * @name combineLatest
8595  * @owner Observable
8596  */
8597 function combineLatest() {
8598     var observables = [];
8599     for (var _i = 0; _i < arguments.length; _i++) {
8600         observables[_i - 0] = arguments[_i];
8601     }
8602     var project = null;
8603     var scheduler = null;
8604     if (isScheduler_1.isScheduler(observables[observables.length - 1])) {
8605         scheduler = observables.pop();
8606     }
8607     if (typeof observables[observables.length - 1] === 'function') {
8608         project = observables.pop();
8609     }
8610     // if the first and only other argument besides the resultSelector is an array
8611     // assume it's been called with `combineLatest([obs1, obs2, obs3], project)`
8612     if (observables.length === 1 && isArray_1.isArray(observables[0])) {
8613         observables = observables[0];
8614     }
8615     return new ArrayObservable_1.ArrayObservable(observables, scheduler).lift(new combineLatest_1.CombineLatestOperator(project));
8616 }
8617 exports.combineLatest = combineLatest;
8618
8619 },{"../operators/combineLatest":164,"../util/isArray":227,"../util/isScheduler":234,"./ArrayObservable":93}],105:[function(require,module,exports){
8620 "use strict";
8621 var isScheduler_1 = require('../util/isScheduler');
8622 var of_1 = require('./of');
8623 var from_1 = require('./from');
8624 var concatAll_1 = require('../operators/concatAll');
8625 /* tslint:enable:max-line-length */
8626 /**
8627  * Creates an output Observable which sequentially emits all values from given
8628  * Observable and then moves on to the next.
8629  *
8630  * <span class="informal">Concatenates multiple Observables together by
8631  * sequentially emitting their values, one Observable after the other.</span>
8632  *
8633  * <img src="./img/concat.png" width="100%">
8634  *
8635  * `concat` joins multiple Observables together, by subscribing to them one at a time and
8636  * merging their results into the output Observable. You can pass either an array of
8637  * Observables, or put them directly as arguments. Passing an empty array will result
8638  * in Observable that completes immediately.
8639  *
8640  * `concat` will subscribe to first input Observable and emit all its values, without
8641  * changing or affecting them in any way. When that Observable completes, it will
8642  * subscribe to then next Observable passed and, again, emit its values. This will be
8643  * repeated, until the operator runs out of Observables. When last input Observable completes,
8644  * `concat` will complete as well. At any given moment only one Observable passed to operator
8645  * emits values. If you would like to emit values from passed Observables concurrently, check out
8646  * {@link merge} instead, especially with optional `concurrent` parameter. As a matter of fact,
8647  * `concat` is an equivalent of `merge` operator with `concurrent` parameter set to `1`.
8648  *
8649  * Note that if some input Observable never completes, `concat` will also never complete
8650  * and Observables following the one that did not complete will never be subscribed. On the other
8651  * hand, if some Observable simply completes immediately after it is subscribed, it will be
8652  * invisible for `concat`, which will just move on to the next Observable.
8653  *
8654  * If any Observable in chain errors, instead of passing control to the next Observable,
8655  * `concat` will error immediately as well. Observables that would be subscribed after
8656  * the one that emitted error, never will.
8657  *
8658  * If you pass to `concat` the same Observable many times, its stream of values
8659  * will be "replayed" on every subscription, which means you can repeat given Observable
8660  * as many times as you like. If passing the same Observable to `concat` 1000 times becomes tedious,
8661  * you can always use {@link repeat}.
8662  *
8663  * @example <caption>Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10</caption>
8664  * var timer = Rx.Observable.interval(1000).take(4);
8665  * var sequence = Rx.Observable.range(1, 10);
8666  * var result = Rx.Observable.concat(timer, sequence);
8667  * result.subscribe(x => console.log(x));
8668  *
8669  * // results in:
8670  * // 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10
8671  *
8672  *
8673  * @example <caption>Concatenate an array of 3 Observables</caption>
8674  * var timer1 = Rx.Observable.interval(1000).take(10);
8675  * var timer2 = Rx.Observable.interval(2000).take(6);
8676  * var timer3 = Rx.Observable.interval(500).take(10);
8677  * var result = Rx.Observable.concat([timer1, timer2, timer3]); // note that array is passed
8678  * result.subscribe(x => console.log(x));
8679  *
8680  * // results in the following:
8681  * // (Prints to console sequentially)
8682  * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9
8683  * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5
8684  * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9
8685  *
8686  *
8687  * @example <caption>Concatenate the same Observable to repeat it</caption>
8688  * const timer = Rx.Observable.interval(1000).take(2);
8689  *
8690  * Rx.Observable.concat(timer, timer) // concating the same Observable!
8691  * .subscribe(
8692  *   value => console.log(value),
8693  *   err => {},
8694  *   () => console.log('...and it is done!')
8695  * );
8696  *
8697  * // Logs:
8698  * // 0 after 1s
8699  * // 1 after 2s
8700  * // 0 after 3s
8701  * // 1 after 4s
8702  * // "...and it is done!" also after 4s
8703  *
8704  * @see {@link concatAll}
8705  * @see {@link concatMap}
8706  * @see {@link concatMapTo}
8707  *
8708  * @param {ObservableInput} input1 An input Observable to concatenate with others.
8709  * @param {ObservableInput} input2 An input Observable to concatenate with others.
8710  * More than one input Observables may be given as argument.
8711  * @param {Scheduler} [scheduler=null] An optional IScheduler to schedule each
8712  * Observable subscription on.
8713  * @return {Observable} All values of each passed Observable merged into a
8714  * single Observable, in order, in serial fashion.
8715  * @static true
8716  * @name concat
8717  * @owner Observable
8718  */
8719 function concat() {
8720     var observables = [];
8721     for (var _i = 0; _i < arguments.length; _i++) {
8722         observables[_i - 0] = arguments[_i];
8723     }
8724     if (observables.length === 1 || (observables.length === 2 && isScheduler_1.isScheduler(observables[1]))) {
8725         return from_1.from(observables[0]);
8726     }
8727     return concatAll_1.concatAll()(of_1.of.apply(void 0, observables));
8728 }
8729 exports.concat = concat;
8730
8731 },{"../operators/concatAll":166,"../util/isScheduler":234,"./from":108,"./of":112}],106:[function(require,module,exports){
8732 "use strict";
8733 var DeferObservable_1 = require('./DeferObservable');
8734 exports.defer = DeferObservable_1.DeferObservable.create;
8735
8736 },{"./DeferObservable":95}],107:[function(require,module,exports){
8737 "use strict";
8738 var EmptyObservable_1 = require('./EmptyObservable');
8739 exports.empty = EmptyObservable_1.EmptyObservable.create;
8740
8741 },{"./EmptyObservable":96}],108:[function(require,module,exports){
8742 "use strict";
8743 var FromObservable_1 = require('./FromObservable');
8744 exports.from = FromObservable_1.FromObservable.create;
8745
8746 },{"./FromObservable":99}],109:[function(require,module,exports){
8747 "use strict";
8748 var FromEventObservable_1 = require('./FromEventObservable');
8749 exports.fromEvent = FromEventObservable_1.FromEventObservable.create;
8750
8751 },{"./FromEventObservable":98}],110:[function(require,module,exports){
8752 "use strict";
8753 var PromiseObservable_1 = require('./PromiseObservable');
8754 exports.fromPromise = PromiseObservable_1.PromiseObservable.create;
8755
8756 },{"./PromiseObservable":101}],111:[function(require,module,exports){
8757 "use strict";
8758 var merge_1 = require('../operator/merge');
8759 exports.merge = merge_1.mergeStatic;
8760
8761 },{"../operator/merge":134}],112:[function(require,module,exports){
8762 "use strict";
8763 var ArrayObservable_1 = require('./ArrayObservable');
8764 exports.of = ArrayObservable_1.ArrayObservable.of;
8765
8766 },{"./ArrayObservable":93}],113:[function(require,module,exports){
8767 "use strict";
8768 var ErrorObservable_1 = require('./ErrorObservable');
8769 exports._throw = ErrorObservable_1.ErrorObservable.create;
8770
8771 },{"./ErrorObservable":97}],114:[function(require,module,exports){
8772 "use strict";
8773 var TimerObservable_1 = require('./TimerObservable');
8774 exports.timer = TimerObservable_1.TimerObservable.create;
8775
8776 },{"./TimerObservable":103}],115:[function(require,module,exports){
8777 "use strict";
8778 var zip_1 = require('../operators/zip');
8779 exports.zip = zip_1.zipStatic;
8780
8781 },{"../operators/zip":207}],116:[function(require,module,exports){
8782 "use strict";
8783 var async_1 = require('../scheduler/async');
8784 var auditTime_1 = require('../operators/auditTime');
8785 /**
8786  * Ignores source values for `duration` milliseconds, then emits the most recent
8787  * value from the source Observable, then repeats this process.
8788  *
8789  * <span class="informal">When it sees a source values, it ignores that plus
8790  * the next ones for `duration` milliseconds, and then it emits the most recent
8791  * value from the source.</span>
8792  *
8793  * <img src="./img/auditTime.png" width="100%">
8794  *
8795  * `auditTime` is similar to `throttleTime`, but emits the last value from the
8796  * silenced time window, instead of the first value. `auditTime` emits the most
8797  * recent value from the source Observable on the output Observable as soon as
8798  * its internal timer becomes disabled, and ignores source values while the
8799  * timer is enabled. Initially, the timer is disabled. As soon as the first
8800  * source value arrives, the timer is enabled. After `duration` milliseconds (or
8801  * the time unit determined internally by the optional `scheduler`) has passed,
8802  * the timer is disabled, then the most recent source value is emitted on the
8803  * output Observable, and this process repeats for the next source value.
8804  * Optionally takes a {@link IScheduler} for managing timers.
8805  *
8806  * @example <caption>Emit clicks at a rate of at most one click per second</caption>
8807  * var clicks = Rx.Observable.fromEvent(document, 'click');
8808  * var result = clicks.auditTime(1000);
8809  * result.subscribe(x => console.log(x));
8810  *
8811  * @see {@link audit}
8812  * @see {@link debounceTime}
8813  * @see {@link delay}
8814  * @see {@link sampleTime}
8815  * @see {@link throttleTime}
8816  *
8817  * @param {number} duration Time to wait before emitting the most recent source
8818  * value, measured in milliseconds or the time unit determined internally
8819  * by the optional `scheduler`.
8820  * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
8821  * managing the timers that handle the rate-limiting behavior.
8822  * @return {Observable<T>} An Observable that performs rate-limiting of
8823  * emissions from the source Observable.
8824  * @method auditTime
8825  * @owner Observable
8826  */
8827 function auditTime(duration, scheduler) {
8828     if (scheduler === void 0) { scheduler = async_1.async; }
8829     return auditTime_1.auditTime(duration, scheduler)(this);
8830 }
8831 exports.auditTime = auditTime;
8832
8833 },{"../operators/auditTime":159,"../scheduler/async":213}],117:[function(require,module,exports){
8834 "use strict";
8835 var buffer_1 = require('../operators/buffer');
8836 /**
8837  * Buffers the source Observable values until `closingNotifier` emits.
8838  *
8839  * <span class="informal">Collects values from the past as an array, and emits
8840  * that array only when another Observable emits.</span>
8841  *
8842  * <img src="./img/buffer.png" width="100%">
8843  *
8844  * Buffers the incoming Observable values until the given `closingNotifier`
8845  * Observable emits a value, at which point it emits the buffer on the output
8846  * Observable and starts a new buffer internally, awaiting the next time
8847  * `closingNotifier` emits.
8848  *
8849  * @example <caption>On every click, emit array of most recent interval events</caption>
8850  * var clicks = Rx.Observable.fromEvent(document, 'click');
8851  * var interval = Rx.Observable.interval(1000);
8852  * var buffered = interval.buffer(clicks);
8853  * buffered.subscribe(x => console.log(x));
8854  *
8855  * @see {@link bufferCount}
8856  * @see {@link bufferTime}
8857  * @see {@link bufferToggle}
8858  * @see {@link bufferWhen}
8859  * @see {@link window}
8860  *
8861  * @param {Observable<any>} closingNotifier An Observable that signals the
8862  * buffer to be emitted on the output Observable.
8863  * @return {Observable<T[]>} An Observable of buffers, which are arrays of
8864  * values.
8865  * @method buffer
8866  * @owner Observable
8867  */
8868 function buffer(closingNotifier) {
8869     return buffer_1.buffer(closingNotifier)(this);
8870 }
8871 exports.buffer = buffer;
8872
8873 },{"../operators/buffer":160}],118:[function(require,module,exports){
8874 "use strict";
8875 var bufferCount_1 = require('../operators/bufferCount');
8876 /**
8877  * Buffers the source Observable values until the size hits the maximum
8878  * `bufferSize` given.
8879  *
8880  * <span class="informal">Collects values from the past as an array, and emits
8881  * that array only when its size reaches `bufferSize`.</span>
8882  *
8883  * <img src="./img/bufferCount.png" width="100%">
8884  *
8885  * Buffers a number of values from the source Observable by `bufferSize` then
8886  * emits the buffer and clears it, and starts a new buffer each
8887  * `startBufferEvery` values. If `startBufferEvery` is not provided or is
8888  * `null`, then new buffers are started immediately at the start of the source
8889  * and when each buffer closes and is emitted.
8890  *
8891  * @example <caption>Emit the last two click events as an array</caption>
8892  * var clicks = Rx.Observable.fromEvent(document, 'click');
8893  * var buffered = clicks.bufferCount(2);
8894  * buffered.subscribe(x => console.log(x));
8895  *
8896  * @example <caption>On every click, emit the last two click events as an array</caption>
8897  * var clicks = Rx.Observable.fromEvent(document, 'click');
8898  * var buffered = clicks.bufferCount(2, 1);
8899  * buffered.subscribe(x => console.log(x));
8900  *
8901  * @see {@link buffer}
8902  * @see {@link bufferTime}
8903  * @see {@link bufferToggle}
8904  * @see {@link bufferWhen}
8905  * @see {@link pairwise}
8906  * @see {@link windowCount}
8907  *
8908  * @param {number} bufferSize The maximum size of the buffer emitted.
8909  * @param {number} [startBufferEvery] Interval at which to start a new buffer.
8910  * For example if `startBufferEvery` is `2`, then a new buffer will be started
8911  * on every other value from the source. A new buffer is started at the
8912  * beginning of the source by default.
8913  * @return {Observable<T[]>} An Observable of arrays of buffered values.
8914  * @method bufferCount
8915  * @owner Observable
8916  */
8917 function bufferCount(bufferSize, startBufferEvery) {
8918     if (startBufferEvery === void 0) { startBufferEvery = null; }
8919     return bufferCount_1.bufferCount(bufferSize, startBufferEvery)(this);
8920 }
8921 exports.bufferCount = bufferCount;
8922
8923 },{"../operators/bufferCount":161}],119:[function(require,module,exports){
8924 "use strict";
8925 var bufferWhen_1 = require('../operators/bufferWhen');
8926 /**
8927  * Buffers the source Observable values, using a factory function of closing
8928  * Observables to determine when to close, emit, and reset the buffer.
8929  *
8930  * <span class="informal">Collects values from the past as an array. When it
8931  * starts collecting values, it calls a function that returns an Observable that
8932  * tells when to close the buffer and restart collecting.</span>
8933  *
8934  * <img src="./img/bufferWhen.png" width="100%">
8935  *
8936  * Opens a buffer immediately, then closes the buffer when the observable
8937  * returned by calling `closingSelector` function emits a value. When it closes
8938  * the buffer, it immediately opens a new buffer and repeats the process.
8939  *
8940  * @example <caption>Emit an array of the last clicks every [1-5] random seconds</caption>
8941  * var clicks = Rx.Observable.fromEvent(document, 'click');
8942  * var buffered = clicks.bufferWhen(() =>
8943  *   Rx.Observable.interval(1000 + Math.random() * 4000)
8944  * );
8945  * buffered.subscribe(x => console.log(x));
8946  *
8947  * @see {@link buffer}
8948  * @see {@link bufferCount}
8949  * @see {@link bufferTime}
8950  * @see {@link bufferToggle}
8951  * @see {@link windowWhen}
8952  *
8953  * @param {function(): Observable} closingSelector A function that takes no
8954  * arguments and returns an Observable that signals buffer closure.
8955  * @return {Observable<T[]>} An observable of arrays of buffered values.
8956  * @method bufferWhen
8957  * @owner Observable
8958  */
8959 function bufferWhen(closingSelector) {
8960     return bufferWhen_1.bufferWhen(closingSelector)(this);
8961 }
8962 exports.bufferWhen = bufferWhen;
8963
8964 },{"../operators/bufferWhen":162}],120:[function(require,module,exports){
8965 "use strict";
8966 var catchError_1 = require('../operators/catchError');
8967 /**
8968  * Catches errors on the observable to be handled by returning a new observable or throwing an error.
8969  *
8970  * <img src="./img/catch.png" width="100%">
8971  *
8972  * @example <caption>Continues with a different Observable when there's an error</caption>
8973  *
8974  * Observable.of(1, 2, 3, 4, 5)
8975  *   .map(n => {
8976  *         if (n == 4) {
8977  *           throw 'four!';
8978  *     }
8979  *         return n;
8980  *   })
8981  *   .catch(err => Observable.of('I', 'II', 'III', 'IV', 'V'))
8982  *   .subscribe(x => console.log(x));
8983  *   // 1, 2, 3, I, II, III, IV, V
8984  *
8985  * @example <caption>Retries the caught source Observable again in case of error, similar to retry() operator</caption>
8986  *
8987  * Observable.of(1, 2, 3, 4, 5)
8988  *   .map(n => {
8989  *         if (n === 4) {
8990  *           throw 'four!';
8991  *     }
8992  *         return n;
8993  *   })
8994  *   .catch((err, caught) => caught)
8995  *   .take(30)
8996  *   .subscribe(x => console.log(x));
8997  *   // 1, 2, 3, 1, 2, 3, ...
8998  *
8999  * @example <caption>Throws a new error when the source Observable throws an error</caption>
9000  *
9001  * Observable.of(1, 2, 3, 4, 5)
9002  *   .map(n => {
9003  *     if (n == 4) {
9004  *       throw 'four!';
9005  *     }
9006  *     return n;
9007  *   })
9008  *   .catch(err => {
9009  *     throw 'error in source. Details: ' + err;
9010  *   })
9011  *   .subscribe(
9012  *     x => console.log(x),
9013  *     err => console.log(err)
9014  *   );
9015  *   // 1, 2, 3, error in source. Details: four!
9016  *
9017  * @param {function} selector a function that takes as arguments `err`, which is the error, and `caught`, which
9018  *  is the source observable, in case you'd like to "retry" that observable by returning it again. Whatever observable
9019  *  is returned by the `selector` will be used to continue the observable chain.
9020  * @return {Observable} An observable that originates from either the source or the observable returned by the
9021  *  catch `selector` function.
9022  * @method catch
9023  * @name catch
9024  * @owner Observable
9025  */
9026 function _catch(selector) {
9027     return catchError_1.catchError(selector)(this);
9028 }
9029 exports._catch = _catch;
9030
9031 },{"../operators/catchError":163}],121:[function(require,module,exports){
9032 "use strict";
9033 var combineLatest_1 = require('../operators/combineLatest');
9034 /* tslint:enable:max-line-length */
9035 /**
9036  * Combines multiple Observables to create an Observable whose values are
9037  * calculated from the latest values of each of its input Observables.
9038  *
9039  * <span class="informal">Whenever any input Observable emits a value, it
9040  * computes a formula using the latest values from all the inputs, then emits
9041  * the output of that formula.</span>
9042  *
9043  * <img src="./img/combineLatest.png" width="100%">
9044  *
9045  * `combineLatest` combines the values from this Observable with values from
9046  * Observables passed as arguments. This is done by subscribing to each
9047  * Observable, in order, and collecting an array of each of the most recent
9048  * values any time any of the input Observables emits, then either taking that
9049  * array and passing it as arguments to an optional `project` function and
9050  * emitting the return value of that, or just emitting the array of recent
9051  * values directly if there is no `project` function.
9052  *
9053  * @example <caption>Dynamically calculate the Body-Mass Index from an Observable of weight and one for height</caption>
9054  * var weight = Rx.Observable.of(70, 72, 76, 79, 75);
9055  * var height = Rx.Observable.of(1.76, 1.77, 1.78);
9056  * var bmi = weight.combineLatest(height, (w, h) => w / (h * h));
9057  * bmi.subscribe(x => console.log('BMI is ' + x));
9058  *
9059  * // With output to console:
9060  * // BMI is 24.212293388429753
9061  * // BMI is 23.93948099205209
9062  * // BMI is 23.671253629592222
9063  *
9064  * @see {@link combineAll}
9065  * @see {@link merge}
9066  * @see {@link withLatestFrom}
9067  *
9068  * @param {ObservableInput} other An input Observable to combine with the source
9069  * Observable. More than one input Observables may be given as argument.
9070  * @param {function} [project] An optional function to project the values from
9071  * the combined latest values into a new value on the output Observable.
9072  * @return {Observable} An Observable of projected values from the most recent
9073  * values from each input Observable, or an array of the most recent values from
9074  * each input Observable.
9075  * @method combineLatest
9076  * @owner Observable
9077  */
9078 function combineLatest() {
9079     var observables = [];
9080     for (var _i = 0; _i < arguments.length; _i++) {
9081         observables[_i - 0] = arguments[_i];
9082     }
9083     return combineLatest_1.combineLatest.apply(void 0, observables)(this);
9084 }
9085 exports.combineLatest = combineLatest;
9086
9087 },{"../operators/combineLatest":164}],122:[function(require,module,exports){
9088 "use strict";
9089 var concat_1 = require('../operators/concat');
9090 /* tslint:enable:max-line-length */
9091 /**
9092  * Creates an output Observable which sequentially emits all values from every
9093  * given input Observable after the current Observable.
9094  *
9095  * <span class="informal">Concatenates multiple Observables together by
9096  * sequentially emitting their values, one Observable after the other.</span>
9097  *
9098  * <img src="./img/concat.png" width="100%">
9099  *
9100  * Joins this Observable with multiple other Observables by subscribing to them
9101  * one at a time, starting with the source, and merging their results into the
9102  * output Observable. Will wait for each Observable to complete before moving
9103  * on to the next.
9104  *
9105  * @example <caption>Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10</caption>
9106  * var timer = Rx.Observable.interval(1000).take(4);
9107  * var sequence = Rx.Observable.range(1, 10);
9108  * var result = timer.concat(sequence);
9109  * result.subscribe(x => console.log(x));
9110  *
9111  * // results in:
9112  * // 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10
9113  *
9114  * @example <caption>Concatenate 3 Observables</caption>
9115  * var timer1 = Rx.Observable.interval(1000).take(10);
9116  * var timer2 = Rx.Observable.interval(2000).take(6);
9117  * var timer3 = Rx.Observable.interval(500).take(10);
9118  * var result = timer1.concat(timer2, timer3);
9119  * result.subscribe(x => console.log(x));
9120  *
9121  * // results in the following:
9122  * // (Prints to console sequentially)
9123  * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9
9124  * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5
9125  * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9
9126  *
9127  * @see {@link concatAll}
9128  * @see {@link concatMap}
9129  * @see {@link concatMapTo}
9130  *
9131  * @param {ObservableInput} other An input Observable to concatenate after the source
9132  * Observable. More than one input Observables may be given as argument.
9133  * @param {Scheduler} [scheduler=null] An optional IScheduler to schedule each
9134  * Observable subscription on.
9135  * @return {Observable} All values of each passed Observable merged into a
9136  * single Observable, in order, in serial fashion.
9137  * @method concat
9138  * @owner Observable
9139  */
9140 function concat() {
9141     var observables = [];
9142     for (var _i = 0; _i < arguments.length; _i++) {
9143         observables[_i - 0] = arguments[_i];
9144     }
9145     return concat_1.concat.apply(void 0, observables)(this);
9146 }
9147 exports.concat = concat;
9148
9149 },{"../operators/concat":165}],123:[function(require,module,exports){
9150 "use strict";
9151 var async_1 = require('../scheduler/async');
9152 var debounceTime_1 = require('../operators/debounceTime');
9153 /**
9154  * Emits a value from the source Observable only after a particular time span
9155  * has passed without another source emission.
9156  *
9157  * <span class="informal">It's like {@link delay}, but passes only the most
9158  * recent value from each burst of emissions.</span>
9159  *
9160  * <img src="./img/debounceTime.png" width="100%">
9161  *
9162  * `debounceTime` delays values emitted by the source Observable, but drops
9163  * previous pending delayed emissions if a new value arrives on the source
9164  * Observable. This operator keeps track of the most recent value from the
9165  * source Observable, and emits that only when `dueTime` enough time has passed
9166  * without any other value appearing on the source Observable. If a new value
9167  * appears before `dueTime` silence occurs, the previous value will be dropped
9168  * and will not be emitted on the output Observable.
9169  *
9170  * This is a rate-limiting operator, because it is impossible for more than one
9171  * value to be emitted in any time window of duration `dueTime`, but it is also
9172  * a delay-like operator since output emissions do not occur at the same time as
9173  * they did on the source Observable. Optionally takes a {@link IScheduler} for
9174  * managing timers.
9175  *
9176  * @example <caption>Emit the most recent click after a burst of clicks</caption>
9177  * var clicks = Rx.Observable.fromEvent(document, 'click');
9178  * var result = clicks.debounceTime(1000);
9179  * result.subscribe(x => console.log(x));
9180  *
9181  * @see {@link auditTime}
9182  * @see {@link debounce}
9183  * @see {@link delay}
9184  * @see {@link sampleTime}
9185  * @see {@link throttleTime}
9186  *
9187  * @param {number} dueTime The timeout duration in milliseconds (or the time
9188  * unit determined internally by the optional `scheduler`) for the window of
9189  * time required to wait for emission silence before emitting the most recent
9190  * source value.
9191  * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
9192  * managing the timers that handle the timeout for each value.
9193  * @return {Observable} An Observable that delays the emissions of the source
9194  * Observable by the specified `dueTime`, and may drop some values if they occur
9195  * too frequently.
9196  * @method debounceTime
9197  * @owner Observable
9198  */
9199 function debounceTime(dueTime, scheduler) {
9200     if (scheduler === void 0) { scheduler = async_1.async; }
9201     return debounceTime_1.debounceTime(dueTime, scheduler)(this);
9202 }
9203 exports.debounceTime = debounceTime;
9204
9205 },{"../operators/debounceTime":167,"../scheduler/async":213}],124:[function(require,module,exports){
9206 "use strict";
9207 var async_1 = require('../scheduler/async');
9208 var delay_1 = require('../operators/delay');
9209 /**
9210  * Delays the emission of items from the source Observable by a given timeout or
9211  * until a given Date.
9212  *
9213  * <span class="informal">Time shifts each item by some specified amount of
9214  * milliseconds.</span>
9215  *
9216  * <img src="./img/delay.png" width="100%">
9217  *
9218  * If the delay argument is a Number, this operator time shifts the source
9219  * Observable by that amount of time expressed in milliseconds. The relative
9220  * time intervals between the values are preserved.
9221  *
9222  * If the delay argument is a Date, this operator time shifts the start of the
9223  * Observable execution until the given date occurs.
9224  *
9225  * @example <caption>Delay each click by one second</caption>
9226  * var clicks = Rx.Observable.fromEvent(document, 'click');
9227  * var delayedClicks = clicks.delay(1000); // each click emitted after 1 second
9228  * delayedClicks.subscribe(x => console.log(x));
9229  *
9230  * @example <caption>Delay all clicks until a future date happens</caption>
9231  * var clicks = Rx.Observable.fromEvent(document, 'click');
9232  * var date = new Date('March 15, 2050 12:00:00'); // in the future
9233  * var delayedClicks = clicks.delay(date); // click emitted only after that date
9234  * delayedClicks.subscribe(x => console.log(x));
9235  *
9236  * @see {@link debounceTime}
9237  * @see {@link delayWhen}
9238  *
9239  * @param {number|Date} delay The delay duration in milliseconds (a `number`) or
9240  * a `Date` until which the emission of the source items is delayed.
9241  * @param {Scheduler} [scheduler=async] The IScheduler to use for
9242  * managing the timers that handle the time-shift for each item.
9243  * @return {Observable} An Observable that delays the emissions of the source
9244  * Observable by the specified timeout or Date.
9245  * @method delay
9246  * @owner Observable
9247  */
9248 function delay(delay, scheduler) {
9249     if (scheduler === void 0) { scheduler = async_1.async; }
9250     return delay_1.delay(delay, scheduler)(this);
9251 }
9252 exports.delay = delay;
9253
9254 },{"../operators/delay":169,"../scheduler/async":213}],125:[function(require,module,exports){
9255 "use strict";
9256 var distinct_1 = require('../operators/distinct');
9257 /**
9258  * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from previous items.
9259  *
9260  * If a keySelector function is provided, then it will project each value from the source observable into a new value that it will
9261  * check for equality with previously projected values. If a keySelector function is not provided, it will use each value from the
9262  * source observable directly with an equality check against previous values.
9263  *
9264  * In JavaScript runtimes that support `Set`, this operator will use a `Set` to improve performance of the distinct value checking.
9265  *
9266  * In other runtimes, this operator will use a minimal implementation of `Set` that relies on an `Array` and `indexOf` under the
9267  * hood, so performance will degrade as more values are checked for distinction. Even in newer browsers, a long-running `distinct`
9268  * use might result in memory leaks. To help alleviate this in some scenarios, an optional `flushes` parameter is also provided so
9269  * that the internal `Set` can be "flushed", basically clearing it of values.
9270  *
9271  * @example <caption>A simple example with numbers</caption>
9272  * Observable.of(1, 1, 2, 2, 2, 1, 2, 3, 4, 3, 2, 1)
9273  *   .distinct()
9274  *   .subscribe(x => console.log(x)); // 1, 2, 3, 4
9275  *
9276  * @example <caption>An example using a keySelector function</caption>
9277  * interface Person {
9278  *    age: number,
9279  *    name: string
9280  * }
9281  *
9282  * Observable.of<Person>(
9283  *     { age: 4, name: 'Foo'},
9284  *     { age: 7, name: 'Bar'},
9285  *     { age: 5, name: 'Foo'})
9286  *     .distinct((p: Person) => p.name)
9287  *     .subscribe(x => console.log(x));
9288  *
9289  * // displays:
9290  * // { age: 4, name: 'Foo' }
9291  * // { age: 7, name: 'Bar' }
9292  *
9293  * @see {@link distinctUntilChanged}
9294  * @see {@link distinctUntilKeyChanged}
9295  *
9296  * @param {function} [keySelector] Optional function to select which value you want to check as distinct.
9297  * @param {Observable} [flushes] Optional Observable for flushing the internal HashSet of the operator.
9298  * @return {Observable} An Observable that emits items from the source Observable with distinct values.
9299  * @method distinct
9300  * @owner Observable
9301  */
9302 function distinct(keySelector, flushes) {
9303     return distinct_1.distinct(keySelector, flushes)(this);
9304 }
9305 exports.distinct = distinct;
9306
9307 },{"../operators/distinct":170}],126:[function(require,module,exports){
9308 "use strict";
9309 var distinctUntilChanged_1 = require('../operators/distinctUntilChanged');
9310 /* tslint:enable:max-line-length */
9311 /**
9312  * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item.
9313  *
9314  * 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.
9315  *
9316  * If a comparator function is not provided, an equality check is used by default.
9317  *
9318  * @example <caption>A simple example with numbers</caption>
9319  * Observable.of(1, 1, 2, 2, 2, 1, 1, 2, 3, 3, 4)
9320  *   .distinctUntilChanged()
9321  *   .subscribe(x => console.log(x)); // 1, 2, 1, 2, 3, 4
9322  *
9323  * @example <caption>An example using a compare function</caption>
9324  * interface Person {
9325  *    age: number,
9326  *    name: string
9327  * }
9328  *
9329  * Observable.of<Person>(
9330  *     { age: 4, name: 'Foo'},
9331  *     { age: 7, name: 'Bar'},
9332  *     { age: 5, name: 'Foo'})
9333  *     { age: 6, name: 'Foo'})
9334  *     .distinctUntilChanged((p: Person, q: Person) => p.name === q.name)
9335  *     .subscribe(x => console.log(x));
9336  *
9337  * // displays:
9338  * // { age: 4, name: 'Foo' }
9339  * // { age: 7, name: 'Bar' }
9340  * // { age: 5, name: 'Foo' }
9341  *
9342  * @see {@link distinct}
9343  * @see {@link distinctUntilKeyChanged}
9344  *
9345  * @param {function} [compare] Optional comparison function called to test if an item is distinct from the previous item in the source.
9346  * @return {Observable} An Observable that emits items from the source Observable with distinct values.
9347  * @method distinctUntilChanged
9348  * @owner Observable
9349  */
9350 function distinctUntilChanged(compare, keySelector) {
9351     return distinctUntilChanged_1.distinctUntilChanged(compare, keySelector)(this);
9352 }
9353 exports.distinctUntilChanged = distinctUntilChanged;
9354
9355 },{"../operators/distinctUntilChanged":171}],127:[function(require,module,exports){
9356 "use strict";
9357 var tap_1 = require('../operators/tap');
9358 /* tslint:enable:max-line-length */
9359 /**
9360  * Perform a side effect for every emission on the source Observable, but return
9361  * an Observable that is identical to the source.
9362  *
9363  * <span class="informal">Intercepts each emission on the source and runs a
9364  * function, but returns an output which is identical to the source as long as errors don't occur.</span>
9365  *
9366  * <img src="./img/do.png" width="100%">
9367  *
9368  * Returns a mirrored Observable of the source Observable, but modified so that
9369  * the provided Observer is called to perform a side effect for every value,
9370  * error, and completion emitted by the source. Any errors that are thrown in
9371  * the aforementioned Observer or handlers are safely sent down the error path
9372  * of the output Observable.
9373  *
9374  * This operator is useful for debugging your Observables for the correct values
9375  * or performing other side effects.
9376  *
9377  * Note: this is different to a `subscribe` on the Observable. If the Observable
9378  * returned by `do` is not subscribed, the side effects specified by the
9379  * Observer will never happen. `do` therefore simply spies on existing
9380  * execution, it does not trigger an execution to happen like `subscribe` does.
9381  *
9382  * @example <caption>Map every click to the clientX position of that click, while also logging the click event</caption>
9383  * var clicks = Rx.Observable.fromEvent(document, 'click');
9384  * var positions = clicks
9385  *   .do(ev => console.log(ev))
9386  *   .map(ev => ev.clientX);
9387  * positions.subscribe(x => console.log(x));
9388  *
9389  * @see {@link map}
9390  * @see {@link subscribe}
9391  *
9392  * @param {Observer|function} [nextOrObserver] A normal Observer object or a
9393  * callback for `next`.
9394  * @param {function} [error] Callback for errors in the source.
9395  * @param {function} [complete] Callback for the completion of the source.
9396  * @return {Observable} An Observable identical to the source, but runs the
9397  * specified Observer or callback(s) for each item.
9398  * @method do
9399  * @name do
9400  * @owner Observable
9401  */
9402 function _do(nextOrObserver, error, complete) {
9403     return tap_1.tap(nextOrObserver, error, complete)(this);
9404 }
9405 exports._do = _do;
9406
9407 },{"../operators/tap":202}],128:[function(require,module,exports){
9408 "use strict";
9409 var expand_1 = require('../operators/expand');
9410 /* tslint:enable:max-line-length */
9411 /**
9412  * Recursively projects each source value to an Observable which is merged in
9413  * the output Observable.
9414  *
9415  * <span class="informal">It's similar to {@link mergeMap}, but applies the
9416  * projection function to every source value as well as every output value.
9417  * It's recursive.</span>
9418  *
9419  * <img src="./img/expand.png" width="100%">
9420  *
9421  * Returns an Observable that emits items based on applying a function that you
9422  * supply to each item emitted by the source Observable, where that function
9423  * returns an Observable, and then merging those resulting Observables and
9424  * emitting the results of this merger. *Expand* will re-emit on the output
9425  * Observable every source value. Then, each output value is given to the
9426  * `project` function which returns an inner Observable to be merged on the
9427  * output Observable. Those output values resulting from the projection are also
9428  * given to the `project` function to produce new output values. This is how
9429  * *expand* behaves recursively.
9430  *
9431  * @example <caption>Start emitting the powers of two on every click, at most 10 of them</caption>
9432  * var clicks = Rx.Observable.fromEvent(document, 'click');
9433  * var powersOfTwo = clicks
9434  *   .mapTo(1)
9435  *   .expand(x => Rx.Observable.of(2 * x).delay(1000))
9436  *   .take(10);
9437  * powersOfTwo.subscribe(x => console.log(x));
9438  *
9439  * @see {@link mergeMap}
9440  * @see {@link mergeScan}
9441  *
9442  * @param {function(value: T, index: number) => Observable} project A function
9443  * that, when applied to an item emitted by the source or the output Observable,
9444  * returns an Observable.
9445  * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
9446  * Observables being subscribed to concurrently.
9447  * @param {Scheduler} [scheduler=null] The IScheduler to use for subscribing to
9448  * each projected inner Observable.
9449  * @return {Observable} An Observable that emits the source values and also
9450  * result of applying the projection function to each value emitted on the
9451  * output Observable and and merging the results of the Observables obtained
9452  * from this transformation.
9453  * @method expand
9454  * @owner Observable
9455  */
9456 function expand(project, concurrent, scheduler) {
9457     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
9458     if (scheduler === void 0) { scheduler = undefined; }
9459     concurrent = (concurrent || 0) < 1 ? Number.POSITIVE_INFINITY : concurrent;
9460     return expand_1.expand(project, concurrent, scheduler)(this);
9461 }
9462 exports.expand = expand;
9463
9464 },{"../operators/expand":172}],129:[function(require,module,exports){
9465 "use strict";
9466 var filter_1 = require('../operators/filter');
9467 /* tslint:enable:max-line-length */
9468 /**
9469  * Filter items emitted by the source Observable by only emitting those that
9470  * satisfy a specified predicate.
9471  *
9472  * <span class="informal">Like
9473  * [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter),
9474  * it only emits a value from the source if it passes a criterion function.</span>
9475  *
9476  * <img src="./img/filter.png" width="100%">
9477  *
9478  * Similar to the well-known `Array.prototype.filter` method, this operator
9479  * takes values from the source Observable, passes them through a `predicate`
9480  * function and only emits those values that yielded `true`.
9481  *
9482  * @example <caption>Emit only click events whose target was a DIV element</caption>
9483  * var clicks = Rx.Observable.fromEvent(document, 'click');
9484  * var clicksOnDivs = clicks.filter(ev => ev.target.tagName === 'DIV');
9485  * clicksOnDivs.subscribe(x => console.log(x));
9486  *
9487  * @see {@link distinct}
9488  * @see {@link distinctUntilChanged}
9489  * @see {@link distinctUntilKeyChanged}
9490  * @see {@link ignoreElements}
9491  * @see {@link partition}
9492  * @see {@link skip}
9493  *
9494  * @param {function(value: T, index: number): boolean} predicate A function that
9495  * evaluates each value emitted by the source Observable. If it returns `true`,
9496  * the value is emitted, if `false` the value is not passed to the output
9497  * Observable. The `index` parameter is the number `i` for the i-th source
9498  * emission that has happened since the subscription, starting from the number
9499  * `0`.
9500  * @param {any} [thisArg] An optional argument to determine the value of `this`
9501  * in the `predicate` function.
9502  * @return {Observable} An Observable of values from the source that were
9503  * allowed by the `predicate` function.
9504  * @method filter
9505  * @owner Observable
9506  */
9507 function filter(predicate, thisArg) {
9508     return filter_1.filter(predicate, thisArg)(this);
9509 }
9510 exports.filter = filter;
9511
9512 },{"../operators/filter":173}],130:[function(require,module,exports){
9513 "use strict";
9514 var finalize_1 = require('../operators/finalize');
9515 /**
9516  * Returns an Observable that mirrors the source Observable, but will call a specified function when
9517  * the source terminates on complete or error.
9518  * @param {function} callback Function to be called when source terminates.
9519  * @return {Observable} An Observable that mirrors the source, but will call the specified function on termination.
9520  * @method finally
9521  * @owner Observable
9522  */
9523 function _finally(callback) {
9524     return finalize_1.finalize(callback)(this);
9525 }
9526 exports._finally = _finally;
9527
9528 },{"../operators/finalize":174}],131:[function(require,module,exports){
9529 "use strict";
9530 var first_1 = require('../operators/first');
9531 /**
9532  * Emits only the first value (or the first value that meets some condition)
9533  * emitted by the source Observable.
9534  *
9535  * <span class="informal">Emits only the first value. Or emits only the first
9536  * value that passes some test.</span>
9537  *
9538  * <img src="./img/first.png" width="100%">
9539  *
9540  * If called with no arguments, `first` emits the first value of the source
9541  * Observable, then completes. If called with a `predicate` function, `first`
9542  * emits the first value of the source that matches the specified condition. It
9543  * may also take a `resultSelector` function to produce the output value from
9544  * the input value, and a `defaultValue` to emit in case the source completes
9545  * before it is able to emit a valid value. Throws an error if `defaultValue`
9546  * was not provided and a matching element is not found.
9547  *
9548  * @example <caption>Emit only the first click that happens on the DOM</caption>
9549  * var clicks = Rx.Observable.fromEvent(document, 'click');
9550  * var result = clicks.first();
9551  * result.subscribe(x => console.log(x));
9552  *
9553  * @example <caption>Emits the first click that happens on a DIV</caption>
9554  * var clicks = Rx.Observable.fromEvent(document, 'click');
9555  * var result = clicks.first(ev => ev.target.tagName === 'DIV');
9556  * result.subscribe(x => console.log(x));
9557  *
9558  * @see {@link filter}
9559  * @see {@link find}
9560  * @see {@link take}
9561  *
9562  * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
9563  * callback if the Observable completes before any `next` notification was sent.
9564  *
9565  * @param {function(value: T, index: number, source: Observable<T>): boolean} [predicate]
9566  * An optional function called with each item to test for condition matching.
9567  * @param {function(value: T, index: number): R} [resultSelector] A function to
9568  * produce the value on the output Observable based on the values
9569  * and the indices of the source Observable. The arguments passed to this
9570  * function are:
9571  * - `value`: the value that was emitted on the source.
9572  * - `index`: the "index" of the value from the source.
9573  * @param {R} [defaultValue] The default value emitted in case no valid value
9574  * was found on the source.
9575  * @return {Observable<T|R>} An Observable of the first item that matches the
9576  * condition.
9577  * @method first
9578  * @owner Observable
9579  */
9580 function first(predicate, resultSelector, defaultValue) {
9581     return first_1.first(predicate, resultSelector, defaultValue)(this);
9582 }
9583 exports.first = first;
9584
9585 },{"../operators/first":175}],132:[function(require,module,exports){
9586 "use strict";
9587 var last_1 = require('../operators/last');
9588 /* tslint:enable:max-line-length */
9589 /**
9590  * Returns an Observable that emits only the last item emitted by the source Observable.
9591  * It optionally takes a predicate function as a parameter, in which case, rather than emitting
9592  * the last item from the source Observable, the resulting Observable will emit the last item
9593  * from the source Observable that satisfies the predicate.
9594  *
9595  * <img src="./img/last.png" width="100%">
9596  *
9597  * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
9598  * callback if the Observable completes before any `next` notification was sent.
9599  * @param {function} predicate - The condition any source emitted item has to satisfy.
9600  * @return {Observable} An Observable that emits only the last item satisfying the given condition
9601  * from the source, or an NoSuchElementException if no such items are emitted.
9602  * @throws - Throws if no items that match the predicate are emitted by the source Observable.
9603  * @method last
9604  * @owner Observable
9605  */
9606 function last(predicate, resultSelector, defaultValue) {
9607     return last_1.last(predicate, resultSelector, defaultValue)(this);
9608 }
9609 exports.last = last;
9610
9611 },{"../operators/last":176}],133:[function(require,module,exports){
9612 "use strict";
9613 var map_1 = require('../operators/map');
9614 /**
9615  * Applies a given `project` function to each value emitted by the source
9616  * Observable, and emits the resulting values as an Observable.
9617  *
9618  * <span class="informal">Like [Array.prototype.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map),
9619  * it passes each source value through a transformation function to get
9620  * corresponding output values.</span>
9621  *
9622  * <img src="./img/map.png" width="100%">
9623  *
9624  * Similar to the well known `Array.prototype.map` function, this operator
9625  * applies a projection to each value and emits that projection in the output
9626  * Observable.
9627  *
9628  * @example <caption>Map every click to the clientX position of that click</caption>
9629  * var clicks = Rx.Observable.fromEvent(document, 'click');
9630  * var positions = clicks.map(ev => ev.clientX);
9631  * positions.subscribe(x => console.log(x));
9632  *
9633  * @see {@link mapTo}
9634  * @see {@link pluck}
9635  *
9636  * @param {function(value: T, index: number): R} project The function to apply
9637  * to each `value` emitted by the source Observable. The `index` parameter is
9638  * the number `i` for the i-th emission that has happened since the
9639  * subscription, starting from the number `0`.
9640  * @param {any} [thisArg] An optional argument to define what `this` is in the
9641  * `project` function.
9642  * @return {Observable<R>} An Observable that emits the values from the source
9643  * Observable transformed by the given `project` function.
9644  * @method map
9645  * @owner Observable
9646  */
9647 function map(project, thisArg) {
9648     return map_1.map(project, thisArg)(this);
9649 }
9650 exports.map = map;
9651
9652 },{"../operators/map":177}],134:[function(require,module,exports){
9653 "use strict";
9654 var merge_1 = require('../operators/merge');
9655 var merge_2 = require('../operators/merge');
9656 exports.mergeStatic = merge_2.mergeStatic;
9657 /* tslint:enable:max-line-length */
9658 /**
9659  * Creates an output Observable which concurrently emits all values from every
9660  * given input Observable.
9661  *
9662  * <span class="informal">Flattens multiple Observables together by blending
9663  * their values into one Observable.</span>
9664  *
9665  * <img src="./img/merge.png" width="100%">
9666  *
9667  * `merge` subscribes to each given input Observable (either the source or an
9668  * Observable given as argument), and simply forwards (without doing any
9669  * transformation) all the values from all the input Observables to the output
9670  * Observable. The output Observable only completes once all input Observables
9671  * have completed. Any error delivered by an input Observable will be immediately
9672  * emitted on the output Observable.
9673  *
9674  * @example <caption>Merge together two Observables: 1s interval and clicks</caption>
9675  * var clicks = Rx.Observable.fromEvent(document, 'click');
9676  * var timer = Rx.Observable.interval(1000);
9677  * var clicksOrTimer = clicks.merge(timer);
9678  * clicksOrTimer.subscribe(x => console.log(x));
9679  *
9680  * @example <caption>Merge together 3 Observables, but only 2 run concurrently</caption>
9681  * var timer1 = Rx.Observable.interval(1000).take(10);
9682  * var timer2 = Rx.Observable.interval(2000).take(6);
9683  * var timer3 = Rx.Observable.interval(500).take(10);
9684  * var concurrent = 2; // the argument
9685  * var merged = timer1.merge(timer2, timer3, concurrent);
9686  * merged.subscribe(x => console.log(x));
9687  *
9688  * @see {@link mergeAll}
9689  * @see {@link mergeMap}
9690  * @see {@link mergeMapTo}
9691  * @see {@link mergeScan}
9692  *
9693  * @param {ObservableInput} other An input Observable to merge with the source
9694  * Observable. More than one input Observables may be given as argument.
9695  * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
9696  * Observables being subscribed to concurrently.
9697  * @param {Scheduler} [scheduler=null] The IScheduler to use for managing
9698  * concurrency of input Observables.
9699  * @return {Observable} An Observable that emits items that are the result of
9700  * every input Observable.
9701  * @method merge
9702  * @owner Observable
9703  */
9704 function merge() {
9705     var observables = [];
9706     for (var _i = 0; _i < arguments.length; _i++) {
9707         observables[_i - 0] = arguments[_i];
9708     }
9709     return merge_1.merge.apply(void 0, observables)(this);
9710 }
9711 exports.merge = merge;
9712
9713 },{"../operators/merge":178}],135:[function(require,module,exports){
9714 "use strict";
9715 var mergeAll_1 = require('../operators/mergeAll');
9716 /**
9717  * Converts a higher-order Observable into a first-order Observable which
9718  * concurrently delivers all values that are emitted on the inner Observables.
9719  *
9720  * <span class="informal">Flattens an Observable-of-Observables.</span>
9721  *
9722  * <img src="./img/mergeAll.png" width="100%">
9723  *
9724  * `mergeAll` subscribes to an Observable that emits Observables, also known as
9725  * a higher-order Observable. Each time it observes one of these emitted inner
9726  * Observables, it subscribes to that and delivers all the values from the
9727  * inner Observable on the output Observable. The output Observable only
9728  * completes once all inner Observables have completed. Any error delivered by
9729  * a inner Observable will be immediately emitted on the output Observable.
9730  *
9731  * @example <caption>Spawn a new interval Observable for each click event, and blend their outputs as one Observable</caption>
9732  * var clicks = Rx.Observable.fromEvent(document, 'click');
9733  * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000));
9734  * var firstOrder = higherOrder.mergeAll();
9735  * firstOrder.subscribe(x => console.log(x));
9736  *
9737  * @example <caption>Count from 0 to 9 every second for each click, but only allow 2 concurrent timers</caption>
9738  * var clicks = Rx.Observable.fromEvent(document, 'click');
9739  * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000).take(10));
9740  * var firstOrder = higherOrder.mergeAll(2);
9741  * firstOrder.subscribe(x => console.log(x));
9742  *
9743  * @see {@link combineAll}
9744  * @see {@link concatAll}
9745  * @see {@link exhaust}
9746  * @see {@link merge}
9747  * @see {@link mergeMap}
9748  * @see {@link mergeMapTo}
9749  * @see {@link mergeScan}
9750  * @see {@link switch}
9751  * @see {@link zipAll}
9752  *
9753  * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of inner
9754  * Observables being subscribed to concurrently.
9755  * @return {Observable} An Observable that emits values coming from all the
9756  * inner Observables emitted by the source Observable.
9757  * @method mergeAll
9758  * @owner Observable
9759  */
9760 function mergeAll(concurrent) {
9761     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
9762     return mergeAll_1.mergeAll(concurrent)(this);
9763 }
9764 exports.mergeAll = mergeAll;
9765
9766 },{"../operators/mergeAll":179}],136:[function(require,module,exports){
9767 "use strict";
9768 var mergeMap_1 = require('../operators/mergeMap');
9769 /* tslint:enable:max-line-length */
9770 /**
9771  * Projects each source value to an Observable which is merged in the output
9772  * Observable.
9773  *
9774  * <span class="informal">Maps each value to an Observable, then flattens all of
9775  * these inner Observables using {@link mergeAll}.</span>
9776  *
9777  * <img src="./img/mergeMap.png" width="100%">
9778  *
9779  * Returns an Observable that emits items based on applying a function that you
9780  * supply to each item emitted by the source Observable, where that function
9781  * returns an Observable, and then merging those resulting Observables and
9782  * emitting the results of this merger.
9783  *
9784  * @example <caption>Map and flatten each letter to an Observable ticking every 1 second</caption>
9785  * var letters = Rx.Observable.of('a', 'b', 'c');
9786  * var result = letters.mergeMap(x =>
9787  *   Rx.Observable.interval(1000).map(i => x+i)
9788  * );
9789  * result.subscribe(x => console.log(x));
9790  *
9791  * // Results in the following:
9792  * // a0
9793  * // b0
9794  * // c0
9795  * // a1
9796  * // b1
9797  * // c1
9798  * // continues to list a,b,c with respective ascending integers
9799  *
9800  * @see {@link concatMap}
9801  * @see {@link exhaustMap}
9802  * @see {@link merge}
9803  * @see {@link mergeAll}
9804  * @see {@link mergeMapTo}
9805  * @see {@link mergeScan}
9806  * @see {@link switchMap}
9807  *
9808  * @param {function(value: T, ?index: number): ObservableInput} project A function
9809  * that, when applied to an item emitted by the source Observable, returns an
9810  * Observable.
9811  * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
9812  * A function to produce the value on the output Observable based on the values
9813  * and the indices of the source (outer) emission and the inner Observable
9814  * emission. The arguments passed to this function are:
9815  * - `outerValue`: the value that came from the source
9816  * - `innerValue`: the value that came from the projected Observable
9817  * - `outerIndex`: the "index" of the value that came from the source
9818  * - `innerIndex`: the "index" of the value from the projected Observable
9819  * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
9820  * Observables being subscribed to concurrently.
9821  * @return {Observable} An Observable that emits the result of applying the
9822  * projection function (and the optional `resultSelector`) to each item emitted
9823  * by the source Observable and merging the results of the Observables obtained
9824  * from this transformation.
9825  * @method mergeMap
9826  * @owner Observable
9827  */
9828 function mergeMap(project, resultSelector, concurrent) {
9829     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
9830     return mergeMap_1.mergeMap(project, resultSelector, concurrent)(this);
9831 }
9832 exports.mergeMap = mergeMap;
9833
9834 },{"../operators/mergeMap":180}],137:[function(require,module,exports){
9835 "use strict";
9836 var pairwise_1 = require('../operators/pairwise');
9837 /**
9838  * Groups pairs of consecutive emissions together and emits them as an array of
9839  * two values.
9840  *
9841  * <span class="informal">Puts the current value and previous value together as
9842  * an array, and emits that.</span>
9843  *
9844  * <img src="./img/pairwise.png" width="100%">
9845  *
9846  * The Nth emission from the source Observable will cause the output Observable
9847  * to emit an array [(N-1)th, Nth] of the previous and the current value, as a
9848  * pair. For this reason, `pairwise` emits on the second and subsequent
9849  * emissions from the source Observable, but not on the first emission, because
9850  * there is no previous value in that case.
9851  *
9852  * @example <caption>On every click (starting from the second), emit the relative distance to the previous click</caption>
9853  * var clicks = Rx.Observable.fromEvent(document, 'click');
9854  * var pairs = clicks.pairwise();
9855  * var distance = pairs.map(pair => {
9856  *   var x0 = pair[0].clientX;
9857  *   var y0 = pair[0].clientY;
9858  *   var x1 = pair[1].clientX;
9859  *   var y1 = pair[1].clientY;
9860  *   return Math.sqrt(Math.pow(x0 - x1, 2) + Math.pow(y0 - y1, 2));
9861  * });
9862  * distance.subscribe(x => console.log(x));
9863  *
9864  * @see {@link buffer}
9865  * @see {@link bufferCount}
9866  *
9867  * @return {Observable<Array<T>>} An Observable of pairs (as arrays) of
9868  * consecutive values from the source Observable.
9869  * @method pairwise
9870  * @owner Observable
9871  */
9872 function pairwise() {
9873     return pairwise_1.pairwise()(this);
9874 }
9875 exports.pairwise = pairwise;
9876
9877 },{"../operators/pairwise":183}],138:[function(require,module,exports){
9878 "use strict";
9879 var pluck_1 = require('../operators/pluck');
9880 /**
9881  * Maps each source value (an object) to its specified nested property.
9882  *
9883  * <span class="informal">Like {@link map}, but meant only for picking one of
9884  * the nested properties of every emitted object.</span>
9885  *
9886  * <img src="./img/pluck.png" width="100%">
9887  *
9888  * Given a list of strings describing a path to an object property, retrieves
9889  * the value of a specified nested property from all values in the source
9890  * Observable. If a property can't be resolved, it will return `undefined` for
9891  * that value.
9892  *
9893  * @example <caption>Map every click to the tagName of the clicked target element</caption>
9894  * var clicks = Rx.Observable.fromEvent(document, 'click');
9895  * var tagNames = clicks.pluck('target', 'tagName');
9896  * tagNames.subscribe(x => console.log(x));
9897  *
9898  * @see {@link map}
9899  *
9900  * @param {...string} properties The nested properties to pluck from each source
9901  * value (an object).
9902  * @return {Observable} A new Observable of property values from the source values.
9903  * @method pluck
9904  * @owner Observable
9905  */
9906 function pluck() {
9907     var properties = [];
9908     for (var _i = 0; _i < arguments.length; _i++) {
9909         properties[_i - 0] = arguments[_i];
9910     }
9911     return pluck_1.pluck.apply(void 0, properties)(this);
9912 }
9913 exports.pluck = pluck;
9914
9915 },{"../operators/pluck":184}],139:[function(require,module,exports){
9916 "use strict";
9917 var publish_1 = require('../operators/publish');
9918 /* tslint:enable:max-line-length */
9919 /**
9920  * Returns a ConnectableObservable, which is a variety of Observable that waits until its connect method is called
9921  * before it begins emitting items to those Observers that have subscribed to it.
9922  *
9923  * <img src="./img/publish.png" width="100%">
9924  *
9925  * @param {Function} [selector] - Optional selector function which can use the multicasted source sequence as many times
9926  * as needed, without causing multiple subscriptions to the source sequence.
9927  * Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
9928  * @return A ConnectableObservable that upon connection causes the source Observable to emit items to its Observers.
9929  * @method publish
9930  * @owner Observable
9931  */
9932 function publish(selector) {
9933     return publish_1.publish(selector)(this);
9934 }
9935 exports.publish = publish;
9936
9937 },{"../operators/publish":185}],140:[function(require,module,exports){
9938 "use strict";
9939 var publishReplay_1 = require('../operators/publishReplay');
9940 /* tslint:enable:max-line-length */
9941 /**
9942  * @param bufferSize
9943  * @param windowTime
9944  * @param selectorOrScheduler
9945  * @param scheduler
9946  * @return {Observable<T> | ConnectableObservable<T>}
9947  * @method publishReplay
9948  * @owner Observable
9949  */
9950 function publishReplay(bufferSize, windowTime, selectorOrScheduler, scheduler) {
9951     return publishReplay_1.publishReplay(bufferSize, windowTime, selectorOrScheduler, scheduler)(this);
9952 }
9953 exports.publishReplay = publishReplay;
9954
9955 },{"../operators/publishReplay":186}],141:[function(require,module,exports){
9956 "use strict";
9957 var reduce_1 = require('../operators/reduce');
9958 /* tslint:enable:max-line-length */
9959 /**
9960  * Applies an accumulator function over the source Observable, and returns the
9961  * accumulated result when the source completes, given an optional seed value.
9962  *
9963  * <span class="informal">Combines together all values emitted on the source,
9964  * using an accumulator function that knows how to join a new source value into
9965  * the accumulation from the past.</span>
9966  *
9967  * <img src="./img/reduce.png" width="100%">
9968  *
9969  * Like
9970  * [Array.prototype.reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce),
9971  * `reduce` applies an `accumulator` function against an accumulation and each
9972  * value of the source Observable (from the past) to reduce it to a single
9973  * value, emitted on the output Observable. Note that `reduce` will only emit
9974  * one value, only when the source Observable completes. It is equivalent to
9975  * applying operator {@link scan} followed by operator {@link last}.
9976  *
9977  * Returns an Observable that applies a specified `accumulator` function to each
9978  * item emitted by the source Observable. If a `seed` value is specified, then
9979  * that value will be used as the initial value for the accumulator. If no seed
9980  * value is specified, the first item of the source is used as the seed.
9981  *
9982  * @example <caption>Count the number of click events that happened in 5 seconds</caption>
9983  * var clicksInFiveSeconds = Rx.Observable.fromEvent(document, 'click')
9984  *   .takeUntil(Rx.Observable.interval(5000));
9985  * var ones = clicksInFiveSeconds.mapTo(1);
9986  * var seed = 0;
9987  * var count = ones.reduce((acc, one) => acc + one, seed);
9988  * count.subscribe(x => console.log(x));
9989  *
9990  * @see {@link count}
9991  * @see {@link expand}
9992  * @see {@link mergeScan}
9993  * @see {@link scan}
9994  *
9995  * @param {function(acc: R, value: T, index: number): R} accumulator The accumulator function
9996  * called on each source value.
9997  * @param {R} [seed] The initial accumulation value.
9998  * @return {Observable<R>} An Observable that emits a single value that is the
9999  * result of accumulating the values emitted by the source Observable.
10000  * @method reduce
10001  * @owner Observable
10002  */
10003 function reduce(accumulator, seed) {
10004     // providing a seed of `undefined` *should* be valid and trigger
10005     // hasSeed! so don't use `seed !== undefined` checks!
10006     // For this reason, we have to check it here at the original call site
10007     // otherwise inside Operator/Subscriber we won't know if `undefined`
10008     // means they didn't provide anything or if they literally provided `undefined`
10009     if (arguments.length >= 2) {
10010         return reduce_1.reduce(accumulator, seed)(this);
10011     }
10012     return reduce_1.reduce(accumulator)(this);
10013 }
10014 exports.reduce = reduce;
10015
10016 },{"../operators/reduce":187}],142:[function(require,module,exports){
10017 "use strict";
10018 var retry_1 = require('../operators/retry');
10019 /**
10020  * Returns an Observable that mirrors the source Observable with the exception of an `error`. If the source Observable
10021  * calls `error`, this method will resubscribe to the source Observable for a maximum of `count` resubscriptions (given
10022  * as a number parameter) rather than propagating the `error` call.
10023  *
10024  * <img src="./img/retry.png" width="100%">
10025  *
10026  * Any and all items emitted by the source Observable will be emitted by the resulting Observable, even those emitted
10027  * during failed subscriptions. For example, if an Observable fails at first but emits [1, 2] then succeeds the second
10028  * time and emits: [1, 2, 3, 4, 5] then the complete stream of emissions and notifications
10029  * would be: [1, 2, 1, 2, 3, 4, 5, `complete`].
10030  * @param {number} count - Number of retry attempts before failing.
10031  * @return {Observable} The source Observable modified with the retry logic.
10032  * @method retry
10033  * @owner Observable
10034  */
10035 function retry(count) {
10036     if (count === void 0) { count = -1; }
10037     return retry_1.retry(count)(this);
10038 }
10039 exports.retry = retry;
10040
10041 },{"../operators/retry":189}],143:[function(require,module,exports){
10042 "use strict";
10043 var sample_1 = require('../operators/sample');
10044 /**
10045  * Emits the most recently emitted value from the source Observable whenever
10046  * another Observable, the `notifier`, emits.
10047  *
10048  * <span class="informal">It's like {@link sampleTime}, but samples whenever
10049  * the `notifier` Observable emits something.</span>
10050  *
10051  * <img src="./img/sample.png" width="100%">
10052  *
10053  * Whenever the `notifier` Observable emits a value or completes, `sample`
10054  * looks at the source Observable and emits whichever value it has most recently
10055  * emitted since the previous sampling, unless the source has not emitted
10056  * anything since the previous sampling. The `notifier` is subscribed to as soon
10057  * as the output Observable is subscribed.
10058  *
10059  * @example <caption>On every click, sample the most recent "seconds" timer</caption>
10060  * var seconds = Rx.Observable.interval(1000);
10061  * var clicks = Rx.Observable.fromEvent(document, 'click');
10062  * var result = seconds.sample(clicks);
10063  * result.subscribe(x => console.log(x));
10064  *
10065  * @see {@link audit}
10066  * @see {@link debounce}
10067  * @see {@link sampleTime}
10068  * @see {@link throttle}
10069  *
10070  * @param {Observable<any>} notifier The Observable to use for sampling the
10071  * source Observable.
10072  * @return {Observable<T>} An Observable that emits the results of sampling the
10073  * values emitted by the source Observable whenever the notifier Observable
10074  * emits value or completes.
10075  * @method sample
10076  * @owner Observable
10077  */
10078 function sample(notifier) {
10079     return sample_1.sample(notifier)(this);
10080 }
10081 exports.sample = sample;
10082
10083 },{"../operators/sample":190}],144:[function(require,module,exports){
10084 "use strict";
10085 var scan_1 = require('../operators/scan');
10086 /* tslint:enable:max-line-length */
10087 /**
10088  * Applies an accumulator function over the source Observable, and returns each
10089  * intermediate result, with an optional seed value.
10090  *
10091  * <span class="informal">It's like {@link reduce}, but emits the current
10092  * accumulation whenever the source emits a value.</span>
10093  *
10094  * <img src="./img/scan.png" width="100%">
10095  *
10096  * Combines together all values emitted on the source, using an accumulator
10097  * function that knows how to join a new source value into the accumulation from
10098  * the past. Is similar to {@link reduce}, but emits the intermediate
10099  * accumulations.
10100  *
10101  * Returns an Observable that applies a specified `accumulator` function to each
10102  * item emitted by the source Observable. If a `seed` value is specified, then
10103  * that value will be used as the initial value for the accumulator. If no seed
10104  * value is specified, the first item of the source is used as the seed.
10105  *
10106  * @example <caption>Count the number of click events</caption>
10107  * var clicks = Rx.Observable.fromEvent(document, 'click');
10108  * var ones = clicks.mapTo(1);
10109  * var seed = 0;
10110  * var count = ones.scan((acc, one) => acc + one, seed);
10111  * count.subscribe(x => console.log(x));
10112  *
10113  * @see {@link expand}
10114  * @see {@link mergeScan}
10115  * @see {@link reduce}
10116  *
10117  * @param {function(acc: R, value: T, index: number): R} accumulator
10118  * The accumulator function called on each source value.
10119  * @param {T|R} [seed] The initial accumulation value.
10120  * @return {Observable<R>} An observable of the accumulated values.
10121  * @method scan
10122  * @owner Observable
10123  */
10124 function scan(accumulator, seed) {
10125     if (arguments.length >= 2) {
10126         return scan_1.scan(accumulator, seed)(this);
10127     }
10128     return scan_1.scan(accumulator)(this);
10129 }
10130 exports.scan = scan;
10131
10132 },{"../operators/scan":191}],145:[function(require,module,exports){
10133 "use strict";
10134 var share_1 = require('../operators/share');
10135 /**
10136  * Returns a new Observable that multicasts (shares) the original Observable. As long as there is at least one
10137  * Subscriber this Observable will be subscribed and emitting data. When all subscribers have unsubscribed it will
10138  * unsubscribe from the source Observable. Because the Observable is multicasting it makes the stream `hot`.
10139  *
10140  * This behaves similarly to .publish().refCount(), with a behavior difference when the source observable emits complete.
10141  * .publish().refCount() will not resubscribe to the original source, however .share() will resubscribe to the original source.
10142  * Observable.of("test").publish().refCount() will not re-emit "test" on new subscriptions, Observable.of("test").share() will
10143  * re-emit "test" to new subscriptions.
10144  *
10145  * <img src="./img/share.png" width="100%">
10146  *
10147  * @return {Observable<T>} An Observable that upon connection causes the source Observable to emit items to its Observers.
10148  * @method share
10149  * @owner Observable
10150  */
10151 function share() {
10152     return share_1.share()(this);
10153 }
10154 exports.share = share;
10155 ;
10156
10157 },{"../operators/share":192}],146:[function(require,module,exports){
10158 "use strict";
10159 var skip_1 = require('../operators/skip');
10160 /**
10161  * Returns an Observable that skips the first `count` items emitted by the source Observable.
10162  *
10163  * <img src="./img/skip.png" width="100%">
10164  *
10165  * @param {Number} count - The number of times, items emitted by source Observable should be skipped.
10166  * @return {Observable} An Observable that skips values emitted by the source Observable.
10167  *
10168  * @method skip
10169  * @owner Observable
10170  */
10171 function skip(count) {
10172     return skip_1.skip(count)(this);
10173 }
10174 exports.skip = skip;
10175
10176 },{"../operators/skip":193}],147:[function(require,module,exports){
10177 "use strict";
10178 var skipUntil_1 = require('../operators/skipUntil');
10179 /**
10180  * Returns an Observable that skips items emitted by the source Observable until a second Observable emits an item.
10181  *
10182  * <img src="./img/skipUntil.png" width="100%">
10183  *
10184  * @param {Observable} notifier - The second Observable that has to emit an item before the source Observable's elements begin to
10185  * be mirrored by the resulting Observable.
10186  * @return {Observable<T>} An Observable that skips items from the source Observable until the second Observable emits
10187  * an item, then emits the remaining items.
10188  * @method skipUntil
10189  * @owner Observable
10190  */
10191 function skipUntil(notifier) {
10192     return skipUntil_1.skipUntil(notifier)(this);
10193 }
10194 exports.skipUntil = skipUntil;
10195
10196 },{"../operators/skipUntil":194}],148:[function(require,module,exports){
10197 "use strict";
10198 var skipWhile_1 = require('../operators/skipWhile');
10199 /**
10200  * Returns an Observable that skips all items emitted by the source Observable as long as a specified condition holds
10201  * true, but emits all further source items as soon as the condition becomes false.
10202  *
10203  * <img src="./img/skipWhile.png" width="100%">
10204  *
10205  * @param {Function} predicate - A function to test each item emitted from the source Observable.
10206  * @return {Observable<T>} An Observable that begins emitting items emitted by the source Observable when the
10207  * specified predicate becomes false.
10208  * @method skipWhile
10209  * @owner Observable
10210  */
10211 function skipWhile(predicate) {
10212     return skipWhile_1.skipWhile(predicate)(this);
10213 }
10214 exports.skipWhile = skipWhile;
10215
10216 },{"../operators/skipWhile":195}],149:[function(require,module,exports){
10217 "use strict";
10218 var startWith_1 = require('../operators/startWith');
10219 /* tslint:enable:max-line-length */
10220 /**
10221  * Returns an Observable that emits the items you specify as arguments before it begins to emit
10222  * items emitted by the source Observable.
10223  *
10224  * <img src="./img/startWith.png" width="100%">
10225  *
10226  * @param {...T} values - Items you want the modified Observable to emit first.
10227  * @param {Scheduler} [scheduler] - A {@link IScheduler} to use for scheduling
10228  * the emissions of the `next` notifications.
10229  * @return {Observable} An Observable that emits the items in the specified Iterable and then emits the items
10230  * emitted by the source Observable.
10231  * @method startWith
10232  * @owner Observable
10233  */
10234 function startWith() {
10235     var array = [];
10236     for (var _i = 0; _i < arguments.length; _i++) {
10237         array[_i - 0] = arguments[_i];
10238     }
10239     return startWith_1.startWith.apply(void 0, array)(this);
10240 }
10241 exports.startWith = startWith;
10242
10243 },{"../operators/startWith":196}],150:[function(require,module,exports){
10244 "use strict";
10245 var switchMap_1 = require('../operators/switchMap');
10246 /* tslint:enable:max-line-length */
10247 /**
10248  * Projects each source value to an Observable which is merged in the output
10249  * Observable, emitting values only from the most recently projected Observable.
10250  *
10251  * <span class="informal">Maps each value to an Observable, then flattens all of
10252  * these inner Observables using {@link switch}.</span>
10253  *
10254  * <img src="./img/switchMap.png" width="100%">
10255  *
10256  * Returns an Observable that emits items based on applying a function that you
10257  * supply to each item emitted by the source Observable, where that function
10258  * returns an (so-called "inner") Observable. Each time it observes one of these
10259  * inner Observables, the output Observable begins emitting the items emitted by
10260  * that inner Observable. When a new inner Observable is emitted, `switchMap`
10261  * stops emitting items from the earlier-emitted inner Observable and begins
10262  * emitting items from the new one. It continues to behave like this for
10263  * subsequent inner Observables.
10264  *
10265  * @example <caption>Rerun an interval Observable on every click event</caption>
10266  * var clicks = Rx.Observable.fromEvent(document, 'click');
10267  * var result = clicks.switchMap((ev) => Rx.Observable.interval(1000));
10268  * result.subscribe(x => console.log(x));
10269  *
10270  * @see {@link concatMap}
10271  * @see {@link exhaustMap}
10272  * @see {@link mergeMap}
10273  * @see {@link switch}
10274  * @see {@link switchMapTo}
10275  *
10276  * @param {function(value: T, ?index: number): ObservableInput} project A function
10277  * that, when applied to an item emitted by the source Observable, returns an
10278  * Observable.
10279  * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
10280  * A function to produce the value on the output Observable based on the values
10281  * and the indices of the source (outer) emission and the inner Observable
10282  * emission. The arguments passed to this function are:
10283  * - `outerValue`: the value that came from the source
10284  * - `innerValue`: the value that came from the projected Observable
10285  * - `outerIndex`: the "index" of the value that came from the source
10286  * - `innerIndex`: the "index" of the value from the projected Observable
10287  * @return {Observable} An Observable that emits the result of applying the
10288  * projection function (and the optional `resultSelector`) to each item emitted
10289  * by the source Observable and taking only the values from the most recently
10290  * projected inner Observable.
10291  * @method switchMap
10292  * @owner Observable
10293  */
10294 function switchMap(project, resultSelector) {
10295     return switchMap_1.switchMap(project, resultSelector)(this);
10296 }
10297 exports.switchMap = switchMap;
10298
10299 },{"../operators/switchMap":197}],151:[function(require,module,exports){
10300 "use strict";
10301 var take_1 = require('../operators/take');
10302 /**
10303  * Emits only the first `count` values emitted by the source Observable.
10304  *
10305  * <span class="informal">Takes the first `count` values from the source, then
10306  * completes.</span>
10307  *
10308  * <img src="./img/take.png" width="100%">
10309  *
10310  * `take` returns an Observable that emits only the first `count` values emitted
10311  * by the source Observable. If the source emits fewer than `count` values then
10312  * all of its values are emitted. After that, it completes, regardless if the
10313  * source completes.
10314  *
10315  * @example <caption>Take the first 5 seconds of an infinite 1-second interval Observable</caption>
10316  * var interval = Rx.Observable.interval(1000);
10317  * var five = interval.take(5);
10318  * five.subscribe(x => console.log(x));
10319  *
10320  * @see {@link takeLast}
10321  * @see {@link takeUntil}
10322  * @see {@link takeWhile}
10323  * @see {@link skip}
10324  *
10325  * @throws {ArgumentOutOfRangeError} When using `take(i)`, it delivers an
10326  * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0`.
10327  *
10328  * @param {number} count The maximum number of `next` values to emit.
10329  * @return {Observable<T>} An Observable that emits only the first `count`
10330  * values emitted by the source Observable, or all of the values from the source
10331  * if the source emits fewer than `count` values.
10332  * @method take
10333  * @owner Observable
10334  */
10335 function take(count) {
10336     return take_1.take(count)(this);
10337 }
10338 exports.take = take;
10339
10340 },{"../operators/take":198}],152:[function(require,module,exports){
10341 "use strict";
10342 var takeUntil_1 = require('../operators/takeUntil');
10343 /**
10344  * Emits the values emitted by the source Observable until a `notifier`
10345  * Observable emits a value.
10346  *
10347  * <span class="informal">Lets values pass until a second Observable,
10348  * `notifier`, emits something. Then, it completes.</span>
10349  *
10350  * <img src="./img/takeUntil.png" width="100%">
10351  *
10352  * `takeUntil` subscribes and begins mirroring the source Observable. It also
10353  * monitors a second Observable, `notifier` that you provide. If the `notifier`
10354  * emits a value, the output Observable stops mirroring the source Observable
10355  * and completes.
10356  *
10357  * @example <caption>Tick every second until the first click happens</caption>
10358  * var interval = Rx.Observable.interval(1000);
10359  * var clicks = Rx.Observable.fromEvent(document, 'click');
10360  * var result = interval.takeUntil(clicks);
10361  * result.subscribe(x => console.log(x));
10362  *
10363  * @see {@link take}
10364  * @see {@link takeLast}
10365  * @see {@link takeWhile}
10366  * @see {@link skip}
10367  *
10368  * @param {Observable} notifier The Observable whose first emitted value will
10369  * cause the output Observable of `takeUntil` to stop emitting values from the
10370  * source Observable.
10371  * @return {Observable<T>} An Observable that emits the values from the source
10372  * Observable until such time as `notifier` emits its first value.
10373  * @method takeUntil
10374  * @owner Observable
10375  */
10376 function takeUntil(notifier) {
10377     return takeUntil_1.takeUntil(notifier)(this);
10378 }
10379 exports.takeUntil = takeUntil;
10380
10381 },{"../operators/takeUntil":200}],153:[function(require,module,exports){
10382 "use strict";
10383 var takeWhile_1 = require('../operators/takeWhile');
10384 /**
10385  * Emits values emitted by the source Observable so long as each value satisfies
10386  * the given `predicate`, and then completes as soon as this `predicate` is not
10387  * satisfied.
10388  *
10389  * <span class="informal">Takes values from the source only while they pass the
10390  * condition given. When the first value does not satisfy, it completes.</span>
10391  *
10392  * <img src="./img/takeWhile.png" width="100%">
10393  *
10394  * `takeWhile` subscribes and begins mirroring the source Observable. Each value
10395  * emitted on the source is given to the `predicate` function which returns a
10396  * boolean, representing a condition to be satisfied by the source values. The
10397  * output Observable emits the source values until such time as the `predicate`
10398  * returns false, at which point `takeWhile` stops mirroring the source
10399  * Observable and completes the output Observable.
10400  *
10401  * @example <caption>Emit click events only while the clientX property is greater than 200</caption>
10402  * var clicks = Rx.Observable.fromEvent(document, 'click');
10403  * var result = clicks.takeWhile(ev => ev.clientX > 200);
10404  * result.subscribe(x => console.log(x));
10405  *
10406  * @see {@link take}
10407  * @see {@link takeLast}
10408  * @see {@link takeUntil}
10409  * @see {@link skip}
10410  *
10411  * @param {function(value: T, index: number): boolean} predicate A function that
10412  * evaluates a value emitted by the source Observable and returns a boolean.
10413  * Also takes the (zero-based) index as the second argument.
10414  * @return {Observable<T>} An Observable that emits the values from the source
10415  * Observable so long as each value satisfies the condition defined by the
10416  * `predicate`, then completes.
10417  * @method takeWhile
10418  * @owner Observable
10419  */
10420 function takeWhile(predicate) {
10421     return takeWhile_1.takeWhile(predicate)(this);
10422 }
10423 exports.takeWhile = takeWhile;
10424
10425 },{"../operators/takeWhile":201}],154:[function(require,module,exports){
10426 "use strict";
10427 var async_1 = require('../scheduler/async');
10428 var throttle_1 = require('../operators/throttle');
10429 var throttleTime_1 = require('../operators/throttleTime');
10430 /**
10431  * Emits a value from the source Observable, then ignores subsequent source
10432  * values for `duration` milliseconds, then repeats this process.
10433  *
10434  * <span class="informal">Lets a value pass, then ignores source values for the
10435  * next `duration` milliseconds.</span>
10436  *
10437  * <img src="./img/throttleTime.png" width="100%">
10438  *
10439  * `throttleTime` emits the source Observable values on the output Observable
10440  * when its internal timer is disabled, and ignores source values when the timer
10441  * is enabled. Initially, the timer is disabled. As soon as the first source
10442  * value arrives, it is forwarded to the output Observable, and then the timer
10443  * is enabled. After `duration` milliseconds (or the time unit determined
10444  * internally by the optional `scheduler`) has passed, the timer is disabled,
10445  * and this process repeats for the next source value. Optionally takes a
10446  * {@link IScheduler} for managing timers.
10447  *
10448  * @example <caption>Emit clicks at a rate of at most one click per second</caption>
10449  * var clicks = Rx.Observable.fromEvent(document, 'click');
10450  * var result = clicks.throttleTime(1000);
10451  * result.subscribe(x => console.log(x));
10452  *
10453  * @see {@link auditTime}
10454  * @see {@link debounceTime}
10455  * @see {@link delay}
10456  * @see {@link sampleTime}
10457  * @see {@link throttle}
10458  *
10459  * @param {number} duration Time to wait before emitting another value after
10460  * emitting the last value, measured in milliseconds or the time unit determined
10461  * internally by the optional `scheduler`.
10462  * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
10463  * managing the timers that handle the throttling.
10464  * @return {Observable<T>} An Observable that performs the throttle operation to
10465  * limit the rate of emissions from the source.
10466  * @method throttleTime
10467  * @owner Observable
10468  */
10469 function throttleTime(duration, scheduler, config) {
10470     if (scheduler === void 0) { scheduler = async_1.async; }
10471     if (config === void 0) { config = throttle_1.defaultThrottleConfig; }
10472     return throttleTime_1.throttleTime(duration, scheduler, config)(this);
10473 }
10474 exports.throttleTime = throttleTime;
10475
10476 },{"../operators/throttle":203,"../operators/throttleTime":204,"../scheduler/async":213}],155:[function(require,module,exports){
10477 "use strict";
10478 var async_1 = require('../scheduler/async');
10479 var timeout_1 = require('../operators/timeout');
10480 /**
10481  *
10482  * Errors if Observable does not emit a value in given time span.
10483  *
10484  * <span class="informal">Timeouts on Observable that doesn't emit values fast enough.</span>
10485  *
10486  * <img src="./img/timeout.png" width="100%">
10487  *
10488  * `timeout` operator accepts as an argument either a number or a Date.
10489  *
10490  * If number was provided, it returns an Observable that behaves like a source
10491  * Observable, unless there is a period of time where there is no value emitted.
10492  * So if you provide `100` as argument and first value comes after 50ms from
10493  * the moment of subscription, this value will be simply re-emitted by the resulting
10494  * Observable. If however after that 100ms passes without a second value being emitted,
10495  * stream will end with an error and source Observable will be unsubscribed.
10496  * These checks are performed throughout whole lifecycle of Observable - from the moment
10497  * it was subscribed to, until it completes or errors itself. Thus every value must be
10498  * emitted within specified period since previous value.
10499  *
10500  * If provided argument was Date, returned Observable behaves differently. It throws
10501  * if Observable did not complete before provided Date. This means that periods between
10502  * emission of particular values do not matter in this case. If Observable did not complete
10503  * before provided Date, source Observable will be unsubscribed. Other than that, resulting
10504  * stream behaves just as source Observable.
10505  *
10506  * `timeout` accepts also a Scheduler as a second parameter. It is used to schedule moment (or moments)
10507  * when returned Observable will check if source stream emitted value or completed.
10508  *
10509  * @example <caption>Check if ticks are emitted within certain timespan</caption>
10510  * const seconds = Rx.Observable.interval(1000);
10511  *
10512  * seconds.timeout(1100) // Let's use bigger timespan to be safe,
10513  *                       // since `interval` might fire a bit later then scheduled.
10514  * .subscribe(
10515  *     value => console.log(value), // Will emit numbers just as regular `interval` would.
10516  *     err => console.log(err) // Will never be called.
10517  * );
10518  *
10519  * seconds.timeout(900).subscribe(
10520  *     value => console.log(value), // Will never be called.
10521  *     err => console.log(err) // Will emit error before even first value is emitted,
10522  *                             // since it did not arrive within 900ms period.
10523  * );
10524  *
10525  * @example <caption>Use Date to check if Observable completed</caption>
10526  * const seconds = Rx.Observable.interval(1000);
10527  *
10528  * seconds.timeout(new Date("December 17, 2020 03:24:00"))
10529  * .subscribe(
10530  *     value => console.log(value), // Will emit values as regular `interval` would
10531  *                                  // until December 17, 2020 at 03:24:00.
10532  *     err => console.log(err) // On December 17, 2020 at 03:24:00 it will emit an error,
10533  *                             // since Observable did not complete by then.
10534  * );
10535  *
10536  * @see {@link timeoutWith}
10537  *
10538  * @param {number|Date} due Number specifying period within which Observable must emit values
10539  *                          or Date specifying before when Observable should complete
10540  * @param {Scheduler} [scheduler] Scheduler controlling when timeout checks occur.
10541  * @return {Observable<T>} Observable that mirrors behaviour of source, unless timeout checks fail.
10542  * @method timeout
10543  * @owner Observable
10544  */
10545 function timeout(due, scheduler) {
10546     if (scheduler === void 0) { scheduler = async_1.async; }
10547     return timeout_1.timeout(due, scheduler)(this);
10548 }
10549 exports.timeout = timeout;
10550
10551 },{"../operators/timeout":205,"../scheduler/async":213}],156:[function(require,module,exports){
10552 "use strict";
10553 var withLatestFrom_1 = require('../operators/withLatestFrom');
10554 /* tslint:enable:max-line-length */
10555 /**
10556  * Combines the source Observable with other Observables to create an Observable
10557  * whose values are calculated from the latest values of each, only when the
10558  * source emits.
10559  *
10560  * <span class="informal">Whenever the source Observable emits a value, it
10561  * computes a formula using that value plus the latest values from other input
10562  * Observables, then emits the output of that formula.</span>
10563  *
10564  * <img src="./img/withLatestFrom.png" width="100%">
10565  *
10566  * `withLatestFrom` combines each value from the source Observable (the
10567  * instance) with the latest values from the other input Observables only when
10568  * the source emits a value, optionally using a `project` function to determine
10569  * the value to be emitted on the output Observable. All input Observables must
10570  * emit at least one value before the output Observable will emit a value.
10571  *
10572  * @example <caption>On every click event, emit an array with the latest timer event plus the click event</caption>
10573  * var clicks = Rx.Observable.fromEvent(document, 'click');
10574  * var timer = Rx.Observable.interval(1000);
10575  * var result = clicks.withLatestFrom(timer);
10576  * result.subscribe(x => console.log(x));
10577  *
10578  * @see {@link combineLatest}
10579  *
10580  * @param {ObservableInput} other An input Observable to combine with the source
10581  * Observable. More than one input Observables may be given as argument.
10582  * @param {Function} [project] Projection function for combining values
10583  * together. Receives all values in order of the Observables passed, where the
10584  * first parameter is a value from the source Observable. (e.g.
10585  * `a.withLatestFrom(b, c, (a1, b1, c1) => a1 + b1 + c1)`). If this is not
10586  * passed, arrays will be emitted on the output Observable.
10587  * @return {Observable} An Observable of projected values from the most recent
10588  * values from each input Observable, or an array of the most recent values from
10589  * each input Observable.
10590  * @method withLatestFrom
10591  * @owner Observable
10592  */
10593 function withLatestFrom() {
10594     var args = [];
10595     for (var _i = 0; _i < arguments.length; _i++) {
10596         args[_i - 0] = arguments[_i];
10597     }
10598     return withLatestFrom_1.withLatestFrom.apply(void 0, args)(this);
10599 }
10600 exports.withLatestFrom = withLatestFrom;
10601
10602 },{"../operators/withLatestFrom":206}],157:[function(require,module,exports){
10603 "use strict";
10604 var zip_1 = require('../operators/zip');
10605 /* tslint:enable:max-line-length */
10606 /**
10607  * @param observables
10608  * @return {Observable<R>}
10609  * @method zip
10610  * @owner Observable
10611  */
10612 function zipProto() {
10613     var observables = [];
10614     for (var _i = 0; _i < arguments.length; _i++) {
10615         observables[_i - 0] = arguments[_i];
10616     }
10617     return zip_1.zip.apply(void 0, observables)(this);
10618 }
10619 exports.zipProto = zipProto;
10620
10621 },{"../operators/zip":207}],158:[function(require,module,exports){
10622 "use strict";
10623 var __extends = (this && this.__extends) || function (d, b) {
10624     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10625     function __() { this.constructor = d; }
10626     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10627 };
10628 var tryCatch_1 = require('../util/tryCatch');
10629 var errorObject_1 = require('../util/errorObject');
10630 var OuterSubscriber_1 = require('../OuterSubscriber');
10631 var subscribeToResult_1 = require('../util/subscribeToResult');
10632 /**
10633  * Ignores source values for a duration determined by another Observable, then
10634  * emits the most recent value from the source Observable, then repeats this
10635  * process.
10636  *
10637  * <span class="informal">It's like {@link auditTime}, but the silencing
10638  * duration is determined by a second Observable.</span>
10639  *
10640  * <img src="./img/audit.png" width="100%">
10641  *
10642  * `audit` is similar to `throttle`, but emits the last value from the silenced
10643  * time window, instead of the first value. `audit` emits the most recent value
10644  * from the source Observable on the output Observable as soon as its internal
10645  * timer becomes disabled, and ignores source values while the timer is enabled.
10646  * Initially, the timer is disabled. As soon as the first source value arrives,
10647  * the timer is enabled by calling the `durationSelector` function with the
10648  * source value, which returns the "duration" Observable. When the duration
10649  * Observable emits a value or completes, the timer is disabled, then the most
10650  * recent source value is emitted on the output Observable, and this process
10651  * repeats for the next source value.
10652  *
10653  * @example <caption>Emit clicks at a rate of at most one click per second</caption>
10654  * var clicks = Rx.Observable.fromEvent(document, 'click');
10655  * var result = clicks.audit(ev => Rx.Observable.interval(1000));
10656  * result.subscribe(x => console.log(x));
10657  *
10658  * @see {@link auditTime}
10659  * @see {@link debounce}
10660  * @see {@link delayWhen}
10661  * @see {@link sample}
10662  * @see {@link throttle}
10663  *
10664  * @param {function(value: T): SubscribableOrPromise} durationSelector A function
10665  * that receives a value from the source Observable, for computing the silencing
10666  * duration, returned as an Observable or a Promise.
10667  * @return {Observable<T>} An Observable that performs rate-limiting of
10668  * emissions from the source Observable.
10669  * @method audit
10670  * @owner Observable
10671  */
10672 function audit(durationSelector) {
10673     return function auditOperatorFunction(source) {
10674         return source.lift(new AuditOperator(durationSelector));
10675     };
10676 }
10677 exports.audit = audit;
10678 var AuditOperator = (function () {
10679     function AuditOperator(durationSelector) {
10680         this.durationSelector = durationSelector;
10681     }
10682     AuditOperator.prototype.call = function (subscriber, source) {
10683         return source.subscribe(new AuditSubscriber(subscriber, this.durationSelector));
10684     };
10685     return AuditOperator;
10686 }());
10687 /**
10688  * We need this JSDoc comment for affecting ESDoc.
10689  * @ignore
10690  * @extends {Ignored}
10691  */
10692 var AuditSubscriber = (function (_super) {
10693     __extends(AuditSubscriber, _super);
10694     function AuditSubscriber(destination, durationSelector) {
10695         _super.call(this, destination);
10696         this.durationSelector = durationSelector;
10697         this.hasValue = false;
10698     }
10699     AuditSubscriber.prototype._next = function (value) {
10700         this.value = value;
10701         this.hasValue = true;
10702         if (!this.throttled) {
10703             var duration = tryCatch_1.tryCatch(this.durationSelector)(value);
10704             if (duration === errorObject_1.errorObject) {
10705                 this.destination.error(errorObject_1.errorObject.e);
10706             }
10707             else {
10708                 var innerSubscription = subscribeToResult_1.subscribeToResult(this, duration);
10709                 if (innerSubscription.closed) {
10710                     this.clearThrottle();
10711                 }
10712                 else {
10713                     this.add(this.throttled = innerSubscription);
10714                 }
10715             }
10716         }
10717     };
10718     AuditSubscriber.prototype.clearThrottle = function () {
10719         var _a = this, value = _a.value, hasValue = _a.hasValue, throttled = _a.throttled;
10720         if (throttled) {
10721             this.remove(throttled);
10722             this.throttled = null;
10723             throttled.unsubscribe();
10724         }
10725         if (hasValue) {
10726             this.value = null;
10727             this.hasValue = false;
10728             this.destination.next(value);
10729         }
10730     };
10731     AuditSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex) {
10732         this.clearThrottle();
10733     };
10734     AuditSubscriber.prototype.notifyComplete = function () {
10735         this.clearThrottle();
10736     };
10737     return AuditSubscriber;
10738 }(OuterSubscriber_1.OuterSubscriber));
10739
10740 },{"../OuterSubscriber":31,"../util/errorObject":225,"../util/subscribeToResult":238,"../util/tryCatch":240}],159:[function(require,module,exports){
10741 "use strict";
10742 var async_1 = require('../scheduler/async');
10743 var audit_1 = require('./audit');
10744 var timer_1 = require('../observable/timer');
10745 /**
10746  * Ignores source values for `duration` milliseconds, then emits the most recent
10747  * value from the source Observable, then repeats this process.
10748  *
10749  * <span class="informal">When it sees a source values, it ignores that plus
10750  * the next ones for `duration` milliseconds, and then it emits the most recent
10751  * value from the source.</span>
10752  *
10753  * <img src="./img/auditTime.png" width="100%">
10754  *
10755  * `auditTime` is similar to `throttleTime`, but emits the last value from the
10756  * silenced time window, instead of the first value. `auditTime` emits the most
10757  * recent value from the source Observable on the output Observable as soon as
10758  * its internal timer becomes disabled, and ignores source values while the
10759  * timer is enabled. Initially, the timer is disabled. As soon as the first
10760  * source value arrives, the timer is enabled. After `duration` milliseconds (or
10761  * the time unit determined internally by the optional `scheduler`) has passed,
10762  * the timer is disabled, then the most recent source value is emitted on the
10763  * output Observable, and this process repeats for the next source value.
10764  * Optionally takes a {@link IScheduler} for managing timers.
10765  *
10766  * @example <caption>Emit clicks at a rate of at most one click per second</caption>
10767  * var clicks = Rx.Observable.fromEvent(document, 'click');
10768  * var result = clicks.auditTime(1000);
10769  * result.subscribe(x => console.log(x));
10770  *
10771  * @see {@link audit}
10772  * @see {@link debounceTime}
10773  * @see {@link delay}
10774  * @see {@link sampleTime}
10775  * @see {@link throttleTime}
10776  *
10777  * @param {number} duration Time to wait before emitting the most recent source
10778  * value, measured in milliseconds or the time unit determined internally
10779  * by the optional `scheduler`.
10780  * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
10781  * managing the timers that handle the rate-limiting behavior.
10782  * @return {Observable<T>} An Observable that performs rate-limiting of
10783  * emissions from the source Observable.
10784  * @method auditTime
10785  * @owner Observable
10786  */
10787 function auditTime(duration, scheduler) {
10788     if (scheduler === void 0) { scheduler = async_1.async; }
10789     return audit_1.audit(function () { return timer_1.timer(duration, scheduler); });
10790 }
10791 exports.auditTime = auditTime;
10792
10793 },{"../observable/timer":114,"../scheduler/async":213,"./audit":158}],160:[function(require,module,exports){
10794 "use strict";
10795 var __extends = (this && this.__extends) || function (d, b) {
10796     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10797     function __() { this.constructor = d; }
10798     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10799 };
10800 var OuterSubscriber_1 = require('../OuterSubscriber');
10801 var subscribeToResult_1 = require('../util/subscribeToResult');
10802 /**
10803  * Buffers the source Observable values until `closingNotifier` emits.
10804  *
10805  * <span class="informal">Collects values from the past as an array, and emits
10806  * that array only when another Observable emits.</span>
10807  *
10808  * <img src="./img/buffer.png" width="100%">
10809  *
10810  * Buffers the incoming Observable values until the given `closingNotifier`
10811  * Observable emits a value, at which point it emits the buffer on the output
10812  * Observable and starts a new buffer internally, awaiting the next time
10813  * `closingNotifier` emits.
10814  *
10815  * @example <caption>On every click, emit array of most recent interval events</caption>
10816  * var clicks = Rx.Observable.fromEvent(document, 'click');
10817  * var interval = Rx.Observable.interval(1000);
10818  * var buffered = interval.buffer(clicks);
10819  * buffered.subscribe(x => console.log(x));
10820  *
10821  * @see {@link bufferCount}
10822  * @see {@link bufferTime}
10823  * @see {@link bufferToggle}
10824  * @see {@link bufferWhen}
10825  * @see {@link window}
10826  *
10827  * @param {Observable<any>} closingNotifier An Observable that signals the
10828  * buffer to be emitted on the output Observable.
10829  * @return {Observable<T[]>} An Observable of buffers, which are arrays of
10830  * values.
10831  * @method buffer
10832  * @owner Observable
10833  */
10834 function buffer(closingNotifier) {
10835     return function bufferOperatorFunction(source) {
10836         return source.lift(new BufferOperator(closingNotifier));
10837     };
10838 }
10839 exports.buffer = buffer;
10840 var BufferOperator = (function () {
10841     function BufferOperator(closingNotifier) {
10842         this.closingNotifier = closingNotifier;
10843     }
10844     BufferOperator.prototype.call = function (subscriber, source) {
10845         return source.subscribe(new BufferSubscriber(subscriber, this.closingNotifier));
10846     };
10847     return BufferOperator;
10848 }());
10849 /**
10850  * We need this JSDoc comment for affecting ESDoc.
10851  * @ignore
10852  * @extends {Ignored}
10853  */
10854 var BufferSubscriber = (function (_super) {
10855     __extends(BufferSubscriber, _super);
10856     function BufferSubscriber(destination, closingNotifier) {
10857         _super.call(this, destination);
10858         this.buffer = [];
10859         this.add(subscribeToResult_1.subscribeToResult(this, closingNotifier));
10860     }
10861     BufferSubscriber.prototype._next = function (value) {
10862         this.buffer.push(value);
10863     };
10864     BufferSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
10865         var buffer = this.buffer;
10866         this.buffer = [];
10867         this.destination.next(buffer);
10868     };
10869     return BufferSubscriber;
10870 }(OuterSubscriber_1.OuterSubscriber));
10871
10872 },{"../OuterSubscriber":31,"../util/subscribeToResult":238}],161:[function(require,module,exports){
10873 "use strict";
10874 var __extends = (this && this.__extends) || function (d, b) {
10875     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
10876     function __() { this.constructor = d; }
10877     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10878 };
10879 var Subscriber_1 = require('../Subscriber');
10880 /**
10881  * Buffers the source Observable values until the size hits the maximum
10882  * `bufferSize` given.
10883  *
10884  * <span class="informal">Collects values from the past as an array, and emits
10885  * that array only when its size reaches `bufferSize`.</span>
10886  *
10887  * <img src="./img/bufferCount.png" width="100%">
10888  *
10889  * Buffers a number of values from the source Observable by `bufferSize` then
10890  * emits the buffer and clears it, and starts a new buffer each
10891  * `startBufferEvery` values. If `startBufferEvery` is not provided or is
10892  * `null`, then new buffers are started immediately at the start of the source
10893  * and when each buffer closes and is emitted.
10894  *
10895  * @example <caption>Emit the last two click events as an array</caption>
10896  * var clicks = Rx.Observable.fromEvent(document, 'click');
10897  * var buffered = clicks.bufferCount(2);
10898  * buffered.subscribe(x => console.log(x));
10899  *
10900  * @example <caption>On every click, emit the last two click events as an array</caption>
10901  * var clicks = Rx.Observable.fromEvent(document, 'click');
10902  * var buffered = clicks.bufferCount(2, 1);
10903  * buffered.subscribe(x => console.log(x));
10904  *
10905  * @see {@link buffer}
10906  * @see {@link bufferTime}
10907  * @see {@link bufferToggle}
10908  * @see {@link bufferWhen}
10909  * @see {@link pairwise}
10910  * @see {@link windowCount}
10911  *
10912  * @param {number} bufferSize The maximum size of the buffer emitted.
10913  * @param {number} [startBufferEvery] Interval at which to start a new buffer.
10914  * For example if `startBufferEvery` is `2`, then a new buffer will be started
10915  * on every other value from the source. A new buffer is started at the
10916  * beginning of the source by default.
10917  * @return {Observable<T[]>} An Observable of arrays of buffered values.
10918  * @method bufferCount
10919  * @owner Observable
10920  */
10921 function bufferCount(bufferSize, startBufferEvery) {
10922     if (startBufferEvery === void 0) { startBufferEvery = null; }
10923     return function bufferCountOperatorFunction(source) {
10924         return source.lift(new BufferCountOperator(bufferSize, startBufferEvery));
10925     };
10926 }
10927 exports.bufferCount = bufferCount;
10928 var BufferCountOperator = (function () {
10929     function BufferCountOperator(bufferSize, startBufferEvery) {
10930         this.bufferSize = bufferSize;
10931         this.startBufferEvery = startBufferEvery;
10932         if (!startBufferEvery || bufferSize === startBufferEvery) {
10933             this.subscriberClass = BufferCountSubscriber;
10934         }
10935         else {
10936             this.subscriberClass = BufferSkipCountSubscriber;
10937         }
10938     }
10939     BufferCountOperator.prototype.call = function (subscriber, source) {
10940         return source.subscribe(new this.subscriberClass(subscriber, this.bufferSize, this.startBufferEvery));
10941     };
10942     return BufferCountOperator;
10943 }());
10944 /**
10945  * We need this JSDoc comment for affecting ESDoc.
10946  * @ignore
10947  * @extends {Ignored}
10948  */
10949 var BufferCountSubscriber = (function (_super) {
10950     __extends(BufferCountSubscriber, _super);
10951     function BufferCountSubscriber(destination, bufferSize) {
10952         _super.call(this, destination);
10953         this.bufferSize = bufferSize;
10954         this.buffer = [];
10955     }
10956     BufferCountSubscriber.prototype._next = function (value) {
10957         var buffer = this.buffer;
10958         buffer.push(value);
10959         if (buffer.length == this.bufferSize) {
10960             this.destination.next(buffer);
10961             this.buffer = [];
10962         }
10963     };
10964     BufferCountSubscriber.prototype._complete = function () {
10965         var buffer = this.buffer;
10966         if (buffer.length > 0) {
10967             this.destination.next(buffer);
10968         }
10969         _super.prototype._complete.call(this);
10970     };
10971     return BufferCountSubscriber;
10972 }(Subscriber_1.Subscriber));
10973 /**
10974  * We need this JSDoc comment for affecting ESDoc.
10975  * @ignore
10976  * @extends {Ignored}
10977  */
10978 var BufferSkipCountSubscriber = (function (_super) {
10979     __extends(BufferSkipCountSubscriber, _super);
10980     function BufferSkipCountSubscriber(destination, bufferSize, startBufferEvery) {
10981         _super.call(this, destination);
10982         this.bufferSize = bufferSize;
10983         this.startBufferEvery = startBufferEvery;
10984         this.buffers = [];
10985         this.count = 0;
10986     }
10987     BufferSkipCountSubscriber.prototype._next = function (value) {
10988         var _a = this, bufferSize = _a.bufferSize, startBufferEvery = _a.startBufferEvery, buffers = _a.buffers, count = _a.count;
10989         this.count++;
10990         if (count % startBufferEvery === 0) {
10991             buffers.push([]);
10992         }
10993         for (var i = buffers.length; i--;) {
10994             var buffer = buffers[i];
10995             buffer.push(value);
10996             if (buffer.length === bufferSize) {
10997                 buffers.splice(i, 1);
10998                 this.destination.next(buffer);
10999             }
11000         }
11001     };
11002     BufferSkipCountSubscriber.prototype._complete = function () {
11003         var _a = this, buffers = _a.buffers, destination = _a.destination;
11004         while (buffers.length > 0) {
11005             var buffer = buffers.shift();
11006             if (buffer.length > 0) {
11007                 destination.next(buffer);
11008             }
11009         }
11010         _super.prototype._complete.call(this);
11011     };
11012     return BufferSkipCountSubscriber;
11013 }(Subscriber_1.Subscriber));
11014
11015 },{"../Subscriber":36}],162:[function(require,module,exports){
11016 "use strict";
11017 var __extends = (this && this.__extends) || function (d, b) {
11018     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11019     function __() { this.constructor = d; }
11020     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11021 };
11022 var Subscription_1 = require('../Subscription');
11023 var tryCatch_1 = require('../util/tryCatch');
11024 var errorObject_1 = require('../util/errorObject');
11025 var OuterSubscriber_1 = require('../OuterSubscriber');
11026 var subscribeToResult_1 = require('../util/subscribeToResult');
11027 /**
11028  * Buffers the source Observable values, using a factory function of closing
11029  * Observables to determine when to close, emit, and reset the buffer.
11030  *
11031  * <span class="informal">Collects values from the past as an array. When it
11032  * starts collecting values, it calls a function that returns an Observable that
11033  * tells when to close the buffer and restart collecting.</span>
11034  *
11035  * <img src="./img/bufferWhen.png" width="100%">
11036  *
11037  * Opens a buffer immediately, then closes the buffer when the observable
11038  * returned by calling `closingSelector` function emits a value. When it closes
11039  * the buffer, it immediately opens a new buffer and repeats the process.
11040  *
11041  * @example <caption>Emit an array of the last clicks every [1-5] random seconds</caption>
11042  * var clicks = Rx.Observable.fromEvent(document, 'click');
11043  * var buffered = clicks.bufferWhen(() =>
11044  *   Rx.Observable.interval(1000 + Math.random() * 4000)
11045  * );
11046  * buffered.subscribe(x => console.log(x));
11047  *
11048  * @see {@link buffer}
11049  * @see {@link bufferCount}
11050  * @see {@link bufferTime}
11051  * @see {@link bufferToggle}
11052  * @see {@link windowWhen}
11053  *
11054  * @param {function(): Observable} closingSelector A function that takes no
11055  * arguments and returns an Observable that signals buffer closure.
11056  * @return {Observable<T[]>} An observable of arrays of buffered values.
11057  * @method bufferWhen
11058  * @owner Observable
11059  */
11060 function bufferWhen(closingSelector) {
11061     return function (source) {
11062         return source.lift(new BufferWhenOperator(closingSelector));
11063     };
11064 }
11065 exports.bufferWhen = bufferWhen;
11066 var BufferWhenOperator = (function () {
11067     function BufferWhenOperator(closingSelector) {
11068         this.closingSelector = closingSelector;
11069     }
11070     BufferWhenOperator.prototype.call = function (subscriber, source) {
11071         return source.subscribe(new BufferWhenSubscriber(subscriber, this.closingSelector));
11072     };
11073     return BufferWhenOperator;
11074 }());
11075 /**
11076  * We need this JSDoc comment for affecting ESDoc.
11077  * @ignore
11078  * @extends {Ignored}
11079  */
11080 var BufferWhenSubscriber = (function (_super) {
11081     __extends(BufferWhenSubscriber, _super);
11082     function BufferWhenSubscriber(destination, closingSelector) {
11083         _super.call(this, destination);
11084         this.closingSelector = closingSelector;
11085         this.subscribing = false;
11086         this.openBuffer();
11087     }
11088     BufferWhenSubscriber.prototype._next = function (value) {
11089         this.buffer.push(value);
11090     };
11091     BufferWhenSubscriber.prototype._complete = function () {
11092         var buffer = this.buffer;
11093         if (buffer) {
11094             this.destination.next(buffer);
11095         }
11096         _super.prototype._complete.call(this);
11097     };
11098     BufferWhenSubscriber.prototype._unsubscribe = function () {
11099         this.buffer = null;
11100         this.subscribing = false;
11101     };
11102     BufferWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11103         this.openBuffer();
11104     };
11105     BufferWhenSubscriber.prototype.notifyComplete = function () {
11106         if (this.subscribing) {
11107             this.complete();
11108         }
11109         else {
11110             this.openBuffer();
11111         }
11112     };
11113     BufferWhenSubscriber.prototype.openBuffer = function () {
11114         var closingSubscription = this.closingSubscription;
11115         if (closingSubscription) {
11116             this.remove(closingSubscription);
11117             closingSubscription.unsubscribe();
11118         }
11119         var buffer = this.buffer;
11120         if (this.buffer) {
11121             this.destination.next(buffer);
11122         }
11123         this.buffer = [];
11124         var closingNotifier = tryCatch_1.tryCatch(this.closingSelector)();
11125         if (closingNotifier === errorObject_1.errorObject) {
11126             this.error(errorObject_1.errorObject.e);
11127         }
11128         else {
11129             closingSubscription = new Subscription_1.Subscription();
11130             this.closingSubscription = closingSubscription;
11131             this.add(closingSubscription);
11132             this.subscribing = true;
11133             closingSubscription.add(subscribeToResult_1.subscribeToResult(this, closingNotifier));
11134             this.subscribing = false;
11135         }
11136     };
11137     return BufferWhenSubscriber;
11138 }(OuterSubscriber_1.OuterSubscriber));
11139
11140 },{"../OuterSubscriber":31,"../Subscription":37,"../util/errorObject":225,"../util/subscribeToResult":238,"../util/tryCatch":240}],163:[function(require,module,exports){
11141 "use strict";
11142 var __extends = (this && this.__extends) || function (d, b) {
11143     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11144     function __() { this.constructor = d; }
11145     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11146 };
11147 var OuterSubscriber_1 = require('../OuterSubscriber');
11148 var subscribeToResult_1 = require('../util/subscribeToResult');
11149 /**
11150  * Catches errors on the observable to be handled by returning a new observable or throwing an error.
11151  *
11152  * <img src="./img/catch.png" width="100%">
11153  *
11154  * @example <caption>Continues with a different Observable when there's an error</caption>
11155  *
11156  * Observable.of(1, 2, 3, 4, 5)
11157  *   .map(n => {
11158  *         if (n == 4) {
11159  *           throw 'four!';
11160  *     }
11161  *         return n;
11162  *   })
11163  *   .catch(err => Observable.of('I', 'II', 'III', 'IV', 'V'))
11164  *   .subscribe(x => console.log(x));
11165  *   // 1, 2, 3, I, II, III, IV, V
11166  *
11167  * @example <caption>Retries the caught source Observable again in case of error, similar to retry() operator</caption>
11168  *
11169  * Observable.of(1, 2, 3, 4, 5)
11170  *   .map(n => {
11171  *         if (n === 4) {
11172  *           throw 'four!';
11173  *     }
11174  *         return n;
11175  *   })
11176  *   .catch((err, caught) => caught)
11177  *   .take(30)
11178  *   .subscribe(x => console.log(x));
11179  *   // 1, 2, 3, 1, 2, 3, ...
11180  *
11181  * @example <caption>Throws a new error when the source Observable throws an error</caption>
11182  *
11183  * Observable.of(1, 2, 3, 4, 5)
11184  *   .map(n => {
11185  *     if (n == 4) {
11186  *       throw 'four!';
11187  *     }
11188  *     return n;
11189  *   })
11190  *   .catch(err => {
11191  *     throw 'error in source. Details: ' + err;
11192  *   })
11193  *   .subscribe(
11194  *     x => console.log(x),
11195  *     err => console.log(err)
11196  *   );
11197  *   // 1, 2, 3, error in source. Details: four!
11198  *
11199  * @param {function} selector a function that takes as arguments `err`, which is the error, and `caught`, which
11200  *  is the source observable, in case you'd like to "retry" that observable by returning it again. Whatever observable
11201  *  is returned by the `selector` will be used to continue the observable chain.
11202  * @return {Observable} An observable that originates from either the source or the observable returned by the
11203  *  catch `selector` function.
11204  * @name catchError
11205  */
11206 function catchError(selector) {
11207     return function catchErrorOperatorFunction(source) {
11208         var operator = new CatchOperator(selector);
11209         var caught = source.lift(operator);
11210         return (operator.caught = caught);
11211     };
11212 }
11213 exports.catchError = catchError;
11214 var CatchOperator = (function () {
11215     function CatchOperator(selector) {
11216         this.selector = selector;
11217     }
11218     CatchOperator.prototype.call = function (subscriber, source) {
11219         return source.subscribe(new CatchSubscriber(subscriber, this.selector, this.caught));
11220     };
11221     return CatchOperator;
11222 }());
11223 /**
11224  * We need this JSDoc comment for affecting ESDoc.
11225  * @ignore
11226  * @extends {Ignored}
11227  */
11228 var CatchSubscriber = (function (_super) {
11229     __extends(CatchSubscriber, _super);
11230     function CatchSubscriber(destination, selector, caught) {
11231         _super.call(this, destination);
11232         this.selector = selector;
11233         this.caught = caught;
11234     }
11235     // NOTE: overriding `error` instead of `_error` because we don't want
11236     // to have this flag this subscriber as `isStopped`. We can mimic the
11237     // behavior of the RetrySubscriber (from the `retry` operator), where
11238     // we unsubscribe from our source chain, reset our Subscriber flags,
11239     // then subscribe to the selector result.
11240     CatchSubscriber.prototype.error = function (err) {
11241         if (!this.isStopped) {
11242             var result = void 0;
11243             try {
11244                 result = this.selector(err, this.caught);
11245             }
11246             catch (err2) {
11247                 _super.prototype.error.call(this, err2);
11248                 return;
11249             }
11250             this._unsubscribeAndRecycle();
11251             this.add(subscribeToResult_1.subscribeToResult(this, result));
11252         }
11253     };
11254     return CatchSubscriber;
11255 }(OuterSubscriber_1.OuterSubscriber));
11256
11257 },{"../OuterSubscriber":31,"../util/subscribeToResult":238}],164:[function(require,module,exports){
11258 "use strict";
11259 var __extends = (this && this.__extends) || function (d, b) {
11260     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11261     function __() { this.constructor = d; }
11262     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11263 };
11264 var ArrayObservable_1 = require('../observable/ArrayObservable');
11265 var isArray_1 = require('../util/isArray');
11266 var OuterSubscriber_1 = require('../OuterSubscriber');
11267 var subscribeToResult_1 = require('../util/subscribeToResult');
11268 var none = {};
11269 /* tslint:enable:max-line-length */
11270 /**
11271  * Combines multiple Observables to create an Observable whose values are
11272  * calculated from the latest values of each of its input Observables.
11273  *
11274  * <span class="informal">Whenever any input Observable emits a value, it
11275  * computes a formula using the latest values from all the inputs, then emits
11276  * the output of that formula.</span>
11277  *
11278  * <img src="./img/combineLatest.png" width="100%">
11279  *
11280  * `combineLatest` combines the values from this Observable with values from
11281  * Observables passed as arguments. This is done by subscribing to each
11282  * Observable, in order, and collecting an array of each of the most recent
11283  * values any time any of the input Observables emits, then either taking that
11284  * array and passing it as arguments to an optional `project` function and
11285  * emitting the return value of that, or just emitting the array of recent
11286  * values directly if there is no `project` function.
11287  *
11288  * @example <caption>Dynamically calculate the Body-Mass Index from an Observable of weight and one for height</caption>
11289  * var weight = Rx.Observable.of(70, 72, 76, 79, 75);
11290  * var height = Rx.Observable.of(1.76, 1.77, 1.78);
11291  * var bmi = weight.combineLatest(height, (w, h) => w / (h * h));
11292  * bmi.subscribe(x => console.log('BMI is ' + x));
11293  *
11294  * // With output to console:
11295  * // BMI is 24.212293388429753
11296  * // BMI is 23.93948099205209
11297  * // BMI is 23.671253629592222
11298  *
11299  * @see {@link combineAll}
11300  * @see {@link merge}
11301  * @see {@link withLatestFrom}
11302  *
11303  * @param {ObservableInput} other An input Observable to combine with the source
11304  * Observable. More than one input Observables may be given as argument.
11305  * @param {function} [project] An optional function to project the values from
11306  * the combined latest values into a new value on the output Observable.
11307  * @return {Observable} An Observable of projected values from the most recent
11308  * values from each input Observable, or an array of the most recent values from
11309  * each input Observable.
11310  * @method combineLatest
11311  * @owner Observable
11312  */
11313 function combineLatest() {
11314     var observables = [];
11315     for (var _i = 0; _i < arguments.length; _i++) {
11316         observables[_i - 0] = arguments[_i];
11317     }
11318     var project = null;
11319     if (typeof observables[observables.length - 1] === 'function') {
11320         project = observables.pop();
11321     }
11322     // if the first and only other argument besides the resultSelector is an array
11323     // assume it's been called with `combineLatest([obs1, obs2, obs3], project)`
11324     if (observables.length === 1 && isArray_1.isArray(observables[0])) {
11325         observables = observables[0].slice();
11326     }
11327     return function (source) { return source.lift.call(new ArrayObservable_1.ArrayObservable([source].concat(observables)), new CombineLatestOperator(project)); };
11328 }
11329 exports.combineLatest = combineLatest;
11330 var CombineLatestOperator = (function () {
11331     function CombineLatestOperator(project) {
11332         this.project = project;
11333     }
11334     CombineLatestOperator.prototype.call = function (subscriber, source) {
11335         return source.subscribe(new CombineLatestSubscriber(subscriber, this.project));
11336     };
11337     return CombineLatestOperator;
11338 }());
11339 exports.CombineLatestOperator = CombineLatestOperator;
11340 /**
11341  * We need this JSDoc comment for affecting ESDoc.
11342  * @ignore
11343  * @extends {Ignored}
11344  */
11345 var CombineLatestSubscriber = (function (_super) {
11346     __extends(CombineLatestSubscriber, _super);
11347     function CombineLatestSubscriber(destination, project) {
11348         _super.call(this, destination);
11349         this.project = project;
11350         this.active = 0;
11351         this.values = [];
11352         this.observables = [];
11353     }
11354     CombineLatestSubscriber.prototype._next = function (observable) {
11355         this.values.push(none);
11356         this.observables.push(observable);
11357     };
11358     CombineLatestSubscriber.prototype._complete = function () {
11359         var observables = this.observables;
11360         var len = observables.length;
11361         if (len === 0) {
11362             this.destination.complete();
11363         }
11364         else {
11365             this.active = len;
11366             this.toRespond = len;
11367             for (var i = 0; i < len; i++) {
11368                 var observable = observables[i];
11369                 this.add(subscribeToResult_1.subscribeToResult(this, observable, observable, i));
11370             }
11371         }
11372     };
11373     CombineLatestSubscriber.prototype.notifyComplete = function (unused) {
11374         if ((this.active -= 1) === 0) {
11375             this.destination.complete();
11376         }
11377     };
11378     CombineLatestSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11379         var values = this.values;
11380         var oldVal = values[outerIndex];
11381         var toRespond = !this.toRespond
11382             ? 0
11383             : oldVal === none ? --this.toRespond : this.toRespond;
11384         values[outerIndex] = innerValue;
11385         if (toRespond === 0) {
11386             if (this.project) {
11387                 this._tryProject(values);
11388             }
11389             else {
11390                 this.destination.next(values.slice());
11391             }
11392         }
11393     };
11394     CombineLatestSubscriber.prototype._tryProject = function (values) {
11395         var result;
11396         try {
11397             result = this.project.apply(this, values);
11398         }
11399         catch (err) {
11400             this.destination.error(err);
11401             return;
11402         }
11403         this.destination.next(result);
11404     };
11405     return CombineLatestSubscriber;
11406 }(OuterSubscriber_1.OuterSubscriber));
11407 exports.CombineLatestSubscriber = CombineLatestSubscriber;
11408
11409 },{"../OuterSubscriber":31,"../observable/ArrayObservable":93,"../util/isArray":227,"../util/subscribeToResult":238}],165:[function(require,module,exports){
11410 "use strict";
11411 var concat_1 = require('../observable/concat');
11412 /* tslint:enable:max-line-length */
11413 /**
11414  * Creates an output Observable which sequentially emits all values from every
11415  * given input Observable after the current Observable.
11416  *
11417  * <span class="informal">Concatenates multiple Observables together by
11418  * sequentially emitting their values, one Observable after the other.</span>
11419  *
11420  * <img src="./img/concat.png" width="100%">
11421  *
11422  * Joins this Observable with multiple other Observables by subscribing to them
11423  * one at a time, starting with the source, and merging their results into the
11424  * output Observable. Will wait for each Observable to complete before moving
11425  * on to the next.
11426  *
11427  * @example <caption>Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10</caption>
11428  * var timer = Rx.Observable.interval(1000).take(4);
11429  * var sequence = Rx.Observable.range(1, 10);
11430  * var result = timer.concat(sequence);
11431  * result.subscribe(x => console.log(x));
11432  *
11433  * // results in:
11434  * // 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10
11435  *
11436  * @example <caption>Concatenate 3 Observables</caption>
11437  * var timer1 = Rx.Observable.interval(1000).take(10);
11438  * var timer2 = Rx.Observable.interval(2000).take(6);
11439  * var timer3 = Rx.Observable.interval(500).take(10);
11440  * var result = timer1.concat(timer2, timer3);
11441  * result.subscribe(x => console.log(x));
11442  *
11443  * // results in the following:
11444  * // (Prints to console sequentially)
11445  * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9
11446  * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5
11447  * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9
11448  *
11449  * @see {@link concatAll}
11450  * @see {@link concatMap}
11451  * @see {@link concatMapTo}
11452  *
11453  * @param {ObservableInput} other An input Observable to concatenate after the source
11454  * Observable. More than one input Observables may be given as argument.
11455  * @param {Scheduler} [scheduler=null] An optional IScheduler to schedule each
11456  * Observable subscription on.
11457  * @return {Observable} All values of each passed Observable merged into a
11458  * single Observable, in order, in serial fashion.
11459  * @method concat
11460  * @owner Observable
11461  */
11462 function concat() {
11463     var observables = [];
11464     for (var _i = 0; _i < arguments.length; _i++) {
11465         observables[_i - 0] = arguments[_i];
11466     }
11467     return function (source) { return source.lift.call(concat_1.concat.apply(void 0, [source].concat(observables))); };
11468 }
11469 exports.concat = concat;
11470
11471 },{"../observable/concat":105}],166:[function(require,module,exports){
11472 "use strict";
11473 var mergeAll_1 = require('./mergeAll');
11474 /**
11475  * Converts a higher-order Observable into a first-order Observable by
11476  * concatenating the inner Observables in order.
11477  *
11478  * <span class="informal">Flattens an Observable-of-Observables by putting one
11479  * inner Observable after the other.</span>
11480  *
11481  * <img src="./img/concatAll.png" width="100%">
11482  *
11483  * Joins every Observable emitted by the source (a higher-order Observable), in
11484  * a serial fashion. It subscribes to each inner Observable only after the
11485  * previous inner Observable has completed, and merges all of their values into
11486  * the returned observable.
11487  *
11488  * __Warning:__ If the source Observable emits Observables quickly and
11489  * endlessly, and the inner Observables it emits generally complete slower than
11490  * the source emits, you can run into memory issues as the incoming Observables
11491  * collect in an unbounded buffer.
11492  *
11493  * Note: `concatAll` is equivalent to `mergeAll` with concurrency parameter set
11494  * to `1`.
11495  *
11496  * @example <caption>For each click event, tick every second from 0 to 3, with no concurrency</caption>
11497  * var clicks = Rx.Observable.fromEvent(document, 'click');
11498  * var higherOrder = clicks.map(ev => Rx.Observable.interval(1000).take(4));
11499  * var firstOrder = higherOrder.concatAll();
11500  * firstOrder.subscribe(x => console.log(x));
11501  *
11502  * // Results in the following:
11503  * // (results are not concurrent)
11504  * // For every click on the "document" it will emit values 0 to 3 spaced
11505  * // on a 1000ms interval
11506  * // one click = 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3
11507  *
11508  * @see {@link combineAll}
11509  * @see {@link concat}
11510  * @see {@link concatMap}
11511  * @see {@link concatMapTo}
11512  * @see {@link exhaust}
11513  * @see {@link mergeAll}
11514  * @see {@link switch}
11515  * @see {@link zipAll}
11516  *
11517  * @return {Observable} An Observable emitting values from all the inner
11518  * Observables concatenated.
11519  * @method concatAll
11520  * @owner Observable
11521  */
11522 function concatAll() {
11523     return mergeAll_1.mergeAll(1);
11524 }
11525 exports.concatAll = concatAll;
11526
11527 },{"./mergeAll":179}],167:[function(require,module,exports){
11528 "use strict";
11529 var __extends = (this && this.__extends) || function (d, b) {
11530     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11531     function __() { this.constructor = d; }
11532     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11533 };
11534 var Subscriber_1 = require('../Subscriber');
11535 var async_1 = require('../scheduler/async');
11536 /**
11537  * Emits a value from the source Observable only after a particular time span
11538  * has passed without another source emission.
11539  *
11540  * <span class="informal">It's like {@link delay}, but passes only the most
11541  * recent value from each burst of emissions.</span>
11542  *
11543  * <img src="./img/debounceTime.png" width="100%">
11544  *
11545  * `debounceTime` delays values emitted by the source Observable, but drops
11546  * previous pending delayed emissions if a new value arrives on the source
11547  * Observable. This operator keeps track of the most recent value from the
11548  * source Observable, and emits that only when `dueTime` enough time has passed
11549  * without any other value appearing on the source Observable. If a new value
11550  * appears before `dueTime` silence occurs, the previous value will be dropped
11551  * and will not be emitted on the output Observable.
11552  *
11553  * This is a rate-limiting operator, because it is impossible for more than one
11554  * value to be emitted in any time window of duration `dueTime`, but it is also
11555  * a delay-like operator since output emissions do not occur at the same time as
11556  * they did on the source Observable. Optionally takes a {@link IScheduler} for
11557  * managing timers.
11558  *
11559  * @example <caption>Emit the most recent click after a burst of clicks</caption>
11560  * var clicks = Rx.Observable.fromEvent(document, 'click');
11561  * var result = clicks.debounceTime(1000);
11562  * result.subscribe(x => console.log(x));
11563  *
11564  * @see {@link auditTime}
11565  * @see {@link debounce}
11566  * @see {@link delay}
11567  * @see {@link sampleTime}
11568  * @see {@link throttleTime}
11569  *
11570  * @param {number} dueTime The timeout duration in milliseconds (or the time
11571  * unit determined internally by the optional `scheduler`) for the window of
11572  * time required to wait for emission silence before emitting the most recent
11573  * source value.
11574  * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
11575  * managing the timers that handle the timeout for each value.
11576  * @return {Observable} An Observable that delays the emissions of the source
11577  * Observable by the specified `dueTime`, and may drop some values if they occur
11578  * too frequently.
11579  * @method debounceTime
11580  * @owner Observable
11581  */
11582 function debounceTime(dueTime, scheduler) {
11583     if (scheduler === void 0) { scheduler = async_1.async; }
11584     return function (source) { return source.lift(new DebounceTimeOperator(dueTime, scheduler)); };
11585 }
11586 exports.debounceTime = debounceTime;
11587 var DebounceTimeOperator = (function () {
11588     function DebounceTimeOperator(dueTime, scheduler) {
11589         this.dueTime = dueTime;
11590         this.scheduler = scheduler;
11591     }
11592     DebounceTimeOperator.prototype.call = function (subscriber, source) {
11593         return source.subscribe(new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler));
11594     };
11595     return DebounceTimeOperator;
11596 }());
11597 /**
11598  * We need this JSDoc comment for affecting ESDoc.
11599  * @ignore
11600  * @extends {Ignored}
11601  */
11602 var DebounceTimeSubscriber = (function (_super) {
11603     __extends(DebounceTimeSubscriber, _super);
11604     function DebounceTimeSubscriber(destination, dueTime, scheduler) {
11605         _super.call(this, destination);
11606         this.dueTime = dueTime;
11607         this.scheduler = scheduler;
11608         this.debouncedSubscription = null;
11609         this.lastValue = null;
11610         this.hasValue = false;
11611     }
11612     DebounceTimeSubscriber.prototype._next = function (value) {
11613         this.clearDebounce();
11614         this.lastValue = value;
11615         this.hasValue = true;
11616         this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext, this.dueTime, this));
11617     };
11618     DebounceTimeSubscriber.prototype._complete = function () {
11619         this.debouncedNext();
11620         this.destination.complete();
11621     };
11622     DebounceTimeSubscriber.prototype.debouncedNext = function () {
11623         this.clearDebounce();
11624         if (this.hasValue) {
11625             this.destination.next(this.lastValue);
11626             this.lastValue = null;
11627             this.hasValue = false;
11628         }
11629     };
11630     DebounceTimeSubscriber.prototype.clearDebounce = function () {
11631         var debouncedSubscription = this.debouncedSubscription;
11632         if (debouncedSubscription !== null) {
11633             this.remove(debouncedSubscription);
11634             debouncedSubscription.unsubscribe();
11635             this.debouncedSubscription = null;
11636         }
11637     };
11638     return DebounceTimeSubscriber;
11639 }(Subscriber_1.Subscriber));
11640 function dispatchNext(subscriber) {
11641     subscriber.debouncedNext();
11642 }
11643
11644 },{"../Subscriber":36,"../scheduler/async":213}],168:[function(require,module,exports){
11645 "use strict";
11646 var __extends = (this && this.__extends) || function (d, b) {
11647     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11648     function __() { this.constructor = d; }
11649     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11650 };
11651 var Subscriber_1 = require('../Subscriber');
11652 /* tslint:enable:max-line-length */
11653 /**
11654  * Emits a given value if the source Observable completes without emitting any
11655  * `next` value, otherwise mirrors the source Observable.
11656  *
11657  * <span class="informal">If the source Observable turns out to be empty, then
11658  * this operator will emit a default value.</span>
11659  *
11660  * <img src="./img/defaultIfEmpty.png" width="100%">
11661  *
11662  * `defaultIfEmpty` emits the values emitted by the source Observable or a
11663  * specified default value if the source Observable is empty (completes without
11664  * having emitted any `next` value).
11665  *
11666  * @example <caption>If no clicks happen in 5 seconds, then emit "no clicks"</caption>
11667  * var clicks = Rx.Observable.fromEvent(document, 'click');
11668  * var clicksBeforeFive = clicks.takeUntil(Rx.Observable.interval(5000));
11669  * var result = clicksBeforeFive.defaultIfEmpty('no clicks');
11670  * result.subscribe(x => console.log(x));
11671  *
11672  * @see {@link empty}
11673  * @see {@link last}
11674  *
11675  * @param {any} [defaultValue=null] The default value used if the source
11676  * Observable is empty.
11677  * @return {Observable} An Observable that emits either the specified
11678  * `defaultValue` if the source Observable emits no items, or the values emitted
11679  * by the source Observable.
11680  * @method defaultIfEmpty
11681  * @owner Observable
11682  */
11683 function defaultIfEmpty(defaultValue) {
11684     if (defaultValue === void 0) { defaultValue = null; }
11685     return function (source) { return source.lift(new DefaultIfEmptyOperator(defaultValue)); };
11686 }
11687 exports.defaultIfEmpty = defaultIfEmpty;
11688 var DefaultIfEmptyOperator = (function () {
11689     function DefaultIfEmptyOperator(defaultValue) {
11690         this.defaultValue = defaultValue;
11691     }
11692     DefaultIfEmptyOperator.prototype.call = function (subscriber, source) {
11693         return source.subscribe(new DefaultIfEmptySubscriber(subscriber, this.defaultValue));
11694     };
11695     return DefaultIfEmptyOperator;
11696 }());
11697 /**
11698  * We need this JSDoc comment for affecting ESDoc.
11699  * @ignore
11700  * @extends {Ignored}
11701  */
11702 var DefaultIfEmptySubscriber = (function (_super) {
11703     __extends(DefaultIfEmptySubscriber, _super);
11704     function DefaultIfEmptySubscriber(destination, defaultValue) {
11705         _super.call(this, destination);
11706         this.defaultValue = defaultValue;
11707         this.isEmpty = true;
11708     }
11709     DefaultIfEmptySubscriber.prototype._next = function (value) {
11710         this.isEmpty = false;
11711         this.destination.next(value);
11712     };
11713     DefaultIfEmptySubscriber.prototype._complete = function () {
11714         if (this.isEmpty) {
11715             this.destination.next(this.defaultValue);
11716         }
11717         this.destination.complete();
11718     };
11719     return DefaultIfEmptySubscriber;
11720 }(Subscriber_1.Subscriber));
11721
11722 },{"../Subscriber":36}],169:[function(require,module,exports){
11723 "use strict";
11724 var __extends = (this && this.__extends) || function (d, b) {
11725     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11726     function __() { this.constructor = d; }
11727     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11728 };
11729 var async_1 = require('../scheduler/async');
11730 var isDate_1 = require('../util/isDate');
11731 var Subscriber_1 = require('../Subscriber');
11732 var Notification_1 = require('../Notification');
11733 /**
11734  * Delays the emission of items from the source Observable by a given timeout or
11735  * until a given Date.
11736  *
11737  * <span class="informal">Time shifts each item by some specified amount of
11738  * milliseconds.</span>
11739  *
11740  * <img src="./img/delay.png" width="100%">
11741  *
11742  * If the delay argument is a Number, this operator time shifts the source
11743  * Observable by that amount of time expressed in milliseconds. The relative
11744  * time intervals between the values are preserved.
11745  *
11746  * If the delay argument is a Date, this operator time shifts the start of the
11747  * Observable execution until the given date occurs.
11748  *
11749  * @example <caption>Delay each click by one second</caption>
11750  * var clicks = Rx.Observable.fromEvent(document, 'click');
11751  * var delayedClicks = clicks.delay(1000); // each click emitted after 1 second
11752  * delayedClicks.subscribe(x => console.log(x));
11753  *
11754  * @example <caption>Delay all clicks until a future date happens</caption>
11755  * var clicks = Rx.Observable.fromEvent(document, 'click');
11756  * var date = new Date('March 15, 2050 12:00:00'); // in the future
11757  * var delayedClicks = clicks.delay(date); // click emitted only after that date
11758  * delayedClicks.subscribe(x => console.log(x));
11759  *
11760  * @see {@link debounceTime}
11761  * @see {@link delayWhen}
11762  *
11763  * @param {number|Date} delay The delay duration in milliseconds (a `number`) or
11764  * a `Date` until which the emission of the source items is delayed.
11765  * @param {Scheduler} [scheduler=async] The IScheduler to use for
11766  * managing the timers that handle the time-shift for each item.
11767  * @return {Observable} An Observable that delays the emissions of the source
11768  * Observable by the specified timeout or Date.
11769  * @method delay
11770  * @owner Observable
11771  */
11772 function delay(delay, scheduler) {
11773     if (scheduler === void 0) { scheduler = async_1.async; }
11774     var absoluteDelay = isDate_1.isDate(delay);
11775     var delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(delay);
11776     return function (source) { return source.lift(new DelayOperator(delayFor, scheduler)); };
11777 }
11778 exports.delay = delay;
11779 var DelayOperator = (function () {
11780     function DelayOperator(delay, scheduler) {
11781         this.delay = delay;
11782         this.scheduler = scheduler;
11783     }
11784     DelayOperator.prototype.call = function (subscriber, source) {
11785         return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler));
11786     };
11787     return DelayOperator;
11788 }());
11789 /**
11790  * We need this JSDoc comment for affecting ESDoc.
11791  * @ignore
11792  * @extends {Ignored}
11793  */
11794 var DelaySubscriber = (function (_super) {
11795     __extends(DelaySubscriber, _super);
11796     function DelaySubscriber(destination, delay, scheduler) {
11797         _super.call(this, destination);
11798         this.delay = delay;
11799         this.scheduler = scheduler;
11800         this.queue = [];
11801         this.active = false;
11802         this.errored = false;
11803     }
11804     DelaySubscriber.dispatch = function (state) {
11805         var source = state.source;
11806         var queue = source.queue;
11807         var scheduler = state.scheduler;
11808         var destination = state.destination;
11809         while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) {
11810             queue.shift().notification.observe(destination);
11811         }
11812         if (queue.length > 0) {
11813             var delay_1 = Math.max(0, queue[0].time - scheduler.now());
11814             this.schedule(state, delay_1);
11815         }
11816         else {
11817             source.active = false;
11818         }
11819     };
11820     DelaySubscriber.prototype._schedule = function (scheduler) {
11821         this.active = true;
11822         this.add(scheduler.schedule(DelaySubscriber.dispatch, this.delay, {
11823             source: this, destination: this.destination, scheduler: scheduler
11824         }));
11825     };
11826     DelaySubscriber.prototype.scheduleNotification = function (notification) {
11827         if (this.errored === true) {
11828             return;
11829         }
11830         var scheduler = this.scheduler;
11831         var message = new DelayMessage(scheduler.now() + this.delay, notification);
11832         this.queue.push(message);
11833         if (this.active === false) {
11834             this._schedule(scheduler);
11835         }
11836     };
11837     DelaySubscriber.prototype._next = function (value) {
11838         this.scheduleNotification(Notification_1.Notification.createNext(value));
11839     };
11840     DelaySubscriber.prototype._error = function (err) {
11841         this.errored = true;
11842         this.queue = [];
11843         this.destination.error(err);
11844     };
11845     DelaySubscriber.prototype._complete = function () {
11846         this.scheduleNotification(Notification_1.Notification.createComplete());
11847     };
11848     return DelaySubscriber;
11849 }(Subscriber_1.Subscriber));
11850 var DelayMessage = (function () {
11851     function DelayMessage(time, notification) {
11852         this.time = time;
11853         this.notification = notification;
11854     }
11855     return DelayMessage;
11856 }());
11857
11858 },{"../Notification":28,"../Subscriber":36,"../scheduler/async":213,"../util/isDate":229}],170:[function(require,module,exports){
11859 "use strict";
11860 var __extends = (this && this.__extends) || function (d, b) {
11861     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11862     function __() { this.constructor = d; }
11863     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11864 };
11865 var OuterSubscriber_1 = require('../OuterSubscriber');
11866 var subscribeToResult_1 = require('../util/subscribeToResult');
11867 var Set_1 = require('../util/Set');
11868 /**
11869  * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from previous items.
11870  *
11871  * If a keySelector function is provided, then it will project each value from the source observable into a new value that it will
11872  * check for equality with previously projected values. If a keySelector function is not provided, it will use each value from the
11873  * source observable directly with an equality check against previous values.
11874  *
11875  * In JavaScript runtimes that support `Set`, this operator will use a `Set` to improve performance of the distinct value checking.
11876  *
11877  * In other runtimes, this operator will use a minimal implementation of `Set` that relies on an `Array` and `indexOf` under the
11878  * hood, so performance will degrade as more values are checked for distinction. Even in newer browsers, a long-running `distinct`
11879  * use might result in memory leaks. To help alleviate this in some scenarios, an optional `flushes` parameter is also provided so
11880  * that the internal `Set` can be "flushed", basically clearing it of values.
11881  *
11882  * @example <caption>A simple example with numbers</caption>
11883  * Observable.of(1, 1, 2, 2, 2, 1, 2, 3, 4, 3, 2, 1)
11884  *   .distinct()
11885  *   .subscribe(x => console.log(x)); // 1, 2, 3, 4
11886  *
11887  * @example <caption>An example using a keySelector function</caption>
11888  * interface Person {
11889  *    age: number,
11890  *    name: string
11891  * }
11892  *
11893  * Observable.of<Person>(
11894  *     { age: 4, name: 'Foo'},
11895  *     { age: 7, name: 'Bar'},
11896  *     { age: 5, name: 'Foo'})
11897  *     .distinct((p: Person) => p.name)
11898  *     .subscribe(x => console.log(x));
11899  *
11900  * // displays:
11901  * // { age: 4, name: 'Foo' }
11902  * // { age: 7, name: 'Bar' }
11903  *
11904  * @see {@link distinctUntilChanged}
11905  * @see {@link distinctUntilKeyChanged}
11906  *
11907  * @param {function} [keySelector] Optional function to select which value you want to check as distinct.
11908  * @param {Observable} [flushes] Optional Observable for flushing the internal HashSet of the operator.
11909  * @return {Observable} An Observable that emits items from the source Observable with distinct values.
11910  * @method distinct
11911  * @owner Observable
11912  */
11913 function distinct(keySelector, flushes) {
11914     return function (source) { return source.lift(new DistinctOperator(keySelector, flushes)); };
11915 }
11916 exports.distinct = distinct;
11917 var DistinctOperator = (function () {
11918     function DistinctOperator(keySelector, flushes) {
11919         this.keySelector = keySelector;
11920         this.flushes = flushes;
11921     }
11922     DistinctOperator.prototype.call = function (subscriber, source) {
11923         return source.subscribe(new DistinctSubscriber(subscriber, this.keySelector, this.flushes));
11924     };
11925     return DistinctOperator;
11926 }());
11927 /**
11928  * We need this JSDoc comment for affecting ESDoc.
11929  * @ignore
11930  * @extends {Ignored}
11931  */
11932 var DistinctSubscriber = (function (_super) {
11933     __extends(DistinctSubscriber, _super);
11934     function DistinctSubscriber(destination, keySelector, flushes) {
11935         _super.call(this, destination);
11936         this.keySelector = keySelector;
11937         this.values = new Set_1.Set();
11938         if (flushes) {
11939             this.add(subscribeToResult_1.subscribeToResult(this, flushes));
11940         }
11941     }
11942     DistinctSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
11943         this.values.clear();
11944     };
11945     DistinctSubscriber.prototype.notifyError = function (error, innerSub) {
11946         this._error(error);
11947     };
11948     DistinctSubscriber.prototype._next = function (value) {
11949         if (this.keySelector) {
11950             this._useKeySelector(value);
11951         }
11952         else {
11953             this._finalizeNext(value, value);
11954         }
11955     };
11956     DistinctSubscriber.prototype._useKeySelector = function (value) {
11957         var key;
11958         var destination = this.destination;
11959         try {
11960             key = this.keySelector(value);
11961         }
11962         catch (err) {
11963             destination.error(err);
11964             return;
11965         }
11966         this._finalizeNext(key, value);
11967     };
11968     DistinctSubscriber.prototype._finalizeNext = function (key, value) {
11969         var values = this.values;
11970         if (!values.has(key)) {
11971             values.add(key);
11972             this.destination.next(value);
11973         }
11974     };
11975     return DistinctSubscriber;
11976 }(OuterSubscriber_1.OuterSubscriber));
11977 exports.DistinctSubscriber = DistinctSubscriber;
11978
11979 },{"../OuterSubscriber":31,"../util/Set":222,"../util/subscribeToResult":238}],171:[function(require,module,exports){
11980 "use strict";
11981 var __extends = (this && this.__extends) || function (d, b) {
11982     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
11983     function __() { this.constructor = d; }
11984     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
11985 };
11986 var Subscriber_1 = require('../Subscriber');
11987 var tryCatch_1 = require('../util/tryCatch');
11988 var errorObject_1 = require('../util/errorObject');
11989 /* tslint:enable:max-line-length */
11990 /**
11991  * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item.
11992  *
11993  * 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.
11994  *
11995  * If a comparator function is not provided, an equality check is used by default.
11996  *
11997  * @example <caption>A simple example with numbers</caption>
11998  * Observable.of(1, 1, 2, 2, 2, 1, 1, 2, 3, 3, 4)
11999  *   .distinctUntilChanged()
12000  *   .subscribe(x => console.log(x)); // 1, 2, 1, 2, 3, 4
12001  *
12002  * @example <caption>An example using a compare function</caption>
12003  * interface Person {
12004  *    age: number,
12005  *    name: string
12006  * }
12007  *
12008  * Observable.of<Person>(
12009  *     { age: 4, name: 'Foo'},
12010  *     { age: 7, name: 'Bar'},
12011  *     { age: 5, name: 'Foo'})
12012  *     { age: 6, name: 'Foo'})
12013  *     .distinctUntilChanged((p: Person, q: Person) => p.name === q.name)
12014  *     .subscribe(x => console.log(x));
12015  *
12016  * // displays:
12017  * // { age: 4, name: 'Foo' }
12018  * // { age: 7, name: 'Bar' }
12019  * // { age: 5, name: 'Foo' }
12020  *
12021  * @see {@link distinct}
12022  * @see {@link distinctUntilKeyChanged}
12023  *
12024  * @param {function} [compare] Optional comparison function called to test if an item is distinct from the previous item in the source.
12025  * @return {Observable} An Observable that emits items from the source Observable with distinct values.
12026  * @method distinctUntilChanged
12027  * @owner Observable
12028  */
12029 function distinctUntilChanged(compare, keySelector) {
12030     return function (source) { return source.lift(new DistinctUntilChangedOperator(compare, keySelector)); };
12031 }
12032 exports.distinctUntilChanged = distinctUntilChanged;
12033 var DistinctUntilChangedOperator = (function () {
12034     function DistinctUntilChangedOperator(compare, keySelector) {
12035         this.compare = compare;
12036         this.keySelector = keySelector;
12037     }
12038     DistinctUntilChangedOperator.prototype.call = function (subscriber, source) {
12039         return source.subscribe(new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector));
12040     };
12041     return DistinctUntilChangedOperator;
12042 }());
12043 /**
12044  * We need this JSDoc comment for affecting ESDoc.
12045  * @ignore
12046  * @extends {Ignored}
12047  */
12048 var DistinctUntilChangedSubscriber = (function (_super) {
12049     __extends(DistinctUntilChangedSubscriber, _super);
12050     function DistinctUntilChangedSubscriber(destination, compare, keySelector) {
12051         _super.call(this, destination);
12052         this.keySelector = keySelector;
12053         this.hasKey = false;
12054         if (typeof compare === 'function') {
12055             this.compare = compare;
12056         }
12057     }
12058     DistinctUntilChangedSubscriber.prototype.compare = function (x, y) {
12059         return x === y;
12060     };
12061     DistinctUntilChangedSubscriber.prototype._next = function (value) {
12062         var keySelector = this.keySelector;
12063         var key = value;
12064         if (keySelector) {
12065             key = tryCatch_1.tryCatch(this.keySelector)(value);
12066             if (key === errorObject_1.errorObject) {
12067                 return this.destination.error(errorObject_1.errorObject.e);
12068             }
12069         }
12070         var result = false;
12071         if (this.hasKey) {
12072             result = tryCatch_1.tryCatch(this.compare)(this.key, key);
12073             if (result === errorObject_1.errorObject) {
12074                 return this.destination.error(errorObject_1.errorObject.e);
12075             }
12076         }
12077         else {
12078             this.hasKey = true;
12079         }
12080         if (Boolean(result) === false) {
12081             this.key = key;
12082             this.destination.next(value);
12083         }
12084     };
12085     return DistinctUntilChangedSubscriber;
12086 }(Subscriber_1.Subscriber));
12087
12088 },{"../Subscriber":36,"../util/errorObject":225,"../util/tryCatch":240}],172:[function(require,module,exports){
12089 "use strict";
12090 var __extends = (this && this.__extends) || function (d, b) {
12091     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12092     function __() { this.constructor = d; }
12093     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12094 };
12095 var tryCatch_1 = require('../util/tryCatch');
12096 var errorObject_1 = require('../util/errorObject');
12097 var OuterSubscriber_1 = require('../OuterSubscriber');
12098 var subscribeToResult_1 = require('../util/subscribeToResult');
12099 /* tslint:enable:max-line-length */
12100 /**
12101  * Recursively projects each source value to an Observable which is merged in
12102  * the output Observable.
12103  *
12104  * <span class="informal">It's similar to {@link mergeMap}, but applies the
12105  * projection function to every source value as well as every output value.
12106  * It's recursive.</span>
12107  *
12108  * <img src="./img/expand.png" width="100%">
12109  *
12110  * Returns an Observable that emits items based on applying a function that you
12111  * supply to each item emitted by the source Observable, where that function
12112  * returns an Observable, and then merging those resulting Observables and
12113  * emitting the results of this merger. *Expand* will re-emit on the output
12114  * Observable every source value. Then, each output value is given to the
12115  * `project` function which returns an inner Observable to be merged on the
12116  * output Observable. Those output values resulting from the projection are also
12117  * given to the `project` function to produce new output values. This is how
12118  * *expand* behaves recursively.
12119  *
12120  * @example <caption>Start emitting the powers of two on every click, at most 10 of them</caption>
12121  * var clicks = Rx.Observable.fromEvent(document, 'click');
12122  * var powersOfTwo = clicks
12123  *   .mapTo(1)
12124  *   .expand(x => Rx.Observable.of(2 * x).delay(1000))
12125  *   .take(10);
12126  * powersOfTwo.subscribe(x => console.log(x));
12127  *
12128  * @see {@link mergeMap}
12129  * @see {@link mergeScan}
12130  *
12131  * @param {function(value: T, index: number) => Observable} project A function
12132  * that, when applied to an item emitted by the source or the output Observable,
12133  * returns an Observable.
12134  * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
12135  * Observables being subscribed to concurrently.
12136  * @param {Scheduler} [scheduler=null] The IScheduler to use for subscribing to
12137  * each projected inner Observable.
12138  * @return {Observable} An Observable that emits the source values and also
12139  * result of applying the projection function to each value emitted on the
12140  * output Observable and and merging the results of the Observables obtained
12141  * from this transformation.
12142  * @method expand
12143  * @owner Observable
12144  */
12145 function expand(project, concurrent, scheduler) {
12146     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
12147     if (scheduler === void 0) { scheduler = undefined; }
12148     concurrent = (concurrent || 0) < 1 ? Number.POSITIVE_INFINITY : concurrent;
12149     return function (source) { return source.lift(new ExpandOperator(project, concurrent, scheduler)); };
12150 }
12151 exports.expand = expand;
12152 var ExpandOperator = (function () {
12153     function ExpandOperator(project, concurrent, scheduler) {
12154         this.project = project;
12155         this.concurrent = concurrent;
12156         this.scheduler = scheduler;
12157     }
12158     ExpandOperator.prototype.call = function (subscriber, source) {
12159         return source.subscribe(new ExpandSubscriber(subscriber, this.project, this.concurrent, this.scheduler));
12160     };
12161     return ExpandOperator;
12162 }());
12163 exports.ExpandOperator = ExpandOperator;
12164 /**
12165  * We need this JSDoc comment for affecting ESDoc.
12166  * @ignore
12167  * @extends {Ignored}
12168  */
12169 var ExpandSubscriber = (function (_super) {
12170     __extends(ExpandSubscriber, _super);
12171     function ExpandSubscriber(destination, project, concurrent, scheduler) {
12172         _super.call(this, destination);
12173         this.project = project;
12174         this.concurrent = concurrent;
12175         this.scheduler = scheduler;
12176         this.index = 0;
12177         this.active = 0;
12178         this.hasCompleted = false;
12179         if (concurrent < Number.POSITIVE_INFINITY) {
12180             this.buffer = [];
12181         }
12182     }
12183     ExpandSubscriber.dispatch = function (arg) {
12184         var subscriber = arg.subscriber, result = arg.result, value = arg.value, index = arg.index;
12185         subscriber.subscribeToProjection(result, value, index);
12186     };
12187     ExpandSubscriber.prototype._next = function (value) {
12188         var destination = this.destination;
12189         if (destination.closed) {
12190             this._complete();
12191             return;
12192         }
12193         var index = this.index++;
12194         if (this.active < this.concurrent) {
12195             destination.next(value);
12196             var result = tryCatch_1.tryCatch(this.project)(value, index);
12197             if (result === errorObject_1.errorObject) {
12198                 destination.error(errorObject_1.errorObject.e);
12199             }
12200             else if (!this.scheduler) {
12201                 this.subscribeToProjection(result, value, index);
12202             }
12203             else {
12204                 var state = { subscriber: this, result: result, value: value, index: index };
12205                 this.add(this.scheduler.schedule(ExpandSubscriber.dispatch, 0, state));
12206             }
12207         }
12208         else {
12209             this.buffer.push(value);
12210         }
12211     };
12212     ExpandSubscriber.prototype.subscribeToProjection = function (result, value, index) {
12213         this.active++;
12214         this.add(subscribeToResult_1.subscribeToResult(this, result, value, index));
12215     };
12216     ExpandSubscriber.prototype._complete = function () {
12217         this.hasCompleted = true;
12218         if (this.hasCompleted && this.active === 0) {
12219             this.destination.complete();
12220         }
12221     };
12222     ExpandSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
12223         this._next(innerValue);
12224     };
12225     ExpandSubscriber.prototype.notifyComplete = function (innerSub) {
12226         var buffer = this.buffer;
12227         this.remove(innerSub);
12228         this.active--;
12229         if (buffer && buffer.length > 0) {
12230             this._next(buffer.shift());
12231         }
12232         if (this.hasCompleted && this.active === 0) {
12233             this.destination.complete();
12234         }
12235     };
12236     return ExpandSubscriber;
12237 }(OuterSubscriber_1.OuterSubscriber));
12238 exports.ExpandSubscriber = ExpandSubscriber;
12239
12240 },{"../OuterSubscriber":31,"../util/errorObject":225,"../util/subscribeToResult":238,"../util/tryCatch":240}],173:[function(require,module,exports){
12241 "use strict";
12242 var __extends = (this && this.__extends) || function (d, b) {
12243     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12244     function __() { this.constructor = d; }
12245     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12246 };
12247 var Subscriber_1 = require('../Subscriber');
12248 /* tslint:enable:max-line-length */
12249 /**
12250  * Filter items emitted by the source Observable by only emitting those that
12251  * satisfy a specified predicate.
12252  *
12253  * <span class="informal">Like
12254  * [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter),
12255  * it only emits a value from the source if it passes a criterion function.</span>
12256  *
12257  * <img src="./img/filter.png" width="100%">
12258  *
12259  * Similar to the well-known `Array.prototype.filter` method, this operator
12260  * takes values from the source Observable, passes them through a `predicate`
12261  * function and only emits those values that yielded `true`.
12262  *
12263  * @example <caption>Emit only click events whose target was a DIV element</caption>
12264  * var clicks = Rx.Observable.fromEvent(document, 'click');
12265  * var clicksOnDivs = clicks.filter(ev => ev.target.tagName === 'DIV');
12266  * clicksOnDivs.subscribe(x => console.log(x));
12267  *
12268  * @see {@link distinct}
12269  * @see {@link distinctUntilChanged}
12270  * @see {@link distinctUntilKeyChanged}
12271  * @see {@link ignoreElements}
12272  * @see {@link partition}
12273  * @see {@link skip}
12274  *
12275  * @param {function(value: T, index: number): boolean} predicate A function that
12276  * evaluates each value emitted by the source Observable. If it returns `true`,
12277  * the value is emitted, if `false` the value is not passed to the output
12278  * Observable. The `index` parameter is the number `i` for the i-th source
12279  * emission that has happened since the subscription, starting from the number
12280  * `0`.
12281  * @param {any} [thisArg] An optional argument to determine the value of `this`
12282  * in the `predicate` function.
12283  * @return {Observable} An Observable of values from the source that were
12284  * allowed by the `predicate` function.
12285  * @method filter
12286  * @owner Observable
12287  */
12288 function filter(predicate, thisArg) {
12289     return function filterOperatorFunction(source) {
12290         return source.lift(new FilterOperator(predicate, thisArg));
12291     };
12292 }
12293 exports.filter = filter;
12294 var FilterOperator = (function () {
12295     function FilterOperator(predicate, thisArg) {
12296         this.predicate = predicate;
12297         this.thisArg = thisArg;
12298     }
12299     FilterOperator.prototype.call = function (subscriber, source) {
12300         return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg));
12301     };
12302     return FilterOperator;
12303 }());
12304 /**
12305  * We need this JSDoc comment for affecting ESDoc.
12306  * @ignore
12307  * @extends {Ignored}
12308  */
12309 var FilterSubscriber = (function (_super) {
12310     __extends(FilterSubscriber, _super);
12311     function FilterSubscriber(destination, predicate, thisArg) {
12312         _super.call(this, destination);
12313         this.predicate = predicate;
12314         this.thisArg = thisArg;
12315         this.count = 0;
12316     }
12317     // the try catch block below is left specifically for
12318     // optimization and perf reasons. a tryCatcher is not necessary here.
12319     FilterSubscriber.prototype._next = function (value) {
12320         var result;
12321         try {
12322             result = this.predicate.call(this.thisArg, value, this.count++);
12323         }
12324         catch (err) {
12325             this.destination.error(err);
12326             return;
12327         }
12328         if (result) {
12329             this.destination.next(value);
12330         }
12331     };
12332     return FilterSubscriber;
12333 }(Subscriber_1.Subscriber));
12334
12335 },{"../Subscriber":36}],174:[function(require,module,exports){
12336 "use strict";
12337 var __extends = (this && this.__extends) || function (d, b) {
12338     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12339     function __() { this.constructor = d; }
12340     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12341 };
12342 var Subscriber_1 = require('../Subscriber');
12343 var Subscription_1 = require('../Subscription');
12344 /**
12345  * Returns an Observable that mirrors the source Observable, but will call a specified function when
12346  * the source terminates on complete or error.
12347  * @param {function} callback Function to be called when source terminates.
12348  * @return {Observable} An Observable that mirrors the source, but will call the specified function on termination.
12349  * @method finally
12350  * @owner Observable
12351  */
12352 function finalize(callback) {
12353     return function (source) { return source.lift(new FinallyOperator(callback)); };
12354 }
12355 exports.finalize = finalize;
12356 var FinallyOperator = (function () {
12357     function FinallyOperator(callback) {
12358         this.callback = callback;
12359     }
12360     FinallyOperator.prototype.call = function (subscriber, source) {
12361         return source.subscribe(new FinallySubscriber(subscriber, this.callback));
12362     };
12363     return FinallyOperator;
12364 }());
12365 /**
12366  * We need this JSDoc comment for affecting ESDoc.
12367  * @ignore
12368  * @extends {Ignored}
12369  */
12370 var FinallySubscriber = (function (_super) {
12371     __extends(FinallySubscriber, _super);
12372     function FinallySubscriber(destination, callback) {
12373         _super.call(this, destination);
12374         this.add(new Subscription_1.Subscription(callback));
12375     }
12376     return FinallySubscriber;
12377 }(Subscriber_1.Subscriber));
12378
12379 },{"../Subscriber":36,"../Subscription":37}],175:[function(require,module,exports){
12380 "use strict";
12381 var __extends = (this && this.__extends) || function (d, b) {
12382     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12383     function __() { this.constructor = d; }
12384     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12385 };
12386 var Subscriber_1 = require('../Subscriber');
12387 var EmptyError_1 = require('../util/EmptyError');
12388 /**
12389  * Emits only the first value (or the first value that meets some condition)
12390  * emitted by the source Observable.
12391  *
12392  * <span class="informal">Emits only the first value. Or emits only the first
12393  * value that passes some test.</span>
12394  *
12395  * <img src="./img/first.png" width="100%">
12396  *
12397  * If called with no arguments, `first` emits the first value of the source
12398  * Observable, then completes. If called with a `predicate` function, `first`
12399  * emits the first value of the source that matches the specified condition. It
12400  * may also take a `resultSelector` function to produce the output value from
12401  * the input value, and a `defaultValue` to emit in case the source completes
12402  * before it is able to emit a valid value. Throws an error if `defaultValue`
12403  * was not provided and a matching element is not found.
12404  *
12405  * @example <caption>Emit only the first click that happens on the DOM</caption>
12406  * var clicks = Rx.Observable.fromEvent(document, 'click');
12407  * var result = clicks.first();
12408  * result.subscribe(x => console.log(x));
12409  *
12410  * @example <caption>Emits the first click that happens on a DIV</caption>
12411  * var clicks = Rx.Observable.fromEvent(document, 'click');
12412  * var result = clicks.first(ev => ev.target.tagName === 'DIV');
12413  * result.subscribe(x => console.log(x));
12414  *
12415  * @see {@link filter}
12416  * @see {@link find}
12417  * @see {@link take}
12418  *
12419  * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
12420  * callback if the Observable completes before any `next` notification was sent.
12421  *
12422  * @param {function(value: T, index: number, source: Observable<T>): boolean} [predicate]
12423  * An optional function called with each item to test for condition matching.
12424  * @param {function(value: T, index: number): R} [resultSelector] A function to
12425  * produce the value on the output Observable based on the values
12426  * and the indices of the source Observable. The arguments passed to this
12427  * function are:
12428  * - `value`: the value that was emitted on the source.
12429  * - `index`: the "index" of the value from the source.
12430  * @param {R} [defaultValue] The default value emitted in case no valid value
12431  * was found on the source.
12432  * @return {Observable<T|R>} An Observable of the first item that matches the
12433  * condition.
12434  * @method first
12435  * @owner Observable
12436  */
12437 function first(predicate, resultSelector, defaultValue) {
12438     return function (source) { return source.lift(new FirstOperator(predicate, resultSelector, defaultValue, source)); };
12439 }
12440 exports.first = first;
12441 var FirstOperator = (function () {
12442     function FirstOperator(predicate, resultSelector, defaultValue, source) {
12443         this.predicate = predicate;
12444         this.resultSelector = resultSelector;
12445         this.defaultValue = defaultValue;
12446         this.source = source;
12447     }
12448     FirstOperator.prototype.call = function (observer, source) {
12449         return source.subscribe(new FirstSubscriber(observer, this.predicate, this.resultSelector, this.defaultValue, this.source));
12450     };
12451     return FirstOperator;
12452 }());
12453 /**
12454  * We need this JSDoc comment for affecting ESDoc.
12455  * @ignore
12456  * @extends {Ignored}
12457  */
12458 var FirstSubscriber = (function (_super) {
12459     __extends(FirstSubscriber, _super);
12460     function FirstSubscriber(destination, predicate, resultSelector, defaultValue, source) {
12461         _super.call(this, destination);
12462         this.predicate = predicate;
12463         this.resultSelector = resultSelector;
12464         this.defaultValue = defaultValue;
12465         this.source = source;
12466         this.index = 0;
12467         this.hasCompleted = false;
12468         this._emitted = false;
12469     }
12470     FirstSubscriber.prototype._next = function (value) {
12471         var index = this.index++;
12472         if (this.predicate) {
12473             this._tryPredicate(value, index);
12474         }
12475         else {
12476             this._emit(value, index);
12477         }
12478     };
12479     FirstSubscriber.prototype._tryPredicate = function (value, index) {
12480         var result;
12481         try {
12482             result = this.predicate(value, index, this.source);
12483         }
12484         catch (err) {
12485             this.destination.error(err);
12486             return;
12487         }
12488         if (result) {
12489             this._emit(value, index);
12490         }
12491     };
12492     FirstSubscriber.prototype._emit = function (value, index) {
12493         if (this.resultSelector) {
12494             this._tryResultSelector(value, index);
12495             return;
12496         }
12497         this._emitFinal(value);
12498     };
12499     FirstSubscriber.prototype._tryResultSelector = function (value, index) {
12500         var result;
12501         try {
12502             result = this.resultSelector(value, index);
12503         }
12504         catch (err) {
12505             this.destination.error(err);
12506             return;
12507         }
12508         this._emitFinal(result);
12509     };
12510     FirstSubscriber.prototype._emitFinal = function (value) {
12511         var destination = this.destination;
12512         if (!this._emitted) {
12513             this._emitted = true;
12514             destination.next(value);
12515             destination.complete();
12516             this.hasCompleted = true;
12517         }
12518     };
12519     FirstSubscriber.prototype._complete = function () {
12520         var destination = this.destination;
12521         if (!this.hasCompleted && typeof this.defaultValue !== 'undefined') {
12522             destination.next(this.defaultValue);
12523             destination.complete();
12524         }
12525         else if (!this.hasCompleted) {
12526             destination.error(new EmptyError_1.EmptyError);
12527         }
12528     };
12529     return FirstSubscriber;
12530 }(Subscriber_1.Subscriber));
12531
12532 },{"../Subscriber":36,"../util/EmptyError":220}],176:[function(require,module,exports){
12533 "use strict";
12534 var __extends = (this && this.__extends) || function (d, b) {
12535     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12536     function __() { this.constructor = d; }
12537     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12538 };
12539 var Subscriber_1 = require('../Subscriber');
12540 var EmptyError_1 = require('../util/EmptyError');
12541 /* tslint:enable:max-line-length */
12542 /**
12543  * Returns an Observable that emits only the last item emitted by the source Observable.
12544  * It optionally takes a predicate function as a parameter, in which case, rather than emitting
12545  * the last item from the source Observable, the resulting Observable will emit the last item
12546  * from the source Observable that satisfies the predicate.
12547  *
12548  * <img src="./img/last.png" width="100%">
12549  *
12550  * @throws {EmptyError} Delivers an EmptyError to the Observer's `error`
12551  * callback if the Observable completes before any `next` notification was sent.
12552  * @param {function} predicate - The condition any source emitted item has to satisfy.
12553  * @return {Observable} An Observable that emits only the last item satisfying the given condition
12554  * from the source, or an NoSuchElementException if no such items are emitted.
12555  * @throws - Throws if no items that match the predicate are emitted by the source Observable.
12556  * @method last
12557  * @owner Observable
12558  */
12559 function last(predicate, resultSelector, defaultValue) {
12560     return function (source) { return source.lift(new LastOperator(predicate, resultSelector, defaultValue, source)); };
12561 }
12562 exports.last = last;
12563 var LastOperator = (function () {
12564     function LastOperator(predicate, resultSelector, defaultValue, source) {
12565         this.predicate = predicate;
12566         this.resultSelector = resultSelector;
12567         this.defaultValue = defaultValue;
12568         this.source = source;
12569     }
12570     LastOperator.prototype.call = function (observer, source) {
12571         return source.subscribe(new LastSubscriber(observer, this.predicate, this.resultSelector, this.defaultValue, this.source));
12572     };
12573     return LastOperator;
12574 }());
12575 /**
12576  * We need this JSDoc comment for affecting ESDoc.
12577  * @ignore
12578  * @extends {Ignored}
12579  */
12580 var LastSubscriber = (function (_super) {
12581     __extends(LastSubscriber, _super);
12582     function LastSubscriber(destination, predicate, resultSelector, defaultValue, source) {
12583         _super.call(this, destination);
12584         this.predicate = predicate;
12585         this.resultSelector = resultSelector;
12586         this.defaultValue = defaultValue;
12587         this.source = source;
12588         this.hasValue = false;
12589         this.index = 0;
12590         if (typeof defaultValue !== 'undefined') {
12591             this.lastValue = defaultValue;
12592             this.hasValue = true;
12593         }
12594     }
12595     LastSubscriber.prototype._next = function (value) {
12596         var index = this.index++;
12597         if (this.predicate) {
12598             this._tryPredicate(value, index);
12599         }
12600         else {
12601             if (this.resultSelector) {
12602                 this._tryResultSelector(value, index);
12603                 return;
12604             }
12605             this.lastValue = value;
12606             this.hasValue = true;
12607         }
12608     };
12609     LastSubscriber.prototype._tryPredicate = function (value, index) {
12610         var result;
12611         try {
12612             result = this.predicate(value, index, this.source);
12613         }
12614         catch (err) {
12615             this.destination.error(err);
12616             return;
12617         }
12618         if (result) {
12619             if (this.resultSelector) {
12620                 this._tryResultSelector(value, index);
12621                 return;
12622             }
12623             this.lastValue = value;
12624             this.hasValue = true;
12625         }
12626     };
12627     LastSubscriber.prototype._tryResultSelector = function (value, index) {
12628         var result;
12629         try {
12630             result = this.resultSelector(value, index);
12631         }
12632         catch (err) {
12633             this.destination.error(err);
12634             return;
12635         }
12636         this.lastValue = result;
12637         this.hasValue = true;
12638     };
12639     LastSubscriber.prototype._complete = function () {
12640         var destination = this.destination;
12641         if (this.hasValue) {
12642             destination.next(this.lastValue);
12643             destination.complete();
12644         }
12645         else {
12646             destination.error(new EmptyError_1.EmptyError);
12647         }
12648     };
12649     return LastSubscriber;
12650 }(Subscriber_1.Subscriber));
12651
12652 },{"../Subscriber":36,"../util/EmptyError":220}],177:[function(require,module,exports){
12653 "use strict";
12654 var __extends = (this && this.__extends) || function (d, b) {
12655     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12656     function __() { this.constructor = d; }
12657     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12658 };
12659 var Subscriber_1 = require('../Subscriber');
12660 /**
12661  * Applies a given `project` function to each value emitted by the source
12662  * Observable, and emits the resulting values as an Observable.
12663  *
12664  * <span class="informal">Like [Array.prototype.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map),
12665  * it passes each source value through a transformation function to get
12666  * corresponding output values.</span>
12667  *
12668  * <img src="./img/map.png" width="100%">
12669  *
12670  * Similar to the well known `Array.prototype.map` function, this operator
12671  * applies a projection to each value and emits that projection in the output
12672  * Observable.
12673  *
12674  * @example <caption>Map every click to the clientX position of that click</caption>
12675  * var clicks = Rx.Observable.fromEvent(document, 'click');
12676  * var positions = clicks.map(ev => ev.clientX);
12677  * positions.subscribe(x => console.log(x));
12678  *
12679  * @see {@link mapTo}
12680  * @see {@link pluck}
12681  *
12682  * @param {function(value: T, index: number): R} project The function to apply
12683  * to each `value` emitted by the source Observable. The `index` parameter is
12684  * the number `i` for the i-th emission that has happened since the
12685  * subscription, starting from the number `0`.
12686  * @param {any} [thisArg] An optional argument to define what `this` is in the
12687  * `project` function.
12688  * @return {Observable<R>} An Observable that emits the values from the source
12689  * Observable transformed by the given `project` function.
12690  * @method map
12691  * @owner Observable
12692  */
12693 function map(project, thisArg) {
12694     return function mapOperation(source) {
12695         if (typeof project !== 'function') {
12696             throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');
12697         }
12698         return source.lift(new MapOperator(project, thisArg));
12699     };
12700 }
12701 exports.map = map;
12702 var MapOperator = (function () {
12703     function MapOperator(project, thisArg) {
12704         this.project = project;
12705         this.thisArg = thisArg;
12706     }
12707     MapOperator.prototype.call = function (subscriber, source) {
12708         return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg));
12709     };
12710     return MapOperator;
12711 }());
12712 exports.MapOperator = MapOperator;
12713 /**
12714  * We need this JSDoc comment for affecting ESDoc.
12715  * @ignore
12716  * @extends {Ignored}
12717  */
12718 var MapSubscriber = (function (_super) {
12719     __extends(MapSubscriber, _super);
12720     function MapSubscriber(destination, project, thisArg) {
12721         _super.call(this, destination);
12722         this.project = project;
12723         this.count = 0;
12724         this.thisArg = thisArg || this;
12725     }
12726     // NOTE: This looks unoptimized, but it's actually purposefully NOT
12727     // using try/catch optimizations.
12728     MapSubscriber.prototype._next = function (value) {
12729         var result;
12730         try {
12731             result = this.project.call(this.thisArg, value, this.count++);
12732         }
12733         catch (err) {
12734             this.destination.error(err);
12735             return;
12736         }
12737         this.destination.next(result);
12738     };
12739     return MapSubscriber;
12740 }(Subscriber_1.Subscriber));
12741
12742 },{"../Subscriber":36}],178:[function(require,module,exports){
12743 "use strict";
12744 var Observable_1 = require('../Observable');
12745 var ArrayObservable_1 = require('../observable/ArrayObservable');
12746 var mergeAll_1 = require('./mergeAll');
12747 var isScheduler_1 = require('../util/isScheduler');
12748 /* tslint:enable:max-line-length */
12749 function merge() {
12750     var observables = [];
12751     for (var _i = 0; _i < arguments.length; _i++) {
12752         observables[_i - 0] = arguments[_i];
12753     }
12754     return function (source) { return source.lift.call(mergeStatic.apply(void 0, [source].concat(observables))); };
12755 }
12756 exports.merge = merge;
12757 /* tslint:enable:max-line-length */
12758 /**
12759  * Creates an output Observable which concurrently emits all values from every
12760  * given input Observable.
12761  *
12762  * <span class="informal">Flattens multiple Observables together by blending
12763  * their values into one Observable.</span>
12764  *
12765  * <img src="./img/merge.png" width="100%">
12766  *
12767  * `merge` subscribes to each given input Observable (as arguments), and simply
12768  * forwards (without doing any transformation) all the values from all the input
12769  * Observables to the output Observable. The output Observable only completes
12770  * once all input Observables have completed. Any error delivered by an input
12771  * Observable will be immediately emitted on the output Observable.
12772  *
12773  * @example <caption>Merge together two Observables: 1s interval and clicks</caption>
12774  * var clicks = Rx.Observable.fromEvent(document, 'click');
12775  * var timer = Rx.Observable.interval(1000);
12776  * var clicksOrTimer = Rx.Observable.merge(clicks, timer);
12777  * clicksOrTimer.subscribe(x => console.log(x));
12778  *
12779  * // Results in the following:
12780  * // timer will emit ascending values, one every second(1000ms) to console
12781  * // clicks logs MouseEvents to console everytime the "document" is clicked
12782  * // Since the two streams are merged you see these happening
12783  * // as they occur.
12784  *
12785  * @example <caption>Merge together 3 Observables, but only 2 run concurrently</caption>
12786  * var timer1 = Rx.Observable.interval(1000).take(10);
12787  * var timer2 = Rx.Observable.interval(2000).take(6);
12788  * var timer3 = Rx.Observable.interval(500).take(10);
12789  * var concurrent = 2; // the argument
12790  * var merged = Rx.Observable.merge(timer1, timer2, timer3, concurrent);
12791  * merged.subscribe(x => console.log(x));
12792  *
12793  * // Results in the following:
12794  * // - First timer1 and timer2 will run concurrently
12795  * // - timer1 will emit a value every 1000ms for 10 iterations
12796  * // - timer2 will emit a value every 2000ms for 6 iterations
12797  * // - after timer1 hits it's max iteration, timer2 will
12798  * //   continue, and timer3 will start to run concurrently with timer2
12799  * // - when timer2 hits it's max iteration it terminates, and
12800  * //   timer3 will continue to emit a value every 500ms until it is complete
12801  *
12802  * @see {@link mergeAll}
12803  * @see {@link mergeMap}
12804  * @see {@link mergeMapTo}
12805  * @see {@link mergeScan}
12806  *
12807  * @param {...ObservableInput} observables Input Observables to merge together.
12808  * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
12809  * Observables being subscribed to concurrently.
12810  * @param {Scheduler} [scheduler=null] The IScheduler to use for managing
12811  * concurrency of input Observables.
12812  * @return {Observable} an Observable that emits items that are the result of
12813  * every input Observable.
12814  * @static true
12815  * @name merge
12816  * @owner Observable
12817  */
12818 function mergeStatic() {
12819     var observables = [];
12820     for (var _i = 0; _i < arguments.length; _i++) {
12821         observables[_i - 0] = arguments[_i];
12822     }
12823     var concurrent = Number.POSITIVE_INFINITY;
12824     var scheduler = null;
12825     var last = observables[observables.length - 1];
12826     if (isScheduler_1.isScheduler(last)) {
12827         scheduler = observables.pop();
12828         if (observables.length > 1 && typeof observables[observables.length - 1] === 'number') {
12829             concurrent = observables.pop();
12830         }
12831     }
12832     else if (typeof last === 'number') {
12833         concurrent = observables.pop();
12834     }
12835     if (scheduler === null && observables.length === 1 && observables[0] instanceof Observable_1.Observable) {
12836         return observables[0];
12837     }
12838     return mergeAll_1.mergeAll(concurrent)(new ArrayObservable_1.ArrayObservable(observables, scheduler));
12839 }
12840 exports.mergeStatic = mergeStatic;
12841
12842 },{"../Observable":29,"../observable/ArrayObservable":93,"../util/isScheduler":234,"./mergeAll":179}],179:[function(require,module,exports){
12843 "use strict";
12844 var mergeMap_1 = require('./mergeMap');
12845 var identity_1 = require('../util/identity');
12846 /**
12847  * Converts a higher-order Observable into a first-order Observable which
12848  * concurrently delivers all values that are emitted on the inner Observables.
12849  *
12850  * <span class="informal">Flattens an Observable-of-Observables.</span>
12851  *
12852  * <img src="./img/mergeAll.png" width="100%">
12853  *
12854  * `mergeAll` subscribes to an Observable that emits Observables, also known as
12855  * a higher-order Observable. Each time it observes one of these emitted inner
12856  * Observables, it subscribes to that and delivers all the values from the
12857  * inner Observable on the output Observable. The output Observable only
12858  * completes once all inner Observables have completed. Any error delivered by
12859  * a inner Observable will be immediately emitted on the output Observable.
12860  *
12861  * @example <caption>Spawn a new interval Observable for each click event, and blend their outputs as one Observable</caption>
12862  * var clicks = Rx.Observable.fromEvent(document, 'click');
12863  * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000));
12864  * var firstOrder = higherOrder.mergeAll();
12865  * firstOrder.subscribe(x => console.log(x));
12866  *
12867  * @example <caption>Count from 0 to 9 every second for each click, but only allow 2 concurrent timers</caption>
12868  * var clicks = Rx.Observable.fromEvent(document, 'click');
12869  * var higherOrder = clicks.map((ev) => Rx.Observable.interval(1000).take(10));
12870  * var firstOrder = higherOrder.mergeAll(2);
12871  * firstOrder.subscribe(x => console.log(x));
12872  *
12873  * @see {@link combineAll}
12874  * @see {@link concatAll}
12875  * @see {@link exhaust}
12876  * @see {@link merge}
12877  * @see {@link mergeMap}
12878  * @see {@link mergeMapTo}
12879  * @see {@link mergeScan}
12880  * @see {@link switch}
12881  * @see {@link zipAll}
12882  *
12883  * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of inner
12884  * Observables being subscribed to concurrently.
12885  * @return {Observable} An Observable that emits values coming from all the
12886  * inner Observables emitted by the source Observable.
12887  * @method mergeAll
12888  * @owner Observable
12889  */
12890 function mergeAll(concurrent) {
12891     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
12892     return mergeMap_1.mergeMap(identity_1.identity, null, concurrent);
12893 }
12894 exports.mergeAll = mergeAll;
12895
12896 },{"../util/identity":226,"./mergeMap":180}],180:[function(require,module,exports){
12897 "use strict";
12898 var __extends = (this && this.__extends) || function (d, b) {
12899     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
12900     function __() { this.constructor = d; }
12901     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12902 };
12903 var subscribeToResult_1 = require('../util/subscribeToResult');
12904 var OuterSubscriber_1 = require('../OuterSubscriber');
12905 /* tslint:enable:max-line-length */
12906 /**
12907  * Projects each source value to an Observable which is merged in the output
12908  * Observable.
12909  *
12910  * <span class="informal">Maps each value to an Observable, then flattens all of
12911  * these inner Observables using {@link mergeAll}.</span>
12912  *
12913  * <img src="./img/mergeMap.png" width="100%">
12914  *
12915  * Returns an Observable that emits items based on applying a function that you
12916  * supply to each item emitted by the source Observable, where that function
12917  * returns an Observable, and then merging those resulting Observables and
12918  * emitting the results of this merger.
12919  *
12920  * @example <caption>Map and flatten each letter to an Observable ticking every 1 second</caption>
12921  * var letters = Rx.Observable.of('a', 'b', 'c');
12922  * var result = letters.mergeMap(x =>
12923  *   Rx.Observable.interval(1000).map(i => x+i)
12924  * );
12925  * result.subscribe(x => console.log(x));
12926  *
12927  * // Results in the following:
12928  * // a0
12929  * // b0
12930  * // c0
12931  * // a1
12932  * // b1
12933  * // c1
12934  * // continues to list a,b,c with respective ascending integers
12935  *
12936  * @see {@link concatMap}
12937  * @see {@link exhaustMap}
12938  * @see {@link merge}
12939  * @see {@link mergeAll}
12940  * @see {@link mergeMapTo}
12941  * @see {@link mergeScan}
12942  * @see {@link switchMap}
12943  *
12944  * @param {function(value: T, ?index: number): ObservableInput} project A function
12945  * that, when applied to an item emitted by the source Observable, returns an
12946  * Observable.
12947  * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
12948  * A function to produce the value on the output Observable based on the values
12949  * and the indices of the source (outer) emission and the inner Observable
12950  * emission. The arguments passed to this function are:
12951  * - `outerValue`: the value that came from the source
12952  * - `innerValue`: the value that came from the projected Observable
12953  * - `outerIndex`: the "index" of the value that came from the source
12954  * - `innerIndex`: the "index" of the value from the projected Observable
12955  * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
12956  * Observables being subscribed to concurrently.
12957  * @return {Observable} An Observable that emits the result of applying the
12958  * projection function (and the optional `resultSelector`) to each item emitted
12959  * by the source Observable and merging the results of the Observables obtained
12960  * from this transformation.
12961  * @method mergeMap
12962  * @owner Observable
12963  */
12964 function mergeMap(project, resultSelector, concurrent) {
12965     if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
12966     return function mergeMapOperatorFunction(source) {
12967         if (typeof resultSelector === 'number') {
12968             concurrent = resultSelector;
12969             resultSelector = null;
12970         }
12971         return source.lift(new MergeMapOperator(project, resultSelector, concurrent));
12972     };
12973 }
12974 exports.mergeMap = mergeMap;
12975 var MergeMapOperator = (function () {
12976     function MergeMapOperator(project, resultSelector, concurrent) {
12977         if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
12978         this.project = project;
12979         this.resultSelector = resultSelector;
12980         this.concurrent = concurrent;
12981     }
12982     MergeMapOperator.prototype.call = function (observer, source) {
12983         return source.subscribe(new MergeMapSubscriber(observer, this.project, this.resultSelector, this.concurrent));
12984     };
12985     return MergeMapOperator;
12986 }());
12987 exports.MergeMapOperator = MergeMapOperator;
12988 /**
12989  * We need this JSDoc comment for affecting ESDoc.
12990  * @ignore
12991  * @extends {Ignored}
12992  */
12993 var MergeMapSubscriber = (function (_super) {
12994     __extends(MergeMapSubscriber, _super);
12995     function MergeMapSubscriber(destination, project, resultSelector, concurrent) {
12996         if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
12997         _super.call(this, destination);
12998         this.project = project;
12999         this.resultSelector = resultSelector;
13000         this.concurrent = concurrent;
13001         this.hasCompleted = false;
13002         this.buffer = [];
13003         this.active = 0;
13004         this.index = 0;
13005     }
13006     MergeMapSubscriber.prototype._next = function (value) {
13007         if (this.active < this.concurrent) {
13008             this._tryNext(value);
13009         }
13010         else {
13011             this.buffer.push(value);
13012         }
13013     };
13014     MergeMapSubscriber.prototype._tryNext = function (value) {
13015         var result;
13016         var index = this.index++;
13017         try {
13018             result = this.project(value, index);
13019         }
13020         catch (err) {
13021             this.destination.error(err);
13022             return;
13023         }
13024         this.active++;
13025         this._innerSub(result, value, index);
13026     };
13027     MergeMapSubscriber.prototype._innerSub = function (ish, value, index) {
13028         this.add(subscribeToResult_1.subscribeToResult(this, ish, value, index));
13029     };
13030     MergeMapSubscriber.prototype._complete = function () {
13031         this.hasCompleted = true;
13032         if (this.active === 0 && this.buffer.length === 0) {
13033             this.destination.complete();
13034         }
13035     };
13036     MergeMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
13037         if (this.resultSelector) {
13038             this._notifyResultSelector(outerValue, innerValue, outerIndex, innerIndex);
13039         }
13040         else {
13041             this.destination.next(innerValue);
13042         }
13043     };
13044     MergeMapSubscriber.prototype._notifyResultSelector = function (outerValue, innerValue, outerIndex, innerIndex) {
13045         var result;
13046         try {
13047             result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex);
13048         }
13049         catch (err) {
13050             this.destination.error(err);
13051             return;
13052         }
13053         this.destination.next(result);
13054     };
13055     MergeMapSubscriber.prototype.notifyComplete = function (innerSub) {
13056         var buffer = this.buffer;
13057         this.remove(innerSub);
13058         this.active--;
13059         if (buffer.length > 0) {
13060             this._next(buffer.shift());
13061         }
13062         else if (this.active === 0 && this.hasCompleted) {
13063             this.destination.complete();
13064         }
13065     };
13066     return MergeMapSubscriber;
13067 }(OuterSubscriber_1.OuterSubscriber));
13068 exports.MergeMapSubscriber = MergeMapSubscriber;
13069
13070 },{"../OuterSubscriber":31,"../util/subscribeToResult":238}],181:[function(require,module,exports){
13071 "use strict";
13072 var ConnectableObservable_1 = require('../observable/ConnectableObservable');
13073 /* tslint:enable:max-line-length */
13074 /**
13075  * Returns an Observable that emits the results of invoking a specified selector on items
13076  * emitted by a ConnectableObservable that shares a single subscription to the underlying stream.
13077  *
13078  * <img src="./img/multicast.png" width="100%">
13079  *
13080  * @param {Function|Subject} subjectOrSubjectFactory - Factory function to create an intermediate subject through
13081  * which the source sequence's elements will be multicast to the selector function
13082  * or Subject to push source elements into.
13083  * @param {Function} [selector] - Optional selector function that can use the multicasted source stream
13084  * as many times as needed, without causing multiple subscriptions to the source stream.
13085  * Subscribers to the given source will receive all notifications of the source from the
13086  * time of the subscription forward.
13087  * @return {Observable} An Observable that emits the results of invoking the selector
13088  * on the items emitted by a `ConnectableObservable` that shares a single subscription to
13089  * the underlying stream.
13090  * @method multicast
13091  * @owner Observable
13092  */
13093 function multicast(subjectOrSubjectFactory, selector) {
13094     return function multicastOperatorFunction(source) {
13095         var subjectFactory;
13096         if (typeof subjectOrSubjectFactory === 'function') {
13097             subjectFactory = subjectOrSubjectFactory;
13098         }
13099         else {
13100             subjectFactory = function subjectFactory() {
13101                 return subjectOrSubjectFactory;
13102             };
13103         }
13104         if (typeof selector === 'function') {
13105             return source.lift(new MulticastOperator(subjectFactory, selector));
13106         }
13107         var connectable = Object.create(source, ConnectableObservable_1.connectableObservableDescriptor);
13108         connectable.source = source;
13109         connectable.subjectFactory = subjectFactory;
13110         return connectable;
13111     };
13112 }
13113 exports.multicast = multicast;
13114 var MulticastOperator = (function () {
13115     function MulticastOperator(subjectFactory, selector) {
13116         this.subjectFactory = subjectFactory;
13117         this.selector = selector;
13118     }
13119     MulticastOperator.prototype.call = function (subscriber, source) {
13120         var selector = this.selector;
13121         var subject = this.subjectFactory();
13122         var subscription = selector(subject).subscribe(subscriber);
13123         subscription.add(source.subscribe(subject));
13124         return subscription;
13125     };
13126     return MulticastOperator;
13127 }());
13128 exports.MulticastOperator = MulticastOperator;
13129
13130 },{"../observable/ConnectableObservable":94}],182:[function(require,module,exports){
13131 "use strict";
13132 var __extends = (this && this.__extends) || function (d, b) {
13133     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13134     function __() { this.constructor = d; }
13135     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13136 };
13137 var Subscriber_1 = require('../Subscriber');
13138 var Notification_1 = require('../Notification');
13139 /**
13140  *
13141  * Re-emits all notifications from source Observable with specified scheduler.
13142  *
13143  * <span class="informal">Ensure a specific scheduler is used, from outside of an Observable.</span>
13144  *
13145  * `observeOn` is an operator that accepts a scheduler as a first parameter, which will be used to reschedule
13146  * notifications emitted by the source Observable. It might be useful, if you do not have control over
13147  * internal scheduler of a given Observable, but want to control when its values are emitted nevertheless.
13148  *
13149  * Returned Observable emits the same notifications (nexted values, complete and error events) as the source Observable,
13150  * but rescheduled with provided scheduler. Note that this doesn't mean that source Observables internal
13151  * scheduler will be replaced in any way. Original scheduler still will be used, but when the source Observable emits
13152  * notification, it will be immediately scheduled again - this time with scheduler passed to `observeOn`.
13153  * An anti-pattern would be calling `observeOn` on Observable that emits lots of values synchronously, to split
13154  * that emissions into asynchronous chunks. For this to happen, scheduler would have to be passed into the source
13155  * Observable directly (usually into the operator that creates it). `observeOn` simply delays notifications a
13156  * little bit more, to ensure that they are emitted at expected moments.
13157  *
13158  * As a matter of fact, `observeOn` accepts second parameter, which specifies in milliseconds with what delay notifications
13159  * will be emitted. The main difference between {@link delay} operator and `observeOn` is that `observeOn`
13160  * will delay all notifications - including error notifications - while `delay` will pass through error
13161  * from source Observable immediately when it is emitted. In general it is highly recommended to use `delay` operator
13162  * for any kind of delaying of values in the stream, while using `observeOn` to specify which scheduler should be used
13163  * for notification emissions in general.
13164  *
13165  * @example <caption>Ensure values in subscribe are called just before browser repaint.</caption>
13166  * const intervals = Rx.Observable.interval(10); // Intervals are scheduled
13167  *                                               // with async scheduler by default...
13168  *
13169  * intervals
13170  * .observeOn(Rx.Scheduler.animationFrame)       // ...but we will observe on animationFrame
13171  * .subscribe(val => {                           // scheduler to ensure smooth animation.
13172  *   someDiv.style.height = val + 'px';
13173  * });
13174  *
13175  * @see {@link delay}
13176  *
13177  * @param {IScheduler} scheduler Scheduler that will be used to reschedule notifications from source Observable.
13178  * @param {number} [delay] Number of milliseconds that states with what delay every notification should be rescheduled.
13179  * @return {Observable<T>} Observable that emits the same notifications as the source Observable,
13180  * but with provided scheduler.
13181  *
13182  * @method observeOn
13183  * @owner Observable
13184  */
13185 function observeOn(scheduler, delay) {
13186     if (delay === void 0) { delay = 0; }
13187     return function observeOnOperatorFunction(source) {
13188         return source.lift(new ObserveOnOperator(scheduler, delay));
13189     };
13190 }
13191 exports.observeOn = observeOn;
13192 var ObserveOnOperator = (function () {
13193     function ObserveOnOperator(scheduler, delay) {
13194         if (delay === void 0) { delay = 0; }
13195         this.scheduler = scheduler;
13196         this.delay = delay;
13197     }
13198     ObserveOnOperator.prototype.call = function (subscriber, source) {
13199         return source.subscribe(new ObserveOnSubscriber(subscriber, this.scheduler, this.delay));
13200     };
13201     return ObserveOnOperator;
13202 }());
13203 exports.ObserveOnOperator = ObserveOnOperator;
13204 /**
13205  * We need this JSDoc comment for affecting ESDoc.
13206  * @ignore
13207  * @extends {Ignored}
13208  */
13209 var ObserveOnSubscriber = (function (_super) {
13210     __extends(ObserveOnSubscriber, _super);
13211     function ObserveOnSubscriber(destination, scheduler, delay) {
13212         if (delay === void 0) { delay = 0; }
13213         _super.call(this, destination);
13214         this.scheduler = scheduler;
13215         this.delay = delay;
13216     }
13217     ObserveOnSubscriber.dispatch = function (arg) {
13218         var notification = arg.notification, destination = arg.destination;
13219         notification.observe(destination);
13220         this.unsubscribe();
13221     };
13222     ObserveOnSubscriber.prototype.scheduleMessage = function (notification) {
13223         this.add(this.scheduler.schedule(ObserveOnSubscriber.dispatch, this.delay, new ObserveOnMessage(notification, this.destination)));
13224     };
13225     ObserveOnSubscriber.prototype._next = function (value) {
13226         this.scheduleMessage(Notification_1.Notification.createNext(value));
13227     };
13228     ObserveOnSubscriber.prototype._error = function (err) {
13229         this.scheduleMessage(Notification_1.Notification.createError(err));
13230     };
13231     ObserveOnSubscriber.prototype._complete = function () {
13232         this.scheduleMessage(Notification_1.Notification.createComplete());
13233     };
13234     return ObserveOnSubscriber;
13235 }(Subscriber_1.Subscriber));
13236 exports.ObserveOnSubscriber = ObserveOnSubscriber;
13237 var ObserveOnMessage = (function () {
13238     function ObserveOnMessage(notification, destination) {
13239         this.notification = notification;
13240         this.destination = destination;
13241     }
13242     return ObserveOnMessage;
13243 }());
13244 exports.ObserveOnMessage = ObserveOnMessage;
13245
13246 },{"../Notification":28,"../Subscriber":36}],183:[function(require,module,exports){
13247 "use strict";
13248 var __extends = (this && this.__extends) || function (d, b) {
13249     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13250     function __() { this.constructor = d; }
13251     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13252 };
13253 var Subscriber_1 = require('../Subscriber');
13254 /**
13255  * Groups pairs of consecutive emissions together and emits them as an array of
13256  * two values.
13257  *
13258  * <span class="informal">Puts the current value and previous value together as
13259  * an array, and emits that.</span>
13260  *
13261  * <img src="./img/pairwise.png" width="100%">
13262  *
13263  * The Nth emission from the source Observable will cause the output Observable
13264  * to emit an array [(N-1)th, Nth] of the previous and the current value, as a
13265  * pair. For this reason, `pairwise` emits on the second and subsequent
13266  * emissions from the source Observable, but not on the first emission, because
13267  * there is no previous value in that case.
13268  *
13269  * @example <caption>On every click (starting from the second), emit the relative distance to the previous click</caption>
13270  * var clicks = Rx.Observable.fromEvent(document, 'click');
13271  * var pairs = clicks.pairwise();
13272  * var distance = pairs.map(pair => {
13273  *   var x0 = pair[0].clientX;
13274  *   var y0 = pair[0].clientY;
13275  *   var x1 = pair[1].clientX;
13276  *   var y1 = pair[1].clientY;
13277  *   return Math.sqrt(Math.pow(x0 - x1, 2) + Math.pow(y0 - y1, 2));
13278  * });
13279  * distance.subscribe(x => console.log(x));
13280  *
13281  * @see {@link buffer}
13282  * @see {@link bufferCount}
13283  *
13284  * @return {Observable<Array<T>>} An Observable of pairs (as arrays) of
13285  * consecutive values from the source Observable.
13286  * @method pairwise
13287  * @owner Observable
13288  */
13289 function pairwise() {
13290     return function (source) { return source.lift(new PairwiseOperator()); };
13291 }
13292 exports.pairwise = pairwise;
13293 var PairwiseOperator = (function () {
13294     function PairwiseOperator() {
13295     }
13296     PairwiseOperator.prototype.call = function (subscriber, source) {
13297         return source.subscribe(new PairwiseSubscriber(subscriber));
13298     };
13299     return PairwiseOperator;
13300 }());
13301 /**
13302  * We need this JSDoc comment for affecting ESDoc.
13303  * @ignore
13304  * @extends {Ignored}
13305  */
13306 var PairwiseSubscriber = (function (_super) {
13307     __extends(PairwiseSubscriber, _super);
13308     function PairwiseSubscriber(destination) {
13309         _super.call(this, destination);
13310         this.hasPrev = false;
13311     }
13312     PairwiseSubscriber.prototype._next = function (value) {
13313         if (this.hasPrev) {
13314             this.destination.next([this.prev, value]);
13315         }
13316         else {
13317             this.hasPrev = true;
13318         }
13319         this.prev = value;
13320     };
13321     return PairwiseSubscriber;
13322 }(Subscriber_1.Subscriber));
13323
13324 },{"../Subscriber":36}],184:[function(require,module,exports){
13325 "use strict";
13326 var map_1 = require('./map');
13327 /**
13328  * Maps each source value (an object) to its specified nested property.
13329  *
13330  * <span class="informal">Like {@link map}, but meant only for picking one of
13331  * the nested properties of every emitted object.</span>
13332  *
13333  * <img src="./img/pluck.png" width="100%">
13334  *
13335  * Given a list of strings describing a path to an object property, retrieves
13336  * the value of a specified nested property from all values in the source
13337  * Observable. If a property can't be resolved, it will return `undefined` for
13338  * that value.
13339  *
13340  * @example <caption>Map every click to the tagName of the clicked target element</caption>
13341  * var clicks = Rx.Observable.fromEvent(document, 'click');
13342  * var tagNames = clicks.pluck('target', 'tagName');
13343  * tagNames.subscribe(x => console.log(x));
13344  *
13345  * @see {@link map}
13346  *
13347  * @param {...string} properties The nested properties to pluck from each source
13348  * value (an object).
13349  * @return {Observable} A new Observable of property values from the source values.
13350  * @method pluck
13351  * @owner Observable
13352  */
13353 function pluck() {
13354     var properties = [];
13355     for (var _i = 0; _i < arguments.length; _i++) {
13356         properties[_i - 0] = arguments[_i];
13357     }
13358     var length = properties.length;
13359     if (length === 0) {
13360         throw new Error('list of properties cannot be empty.');
13361     }
13362     return function (source) { return map_1.map(plucker(properties, length))(source); };
13363 }
13364 exports.pluck = pluck;
13365 function plucker(props, length) {
13366     var mapper = function (x) {
13367         var currentProp = x;
13368         for (var i = 0; i < length; i++) {
13369             var p = currentProp[props[i]];
13370             if (typeof p !== 'undefined') {
13371                 currentProp = p;
13372             }
13373             else {
13374                 return undefined;
13375             }
13376         }
13377         return currentProp;
13378     };
13379     return mapper;
13380 }
13381
13382 },{"./map":177}],185:[function(require,module,exports){
13383 "use strict";
13384 var Subject_1 = require('../Subject');
13385 var multicast_1 = require('./multicast');
13386 /* tslint:enable:max-line-length */
13387 /**
13388  * Returns a ConnectableObservable, which is a variety of Observable that waits until its connect method is called
13389  * before it begins emitting items to those Observers that have subscribed to it.
13390  *
13391  * <img src="./img/publish.png" width="100%">
13392  *
13393  * @param {Function} [selector] - Optional selector function which can use the multicasted source sequence as many times
13394  * as needed, without causing multiple subscriptions to the source sequence.
13395  * Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
13396  * @return A ConnectableObservable that upon connection causes the source Observable to emit items to its Observers.
13397  * @method publish
13398  * @owner Observable
13399  */
13400 function publish(selector) {
13401     return selector ?
13402         multicast_1.multicast(function () { return new Subject_1.Subject(); }, selector) :
13403         multicast_1.multicast(new Subject_1.Subject());
13404 }
13405 exports.publish = publish;
13406
13407 },{"../Subject":34,"./multicast":181}],186:[function(require,module,exports){
13408 "use strict";
13409 var ReplaySubject_1 = require('../ReplaySubject');
13410 var multicast_1 = require('./multicast');
13411 /* tslint:enable:max-line-length */
13412 function publishReplay(bufferSize, windowTime, selectorOrScheduler, scheduler) {
13413     if (selectorOrScheduler && typeof selectorOrScheduler !== 'function') {
13414         scheduler = selectorOrScheduler;
13415     }
13416     var selector = typeof selectorOrScheduler === 'function' ? selectorOrScheduler : undefined;
13417     var subject = new ReplaySubject_1.ReplaySubject(bufferSize, windowTime, scheduler);
13418     return function (source) { return multicast_1.multicast(function () { return subject; }, selector)(source); };
13419 }
13420 exports.publishReplay = publishReplay;
13421
13422 },{"../ReplaySubject":32,"./multicast":181}],187:[function(require,module,exports){
13423 "use strict";
13424 var scan_1 = require('./scan');
13425 var takeLast_1 = require('./takeLast');
13426 var defaultIfEmpty_1 = require('./defaultIfEmpty');
13427 var pipe_1 = require('../util/pipe');
13428 /* tslint:enable:max-line-length */
13429 /**
13430  * Applies an accumulator function over the source Observable, and returns the
13431  * accumulated result when the source completes, given an optional seed value.
13432  *
13433  * <span class="informal">Combines together all values emitted on the source,
13434  * using an accumulator function that knows how to join a new source value into
13435  * the accumulation from the past.</span>
13436  *
13437  * <img src="./img/reduce.png" width="100%">
13438  *
13439  * Like
13440  * [Array.prototype.reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce),
13441  * `reduce` applies an `accumulator` function against an accumulation and each
13442  * value of the source Observable (from the past) to reduce it to a single
13443  * value, emitted on the output Observable. Note that `reduce` will only emit
13444  * one value, only when the source Observable completes. It is equivalent to
13445  * applying operator {@link scan} followed by operator {@link last}.
13446  *
13447  * Returns an Observable that applies a specified `accumulator` function to each
13448  * item emitted by the source Observable. If a `seed` value is specified, then
13449  * that value will be used as the initial value for the accumulator. If no seed
13450  * value is specified, the first item of the source is used as the seed.
13451  *
13452  * @example <caption>Count the number of click events that happened in 5 seconds</caption>
13453  * var clicksInFiveSeconds = Rx.Observable.fromEvent(document, 'click')
13454  *   .takeUntil(Rx.Observable.interval(5000));
13455  * var ones = clicksInFiveSeconds.mapTo(1);
13456  * var seed = 0;
13457  * var count = ones.reduce((acc, one) => acc + one, seed);
13458  * count.subscribe(x => console.log(x));
13459  *
13460  * @see {@link count}
13461  * @see {@link expand}
13462  * @see {@link mergeScan}
13463  * @see {@link scan}
13464  *
13465  * @param {function(acc: R, value: T, index: number): R} accumulator The accumulator function
13466  * called on each source value.
13467  * @param {R} [seed] The initial accumulation value.
13468  * @return {Observable<R>} An Observable that emits a single value that is the
13469  * result of accumulating the values emitted by the source Observable.
13470  * @method reduce
13471  * @owner Observable
13472  */
13473 function reduce(accumulator, seed) {
13474     // providing a seed of `undefined` *should* be valid and trigger
13475     // hasSeed! so don't use `seed !== undefined` checks!
13476     // For this reason, we have to check it here at the original call site
13477     // otherwise inside Operator/Subscriber we won't know if `undefined`
13478     // means they didn't provide anything or if they literally provided `undefined`
13479     if (arguments.length >= 2) {
13480         return function reduceOperatorFunctionWithSeed(source) {
13481             return pipe_1.pipe(scan_1.scan(accumulator, seed), takeLast_1.takeLast(1), defaultIfEmpty_1.defaultIfEmpty(seed))(source);
13482         };
13483     }
13484     return function reduceOperatorFunction(source) {
13485         return pipe_1.pipe(scan_1.scan(function (acc, value, index) {
13486             return accumulator(acc, value, index + 1);
13487         }), takeLast_1.takeLast(1))(source);
13488     };
13489 }
13490 exports.reduce = reduce;
13491
13492 },{"../util/pipe":236,"./defaultIfEmpty":168,"./scan":191,"./takeLast":199}],188:[function(require,module,exports){
13493 "use strict";
13494 var __extends = (this && this.__extends) || function (d, b) {
13495     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13496     function __() { this.constructor = d; }
13497     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13498 };
13499 var Subscriber_1 = require('../Subscriber');
13500 function refCount() {
13501     return function refCountOperatorFunction(source) {
13502         return source.lift(new RefCountOperator(source));
13503     };
13504 }
13505 exports.refCount = refCount;
13506 var RefCountOperator = (function () {
13507     function RefCountOperator(connectable) {
13508         this.connectable = connectable;
13509     }
13510     RefCountOperator.prototype.call = function (subscriber, source) {
13511         var connectable = this.connectable;
13512         connectable._refCount++;
13513         var refCounter = new RefCountSubscriber(subscriber, connectable);
13514         var subscription = source.subscribe(refCounter);
13515         if (!refCounter.closed) {
13516             refCounter.connection = connectable.connect();
13517         }
13518         return subscription;
13519     };
13520     return RefCountOperator;
13521 }());
13522 var RefCountSubscriber = (function (_super) {
13523     __extends(RefCountSubscriber, _super);
13524     function RefCountSubscriber(destination, connectable) {
13525         _super.call(this, destination);
13526         this.connectable = connectable;
13527     }
13528     RefCountSubscriber.prototype._unsubscribe = function () {
13529         var connectable = this.connectable;
13530         if (!connectable) {
13531             this.connection = null;
13532             return;
13533         }
13534         this.connectable = null;
13535         var refCount = connectable._refCount;
13536         if (refCount <= 0) {
13537             this.connection = null;
13538             return;
13539         }
13540         connectable._refCount = refCount - 1;
13541         if (refCount > 1) {
13542             this.connection = null;
13543             return;
13544         }
13545         ///
13546         // Compare the local RefCountSubscriber's connection Subscription to the
13547         // connection Subscription on the shared ConnectableObservable. In cases
13548         // where the ConnectableObservable source synchronously emits values, and
13549         // the RefCountSubscriber's downstream Observers synchronously unsubscribe,
13550         // execution continues to here before the RefCountOperator has a chance to
13551         // supply the RefCountSubscriber with the shared connection Subscription.
13552         // For example:
13553         // ```
13554         // Observable.range(0, 10)
13555         //   .publish()
13556         //   .refCount()
13557         //   .take(5)
13558         //   .subscribe();
13559         // ```
13560         // In order to account for this case, RefCountSubscriber should only dispose
13561         // the ConnectableObservable's shared connection Subscription if the
13562         // connection Subscription exists, *and* either:
13563         //   a. RefCountSubscriber doesn't have a reference to the shared connection
13564         //      Subscription yet, or,
13565         //   b. RefCountSubscriber's connection Subscription reference is identical
13566         //      to the shared connection Subscription
13567         ///
13568         var connection = this.connection;
13569         var sharedConnection = connectable._connection;
13570         this.connection = null;
13571         if (sharedConnection && (!connection || sharedConnection === connection)) {
13572             sharedConnection.unsubscribe();
13573         }
13574     };
13575     return RefCountSubscriber;
13576 }(Subscriber_1.Subscriber));
13577
13578 },{"../Subscriber":36}],189:[function(require,module,exports){
13579 "use strict";
13580 var __extends = (this && this.__extends) || function (d, b) {
13581     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13582     function __() { this.constructor = d; }
13583     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13584 };
13585 var Subscriber_1 = require('../Subscriber');
13586 /**
13587  * Returns an Observable that mirrors the source Observable with the exception of an `error`. If the source Observable
13588  * calls `error`, this method will resubscribe to the source Observable for a maximum of `count` resubscriptions (given
13589  * as a number parameter) rather than propagating the `error` call.
13590  *
13591  * <img src="./img/retry.png" width="100%">
13592  *
13593  * Any and all items emitted by the source Observable will be emitted by the resulting Observable, even those emitted
13594  * during failed subscriptions. For example, if an Observable fails at first but emits [1, 2] then succeeds the second
13595  * time and emits: [1, 2, 3, 4, 5] then the complete stream of emissions and notifications
13596  * would be: [1, 2, 1, 2, 3, 4, 5, `complete`].
13597  * @param {number} count - Number of retry attempts before failing.
13598  * @return {Observable} The source Observable modified with the retry logic.
13599  * @method retry
13600  * @owner Observable
13601  */
13602 function retry(count) {
13603     if (count === void 0) { count = -1; }
13604     return function (source) { return source.lift(new RetryOperator(count, source)); };
13605 }
13606 exports.retry = retry;
13607 var RetryOperator = (function () {
13608     function RetryOperator(count, source) {
13609         this.count = count;
13610         this.source = source;
13611     }
13612     RetryOperator.prototype.call = function (subscriber, source) {
13613         return source.subscribe(new RetrySubscriber(subscriber, this.count, this.source));
13614     };
13615     return RetryOperator;
13616 }());
13617 /**
13618  * We need this JSDoc comment for affecting ESDoc.
13619  * @ignore
13620  * @extends {Ignored}
13621  */
13622 var RetrySubscriber = (function (_super) {
13623     __extends(RetrySubscriber, _super);
13624     function RetrySubscriber(destination, count, source) {
13625         _super.call(this, destination);
13626         this.count = count;
13627         this.source = source;
13628     }
13629     RetrySubscriber.prototype.error = function (err) {
13630         if (!this.isStopped) {
13631             var _a = this, source = _a.source, count = _a.count;
13632             if (count === 0) {
13633                 return _super.prototype.error.call(this, err);
13634             }
13635             else if (count > -1) {
13636                 this.count = count - 1;
13637             }
13638             source.subscribe(this._unsubscribeAndRecycle());
13639         }
13640     };
13641     return RetrySubscriber;
13642 }(Subscriber_1.Subscriber));
13643
13644 },{"../Subscriber":36}],190:[function(require,module,exports){
13645 "use strict";
13646 var __extends = (this && this.__extends) || function (d, b) {
13647     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13648     function __() { this.constructor = d; }
13649     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13650 };
13651 var OuterSubscriber_1 = require('../OuterSubscriber');
13652 var subscribeToResult_1 = require('../util/subscribeToResult');
13653 /**
13654  * Emits the most recently emitted value from the source Observable whenever
13655  * another Observable, the `notifier`, emits.
13656  *
13657  * <span class="informal">It's like {@link sampleTime}, but samples whenever
13658  * the `notifier` Observable emits something.</span>
13659  *
13660  * <img src="./img/sample.png" width="100%">
13661  *
13662  * Whenever the `notifier` Observable emits a value or completes, `sample`
13663  * looks at the source Observable and emits whichever value it has most recently
13664  * emitted since the previous sampling, unless the source has not emitted
13665  * anything since the previous sampling. The `notifier` is subscribed to as soon
13666  * as the output Observable is subscribed.
13667  *
13668  * @example <caption>On every click, sample the most recent "seconds" timer</caption>
13669  * var seconds = Rx.Observable.interval(1000);
13670  * var clicks = Rx.Observable.fromEvent(document, 'click');
13671  * var result = seconds.sample(clicks);
13672  * result.subscribe(x => console.log(x));
13673  *
13674  * @see {@link audit}
13675  * @see {@link debounce}
13676  * @see {@link sampleTime}
13677  * @see {@link throttle}
13678  *
13679  * @param {Observable<any>} notifier The Observable to use for sampling the
13680  * source Observable.
13681  * @return {Observable<T>} An Observable that emits the results of sampling the
13682  * values emitted by the source Observable whenever the notifier Observable
13683  * emits value or completes.
13684  * @method sample
13685  * @owner Observable
13686  */
13687 function sample(notifier) {
13688     return function (source) { return source.lift(new SampleOperator(notifier)); };
13689 }
13690 exports.sample = sample;
13691 var SampleOperator = (function () {
13692     function SampleOperator(notifier) {
13693         this.notifier = notifier;
13694     }
13695     SampleOperator.prototype.call = function (subscriber, source) {
13696         var sampleSubscriber = new SampleSubscriber(subscriber);
13697         var subscription = source.subscribe(sampleSubscriber);
13698         subscription.add(subscribeToResult_1.subscribeToResult(sampleSubscriber, this.notifier));
13699         return subscription;
13700     };
13701     return SampleOperator;
13702 }());
13703 /**
13704  * We need this JSDoc comment for affecting ESDoc.
13705  * @ignore
13706  * @extends {Ignored}
13707  */
13708 var SampleSubscriber = (function (_super) {
13709     __extends(SampleSubscriber, _super);
13710     function SampleSubscriber() {
13711         _super.apply(this, arguments);
13712         this.hasValue = false;
13713     }
13714     SampleSubscriber.prototype._next = function (value) {
13715         this.value = value;
13716         this.hasValue = true;
13717     };
13718     SampleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
13719         this.emitValue();
13720     };
13721     SampleSubscriber.prototype.notifyComplete = function () {
13722         this.emitValue();
13723     };
13724     SampleSubscriber.prototype.emitValue = function () {
13725         if (this.hasValue) {
13726             this.hasValue = false;
13727             this.destination.next(this.value);
13728         }
13729     };
13730     return SampleSubscriber;
13731 }(OuterSubscriber_1.OuterSubscriber));
13732
13733 },{"../OuterSubscriber":31,"../util/subscribeToResult":238}],191:[function(require,module,exports){
13734 "use strict";
13735 var __extends = (this && this.__extends) || function (d, b) {
13736     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13737     function __() { this.constructor = d; }
13738     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13739 };
13740 var Subscriber_1 = require('../Subscriber');
13741 /* tslint:enable:max-line-length */
13742 /**
13743  * Applies an accumulator function over the source Observable, and returns each
13744  * intermediate result, with an optional seed value.
13745  *
13746  * <span class="informal">It's like {@link reduce}, but emits the current
13747  * accumulation whenever the source emits a value.</span>
13748  *
13749  * <img src="./img/scan.png" width="100%">
13750  *
13751  * Combines together all values emitted on the source, using an accumulator
13752  * function that knows how to join a new source value into the accumulation from
13753  * the past. Is similar to {@link reduce}, but emits the intermediate
13754  * accumulations.
13755  *
13756  * Returns an Observable that applies a specified `accumulator` function to each
13757  * item emitted by the source Observable. If a `seed` value is specified, then
13758  * that value will be used as the initial value for the accumulator. If no seed
13759  * value is specified, the first item of the source is used as the seed.
13760  *
13761  * @example <caption>Count the number of click events</caption>
13762  * var clicks = Rx.Observable.fromEvent(document, 'click');
13763  * var ones = clicks.mapTo(1);
13764  * var seed = 0;
13765  * var count = ones.scan((acc, one) => acc + one, seed);
13766  * count.subscribe(x => console.log(x));
13767  *
13768  * @see {@link expand}
13769  * @see {@link mergeScan}
13770  * @see {@link reduce}
13771  *
13772  * @param {function(acc: R, value: T, index: number): R} accumulator
13773  * The accumulator function called on each source value.
13774  * @param {T|R} [seed] The initial accumulation value.
13775  * @return {Observable<R>} An observable of the accumulated values.
13776  * @method scan
13777  * @owner Observable
13778  */
13779 function scan(accumulator, seed) {
13780     var hasSeed = false;
13781     // providing a seed of `undefined` *should* be valid and trigger
13782     // hasSeed! so don't use `seed !== undefined` checks!
13783     // For this reason, we have to check it here at the original call site
13784     // otherwise inside Operator/Subscriber we won't know if `undefined`
13785     // means they didn't provide anything or if they literally provided `undefined`
13786     if (arguments.length >= 2) {
13787         hasSeed = true;
13788     }
13789     return function scanOperatorFunction(source) {
13790         return source.lift(new ScanOperator(accumulator, seed, hasSeed));
13791     };
13792 }
13793 exports.scan = scan;
13794 var ScanOperator = (function () {
13795     function ScanOperator(accumulator, seed, hasSeed) {
13796         if (hasSeed === void 0) { hasSeed = false; }
13797         this.accumulator = accumulator;
13798         this.seed = seed;
13799         this.hasSeed = hasSeed;
13800     }
13801     ScanOperator.prototype.call = function (subscriber, source) {
13802         return source.subscribe(new ScanSubscriber(subscriber, this.accumulator, this.seed, this.hasSeed));
13803     };
13804     return ScanOperator;
13805 }());
13806 /**
13807  * We need this JSDoc comment for affecting ESDoc.
13808  * @ignore
13809  * @extends {Ignored}
13810  */
13811 var ScanSubscriber = (function (_super) {
13812     __extends(ScanSubscriber, _super);
13813     function ScanSubscriber(destination, accumulator, _seed, hasSeed) {
13814         _super.call(this, destination);
13815         this.accumulator = accumulator;
13816         this._seed = _seed;
13817         this.hasSeed = hasSeed;
13818         this.index = 0;
13819     }
13820     Object.defineProperty(ScanSubscriber.prototype, "seed", {
13821         get: function () {
13822             return this._seed;
13823         },
13824         set: function (value) {
13825             this.hasSeed = true;
13826             this._seed = value;
13827         },
13828         enumerable: true,
13829         configurable: true
13830     });
13831     ScanSubscriber.prototype._next = function (value) {
13832         if (!this.hasSeed) {
13833             this.seed = value;
13834             this.destination.next(value);
13835         }
13836         else {
13837             return this._tryNext(value);
13838         }
13839     };
13840     ScanSubscriber.prototype._tryNext = function (value) {
13841         var index = this.index++;
13842         var result;
13843         try {
13844             result = this.accumulator(this.seed, value, index);
13845         }
13846         catch (err) {
13847             this.destination.error(err);
13848         }
13849         this.seed = result;
13850         this.destination.next(result);
13851     };
13852     return ScanSubscriber;
13853 }(Subscriber_1.Subscriber));
13854
13855 },{"../Subscriber":36}],192:[function(require,module,exports){
13856 "use strict";
13857 var multicast_1 = require('./multicast');
13858 var refCount_1 = require('./refCount');
13859 var Subject_1 = require('../Subject');
13860 function shareSubjectFactory() {
13861     return new Subject_1.Subject();
13862 }
13863 /**
13864  * Returns a new Observable that multicasts (shares) the original Observable. As long as there is at least one
13865  * Subscriber this Observable will be subscribed and emitting data. When all subscribers have unsubscribed it will
13866  * unsubscribe from the source Observable. Because the Observable is multicasting it makes the stream `hot`.
13867  * This is an alias for .multicast(() => new Subject()).refCount().
13868  *
13869  * <img src="./img/share.png" width="100%">
13870  *
13871  * @return {Observable<T>} An Observable that upon connection causes the source Observable to emit items to its Observers.
13872  * @method share
13873  * @owner Observable
13874  */
13875 function share() {
13876     return function (source) { return refCount_1.refCount()(multicast_1.multicast(shareSubjectFactory)(source)); };
13877 }
13878 exports.share = share;
13879 ;
13880
13881 },{"../Subject":34,"./multicast":181,"./refCount":188}],193:[function(require,module,exports){
13882 "use strict";
13883 var __extends = (this && this.__extends) || function (d, b) {
13884     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13885     function __() { this.constructor = d; }
13886     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13887 };
13888 var Subscriber_1 = require('../Subscriber');
13889 /**
13890  * Returns an Observable that skips the first `count` items emitted by the source Observable.
13891  *
13892  * <img src="./img/skip.png" width="100%">
13893  *
13894  * @param {Number} count - The number of times, items emitted by source Observable should be skipped.
13895  * @return {Observable} An Observable that skips values emitted by the source Observable.
13896  *
13897  * @method skip
13898  * @owner Observable
13899  */
13900 function skip(count) {
13901     return function (source) { return source.lift(new SkipOperator(count)); };
13902 }
13903 exports.skip = skip;
13904 var SkipOperator = (function () {
13905     function SkipOperator(total) {
13906         this.total = total;
13907     }
13908     SkipOperator.prototype.call = function (subscriber, source) {
13909         return source.subscribe(new SkipSubscriber(subscriber, this.total));
13910     };
13911     return SkipOperator;
13912 }());
13913 /**
13914  * We need this JSDoc comment for affecting ESDoc.
13915  * @ignore
13916  * @extends {Ignored}
13917  */
13918 var SkipSubscriber = (function (_super) {
13919     __extends(SkipSubscriber, _super);
13920     function SkipSubscriber(destination, total) {
13921         _super.call(this, destination);
13922         this.total = total;
13923         this.count = 0;
13924     }
13925     SkipSubscriber.prototype._next = function (x) {
13926         if (++this.count > this.total) {
13927             this.destination.next(x);
13928         }
13929     };
13930     return SkipSubscriber;
13931 }(Subscriber_1.Subscriber));
13932
13933 },{"../Subscriber":36}],194:[function(require,module,exports){
13934 "use strict";
13935 var __extends = (this && this.__extends) || function (d, b) {
13936     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
13937     function __() { this.constructor = d; }
13938     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13939 };
13940 var OuterSubscriber_1 = require('../OuterSubscriber');
13941 var subscribeToResult_1 = require('../util/subscribeToResult');
13942 /**
13943  * Returns an Observable that skips items emitted by the source Observable until a second Observable emits an item.
13944  *
13945  * <img src="./img/skipUntil.png" width="100%">
13946  *
13947  * @param {Observable} notifier - The second Observable that has to emit an item before the source Observable's elements begin to
13948  * be mirrored by the resulting Observable.
13949  * @return {Observable<T>} An Observable that skips items from the source Observable until the second Observable emits
13950  * an item, then emits the remaining items.
13951  * @method skipUntil
13952  * @owner Observable
13953  */
13954 function skipUntil(notifier) {
13955     return function (source) { return source.lift(new SkipUntilOperator(notifier)); };
13956 }
13957 exports.skipUntil = skipUntil;
13958 var SkipUntilOperator = (function () {
13959     function SkipUntilOperator(notifier) {
13960         this.notifier = notifier;
13961     }
13962     SkipUntilOperator.prototype.call = function (subscriber, source) {
13963         return source.subscribe(new SkipUntilSubscriber(subscriber, this.notifier));
13964     };
13965     return SkipUntilOperator;
13966 }());
13967 /**
13968  * We need this JSDoc comment for affecting ESDoc.
13969  * @ignore
13970  * @extends {Ignored}
13971  */
13972 var SkipUntilSubscriber = (function (_super) {
13973     __extends(SkipUntilSubscriber, _super);
13974     function SkipUntilSubscriber(destination, notifier) {
13975         _super.call(this, destination);
13976         this.hasValue = false;
13977         this.isInnerStopped = false;
13978         this.add(subscribeToResult_1.subscribeToResult(this, notifier));
13979     }
13980     SkipUntilSubscriber.prototype._next = function (value) {
13981         if (this.hasValue) {
13982             _super.prototype._next.call(this, value);
13983         }
13984     };
13985     SkipUntilSubscriber.prototype._complete = function () {
13986         if (this.isInnerStopped) {
13987             _super.prototype._complete.call(this);
13988         }
13989         else {
13990             this.unsubscribe();
13991         }
13992     };
13993     SkipUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
13994         this.hasValue = true;
13995     };
13996     SkipUntilSubscriber.prototype.notifyComplete = function () {
13997         this.isInnerStopped = true;
13998         if (this.isStopped) {
13999             _super.prototype._complete.call(this);
14000         }
14001     };
14002     return SkipUntilSubscriber;
14003 }(OuterSubscriber_1.OuterSubscriber));
14004
14005 },{"../OuterSubscriber":31,"../util/subscribeToResult":238}],195:[function(require,module,exports){
14006 "use strict";
14007 var __extends = (this && this.__extends) || function (d, b) {
14008     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
14009     function __() { this.constructor = d; }
14010     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14011 };
14012 var Subscriber_1 = require('../Subscriber');
14013 /**
14014  * Returns an Observable that skips all items emitted by the source Observable as long as a specified condition holds
14015  * true, but emits all further source items as soon as the condition becomes false.
14016  *
14017  * <img src="./img/skipWhile.png" width="100%">
14018  *
14019  * @param {Function} predicate - A function to test each item emitted from the source Observable.
14020  * @return {Observable<T>} An Observable that begins emitting items emitted by the source Observable when the
14021  * specified predicate becomes false.
14022  * @method skipWhile
14023  * @owner Observable
14024  */
14025 function skipWhile(predicate) {
14026     return function (source) { return source.lift(new SkipWhileOperator(predicate)); };
14027 }
14028 exports.skipWhile = skipWhile;
14029 var SkipWhileOperator = (function () {
14030     function SkipWhileOperator(predicate) {
14031         this.predicate = predicate;
14032     }
14033     SkipWhileOperator.prototype.call = function (subscriber, source) {
14034         return source.subscribe(new SkipWhileSubscriber(subscriber, this.predicate));
14035     };
14036     return SkipWhileOperator;
14037 }());
14038 /**
14039  * We need this JSDoc comment for affecting ESDoc.
14040  * @ignore
14041  * @extends {Ignored}
14042  */
14043 var SkipWhileSubscriber = (function (_super) {
14044     __extends(SkipWhileSubscriber, _super);
14045     function SkipWhileSubscriber(destination, predicate) {
14046         _super.call(this, destination);
14047         this.predicate = predicate;
14048         this.skipping = true;
14049         this.index = 0;
14050     }
14051     SkipWhileSubscriber.prototype._next = function (value) {
14052         var destination = this.destination;
14053         if (this.skipping) {
14054             this.tryCallPredicate(value);
14055         }
14056         if (!this.skipping) {
14057             destination.next(value);
14058         }
14059     };
14060     SkipWhileSubscriber.prototype.tryCallPredicate = function (value) {
14061         try {
14062             var result = this.predicate(value, this.index++);
14063             this.skipping = Boolean(result);
14064         }
14065         catch (err) {
14066             this.destination.error(err);
14067         }
14068     };
14069     return SkipWhileSubscriber;
14070 }(Subscriber_1.Subscriber));
14071
14072 },{"../Subscriber":36}],196:[function(require,module,exports){
14073 "use strict";
14074 var ArrayObservable_1 = require('../observable/ArrayObservable');
14075 var ScalarObservable_1 = require('../observable/ScalarObservable');
14076 var EmptyObservable_1 = require('../observable/EmptyObservable');
14077 var concat_1 = require('../observable/concat');
14078 var isScheduler_1 = require('../util/isScheduler');
14079 /* tslint:enable:max-line-length */
14080 /**
14081  * Returns an Observable that emits the items you specify as arguments before it begins to emit
14082  * items emitted by the source Observable.
14083  *
14084  * <img src="./img/startWith.png" width="100%">
14085  *
14086  * @param {...T} values - Items you want the modified Observable to emit first.
14087  * @param {Scheduler} [scheduler] - A {@link IScheduler} to use for scheduling
14088  * the emissions of the `next` notifications.
14089  * @return {Observable} An Observable that emits the items in the specified Iterable and then emits the items
14090  * emitted by the source Observable.
14091  * @method startWith
14092  * @owner Observable
14093  */
14094 function startWith() {
14095     var array = [];
14096     for (var _i = 0; _i < arguments.length; _i++) {
14097         array[_i - 0] = arguments[_i];
14098     }
14099     return function (source) {
14100         var scheduler = array[array.length - 1];
14101         if (isScheduler_1.isScheduler(scheduler)) {
14102             array.pop();
14103         }
14104         else {
14105             scheduler = null;
14106         }
14107         var len = array.length;
14108         if (len === 1) {
14109             return concat_1.concat(new ScalarObservable_1.ScalarObservable(array[0], scheduler), source);
14110         }
14111         else if (len > 1) {
14112             return concat_1.concat(new ArrayObservable_1.ArrayObservable(array, scheduler), source);
14113         }
14114         else {
14115             return concat_1.concat(new EmptyObservable_1.EmptyObservable(scheduler), source);
14116         }
14117     };
14118 }
14119 exports.startWith = startWith;
14120
14121 },{"../observable/ArrayObservable":93,"../observable/EmptyObservable":96,"../observable/ScalarObservable":102,"../observable/concat":105,"../util/isScheduler":234}],197:[function(require,module,exports){
14122 "use strict";
14123 var __extends = (this && this.__extends) || function (d, b) {
14124     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
14125     function __() { this.constructor = d; }
14126     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14127 };
14128 var OuterSubscriber_1 = require('../OuterSubscriber');
14129 var subscribeToResult_1 = require('../util/subscribeToResult');
14130 /* tslint:enable:max-line-length */
14131 /**
14132  * Projects each source value to an Observable which is merged in the output
14133  * Observable, emitting values only from the most recently projected Observable.
14134  *
14135  * <span class="informal">Maps each value to an Observable, then flattens all of
14136  * these inner Observables using {@link switch}.</span>
14137  *
14138  * <img src="./img/switchMap.png" width="100%">
14139  *
14140  * Returns an Observable that emits items based on applying a function that you
14141  * supply to each item emitted by the source Observable, where that function
14142  * returns an (so-called "inner") Observable. Each time it observes one of these
14143  * inner Observables, the output Observable begins emitting the items emitted by
14144  * that inner Observable. When a new inner Observable is emitted, `switchMap`
14145  * stops emitting items from the earlier-emitted inner Observable and begins
14146  * emitting items from the new one. It continues to behave like this for
14147  * subsequent inner Observables.
14148  *
14149  * @example <caption>Rerun an interval Observable on every click event</caption>
14150  * var clicks = Rx.Observable.fromEvent(document, 'click');
14151  * var result = clicks.switchMap((ev) => Rx.Observable.interval(1000));
14152  * result.subscribe(x => console.log(x));
14153  *
14154  * @see {@link concatMap}
14155  * @see {@link exhaustMap}
14156  * @see {@link mergeMap}
14157  * @see {@link switch}
14158  * @see {@link switchMapTo}
14159  *
14160  * @param {function(value: T, ?index: number): ObservableInput} project A function
14161  * that, when applied to an item emitted by the source Observable, returns an
14162  * Observable.
14163  * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
14164  * A function to produce the value on the output Observable based on the values
14165  * and the indices of the source (outer) emission and the inner Observable
14166  * emission. The arguments passed to this function are:
14167  * - `outerValue`: the value that came from the source
14168  * - `innerValue`: the value that came from the projected Observable
14169  * - `outerIndex`: the "index" of the value that came from the source
14170  * - `innerIndex`: the "index" of the value from the projected Observable
14171  * @return {Observable} An Observable that emits the result of applying the
14172  * projection function (and the optional `resultSelector`) to each item emitted
14173  * by the source Observable and taking only the values from the most recently
14174  * projected inner Observable.
14175  * @method switchMap
14176  * @owner Observable
14177  */
14178 function switchMap(project, resultSelector) {
14179     return function switchMapOperatorFunction(source) {
14180         return source.lift(new SwitchMapOperator(project, resultSelector));
14181     };
14182 }
14183 exports.switchMap = switchMap;
14184 var SwitchMapOperator = (function () {
14185     function SwitchMapOperator(project, resultSelector) {
14186         this.project = project;
14187         this.resultSelector = resultSelector;
14188     }
14189     SwitchMapOperator.prototype.call = function (subscriber, source) {
14190         return source.subscribe(new SwitchMapSubscriber(subscriber, this.project, this.resultSelector));
14191     };
14192     return SwitchMapOperator;
14193 }());
14194 /**
14195  * We need this JSDoc comment for affecting ESDoc.
14196  * @ignore
14197  * @extends {Ignored}
14198  */
14199 var SwitchMapSubscriber = (function (_super) {
14200     __extends(SwitchMapSubscriber, _super);
14201     function SwitchMapSubscriber(destination, project, resultSelector) {
14202         _super.call(this, destination);
14203         this.project = project;
14204         this.resultSelector = resultSelector;
14205         this.index = 0;
14206     }
14207     SwitchMapSubscriber.prototype._next = function (value) {
14208         var result;
14209         var index = this.index++;
14210         try {
14211             result = this.project(value, index);
14212         }
14213         catch (error) {
14214             this.destination.error(error);
14215             return;
14216         }
14217         this._innerSub(result, value, index);
14218     };
14219     SwitchMapSubscriber.prototype._innerSub = function (result, value, index) {
14220         var innerSubscription = this.innerSubscription;
14221         if (innerSubscription) {
14222             innerSubscription.unsubscribe();
14223         }
14224         this.add(this.innerSubscription = subscribeToResult_1.subscribeToResult(this, result, value, index));
14225     };
14226     SwitchMapSubscriber.prototype._complete = function () {
14227         var innerSubscription = this.innerSubscription;
14228         if (!innerSubscription || innerSubscription.closed) {
14229             _super.prototype._complete.call(this);
14230         }
14231     };
14232     SwitchMapSubscriber.prototype._unsubscribe = function () {
14233         this.innerSubscription = null;
14234     };
14235     SwitchMapSubscriber.prototype.notifyComplete = function (innerSub) {
14236         this.remove(innerSub);
14237         this.innerSubscription = null;
14238         if (this.isStopped) {
14239             _super.prototype._complete.call(this);
14240         }
14241     };
14242     SwitchMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
14243         if (this.resultSelector) {
14244             this._tryNotifyNext(outerValue, innerValue, outerIndex, innerIndex);
14245         }
14246         else {
14247             this.destination.next(innerValue);
14248         }
14249     };
14250     SwitchMapSubscriber.prototype._tryNotifyNext = function (outerValue, innerValue, outerIndex, innerIndex) {
14251         var result;
14252         try {
14253             result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex);
14254         }
14255         catch (err) {
14256             this.destination.error(err);
14257             return;
14258         }
14259         this.destination.next(result);
14260     };
14261     return SwitchMapSubscriber;
14262 }(OuterSubscriber_1.OuterSubscriber));
14263
14264 },{"../OuterSubscriber":31,"../util/subscribeToResult":238}],198:[function(require,module,exports){
14265 "use strict";
14266 var __extends = (this && this.__extends) || function (d, b) {
14267     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
14268     function __() { this.constructor = d; }
14269     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14270 };
14271 var Subscriber_1 = require('../Subscriber');
14272 var ArgumentOutOfRangeError_1 = require('../util/ArgumentOutOfRangeError');
14273 var EmptyObservable_1 = require('../observable/EmptyObservable');
14274 /**
14275  * Emits only the first `count` values emitted by the source Observable.
14276  *
14277  * <span class="informal">Takes the first `count` values from the source, then
14278  * completes.</span>
14279  *
14280  * <img src="./img/take.png" width="100%">
14281  *
14282  * `take` returns an Observable that emits only the first `count` values emitted
14283  * by the source Observable. If the source emits fewer than `count` values then
14284  * all of its values are emitted. After that, it completes, regardless if the
14285  * source completes.
14286  *
14287  * @example <caption>Take the first 5 seconds of an infinite 1-second interval Observable</caption>
14288  * var interval = Rx.Observable.interval(1000);
14289  * var five = interval.take(5);
14290  * five.subscribe(x => console.log(x));
14291  *
14292  * @see {@link takeLast}
14293  * @see {@link takeUntil}
14294  * @see {@link takeWhile}
14295  * @see {@link skip}
14296  *
14297  * @throws {ArgumentOutOfRangeError} When using `take(i)`, it delivers an
14298  * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0`.
14299  *
14300  * @param {number} count The maximum number of `next` values to emit.
14301  * @return {Observable<T>} An Observable that emits only the first `count`
14302  * values emitted by the source Observable, or all of the values from the source
14303  * if the source emits fewer than `count` values.
14304  * @method take
14305  * @owner Observable
14306  */
14307 function take(count) {
14308     return function (source) {
14309         if (count === 0) {
14310             return new EmptyObservable_1.EmptyObservable();
14311         }
14312         else {
14313             return source.lift(new TakeOperator(count));
14314         }
14315     };
14316 }
14317 exports.take = take;
14318 var TakeOperator = (function () {
14319     function TakeOperator(total) {
14320         this.total = total;
14321         if (this.total < 0) {
14322             throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError;
14323         }
14324     }
14325     TakeOperator.prototype.call = function (subscriber, source) {
14326         return source.subscribe(new TakeSubscriber(subscriber, this.total));
14327     };
14328     return TakeOperator;
14329 }());
14330 /**
14331  * We need this JSDoc comment for affecting ESDoc.
14332  * @ignore
14333  * @extends {Ignored}
14334  */
14335 var TakeSubscriber = (function (_super) {
14336     __extends(TakeSubscriber, _super);
14337     function TakeSubscriber(destination, total) {
14338         _super.call(this, destination);
14339         this.total = total;
14340         this.count = 0;
14341     }
14342     TakeSubscriber.prototype._next = function (value) {
14343         var total = this.total;
14344         var count = ++this.count;
14345         if (count <= total) {
14346             this.destination.next(value);
14347             if (count === total) {
14348                 this.destination.complete();
14349                 this.unsubscribe();
14350             }
14351         }
14352     };
14353     return TakeSubscriber;
14354 }(Subscriber_1.Subscriber));
14355
14356 },{"../Subscriber":36,"../observable/EmptyObservable":96,"../util/ArgumentOutOfRangeError":219}],199:[function(require,module,exports){
14357 "use strict";
14358 var __extends = (this && this.__extends) || function (d, b) {
14359     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
14360     function __() { this.constructor = d; }
14361     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14362 };
14363 var Subscriber_1 = require('../Subscriber');
14364 var ArgumentOutOfRangeError_1 = require('../util/ArgumentOutOfRangeError');
14365 var EmptyObservable_1 = require('../observable/EmptyObservable');
14366 /**
14367  * Emits only the last `count` values emitted by the source Observable.
14368  *
14369  * <span class="informal">Remembers the latest `count` values, then emits those
14370  * only when the source completes.</span>
14371  *
14372  * <img src="./img/takeLast.png" width="100%">
14373  *
14374  * `takeLast` returns an Observable that emits at most the last `count` values
14375  * emitted by the source Observable. If the source emits fewer than `count`
14376  * values then all of its values are emitted. This operator must wait until the
14377  * `complete` notification emission from the source in order to emit the `next`
14378  * values on the output Observable, because otherwise it is impossible to know
14379  * whether or not more values will be emitted on the source. For this reason,
14380  * all values are emitted synchronously, followed by the complete notification.
14381  *
14382  * @example <caption>Take the last 3 values of an Observable with many values</caption>
14383  * var many = Rx.Observable.range(1, 100);
14384  * var lastThree = many.takeLast(3);
14385  * lastThree.subscribe(x => console.log(x));
14386  *
14387  * @see {@link take}
14388  * @see {@link takeUntil}
14389  * @see {@link takeWhile}
14390  * @see {@link skip}
14391  *
14392  * @throws {ArgumentOutOfRangeError} When using `takeLast(i)`, it delivers an
14393  * ArgumentOutOrRangeError to the Observer's `error` callback if `i < 0`.
14394  *
14395  * @param {number} count The maximum number of values to emit from the end of
14396  * the sequence of values emitted by the source Observable.
14397  * @return {Observable<T>} An Observable that emits at most the last count
14398  * values emitted by the source Observable.
14399  * @method takeLast
14400  * @owner Observable
14401  */
14402 function takeLast(count) {
14403     return function takeLastOperatorFunction(source) {
14404         if (count === 0) {
14405             return new EmptyObservable_1.EmptyObservable();
14406         }
14407         else {
14408             return source.lift(new TakeLastOperator(count));
14409         }
14410     };
14411 }
14412 exports.takeLast = takeLast;
14413 var TakeLastOperator = (function () {
14414     function TakeLastOperator(total) {
14415         this.total = total;
14416         if (this.total < 0) {
14417             throw new ArgumentOutOfRangeError_1.ArgumentOutOfRangeError;
14418         }
14419     }
14420     TakeLastOperator.prototype.call = function (subscriber, source) {
14421         return source.subscribe(new TakeLastSubscriber(subscriber, this.total));
14422     };
14423     return TakeLastOperator;
14424 }());
14425 /**
14426  * We need this JSDoc comment for affecting ESDoc.
14427  * @ignore
14428  * @extends {Ignored}
14429  */
14430 var TakeLastSubscriber = (function (_super) {
14431     __extends(TakeLastSubscriber, _super);
14432     function TakeLastSubscriber(destination, total) {
14433         _super.call(this, destination);
14434         this.total = total;
14435         this.ring = new Array();
14436         this.count = 0;
14437     }
14438     TakeLastSubscriber.prototype._next = function (value) {
14439         var ring = this.ring;
14440         var total = this.total;
14441         var count = this.count++;
14442         if (ring.length < total) {
14443             ring.push(value);
14444         }
14445         else {
14446             var index = count % total;
14447             ring[index] = value;
14448         }
14449     };
14450     TakeLastSubscriber.prototype._complete = function () {
14451         var destination = this.destination;
14452         var count = this.count;
14453         if (count > 0) {
14454             var total = this.count >= this.total ? this.total : this.count;
14455             var ring = this.ring;
14456             for (var i = 0; i < total; i++) {
14457                 var idx = (count++) % total;
14458                 destination.next(ring[idx]);
14459             }
14460         }
14461         destination.complete();
14462     };
14463     return TakeLastSubscriber;
14464 }(Subscriber_1.Subscriber));
14465
14466 },{"../Subscriber":36,"../observable/EmptyObservable":96,"../util/ArgumentOutOfRangeError":219}],200:[function(require,module,exports){
14467 "use strict";
14468 var __extends = (this && this.__extends) || function (d, b) {
14469     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
14470     function __() { this.constructor = d; }
14471     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14472 };
14473 var OuterSubscriber_1 = require('../OuterSubscriber');
14474 var subscribeToResult_1 = require('../util/subscribeToResult');
14475 /**
14476  * Emits the values emitted by the source Observable until a `notifier`
14477  * Observable emits a value.
14478  *
14479  * <span class="informal">Lets values pass until a second Observable,
14480  * `notifier`, emits something. Then, it completes.</span>
14481  *
14482  * <img src="./img/takeUntil.png" width="100%">
14483  *
14484  * `takeUntil` subscribes and begins mirroring the source Observable. It also
14485  * monitors a second Observable, `notifier` that you provide. If the `notifier`
14486  * emits a value or a complete notification, the output Observable stops
14487  * mirroring the source Observable and completes.
14488  *
14489  * @example <caption>Tick every second until the first click happens</caption>
14490  * var interval = Rx.Observable.interval(1000);
14491  * var clicks = Rx.Observable.fromEvent(document, 'click');
14492  * var result = interval.takeUntil(clicks);
14493  * result.subscribe(x => console.log(x));
14494  *
14495  * @see {@link take}
14496  * @see {@link takeLast}
14497  * @see {@link takeWhile}
14498  * @see {@link skip}
14499  *
14500  * @param {Observable} notifier The Observable whose first emitted value will
14501  * cause the output Observable of `takeUntil` to stop emitting values from the
14502  * source Observable.
14503  * @return {Observable<T>} An Observable that emits the values from the source
14504  * Observable until such time as `notifier` emits its first value.
14505  * @method takeUntil
14506  * @owner Observable
14507  */
14508 function takeUntil(notifier) {
14509     return function (source) { return source.lift(new TakeUntilOperator(notifier)); };
14510 }
14511 exports.takeUntil = takeUntil;
14512 var TakeUntilOperator = (function () {
14513     function TakeUntilOperator(notifier) {
14514         this.notifier = notifier;
14515     }
14516     TakeUntilOperator.prototype.call = function (subscriber, source) {
14517         return source.subscribe(new TakeUntilSubscriber(subscriber, this.notifier));
14518     };
14519     return TakeUntilOperator;
14520 }());
14521 /**
14522  * We need this JSDoc comment for affecting ESDoc.
14523  * @ignore
14524  * @extends {Ignored}
14525  */
14526 var TakeUntilSubscriber = (function (_super) {
14527     __extends(TakeUntilSubscriber, _super);
14528     function TakeUntilSubscriber(destination, notifier) {
14529         _super.call(this, destination);
14530         this.notifier = notifier;
14531         this.add(subscribeToResult_1.subscribeToResult(this, notifier));
14532     }
14533     TakeUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
14534         this.complete();
14535     };
14536     TakeUntilSubscriber.prototype.notifyComplete = function () {
14537         // noop
14538     };
14539     return TakeUntilSubscriber;
14540 }(OuterSubscriber_1.OuterSubscriber));
14541
14542 },{"../OuterSubscriber":31,"../util/subscribeToResult":238}],201:[function(require,module,exports){
14543 "use strict";
14544 var __extends = (this && this.__extends) || function (d, b) {
14545     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
14546     function __() { this.constructor = d; }
14547     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14548 };
14549 var Subscriber_1 = require('../Subscriber');
14550 /**
14551  * Emits values emitted by the source Observable so long as each value satisfies
14552  * the given `predicate`, and then completes as soon as this `predicate` is not
14553  * satisfied.
14554  *
14555  * <span class="informal">Takes values from the source only while they pass the
14556  * condition given. When the first value does not satisfy, it completes.</span>
14557  *
14558  * <img src="./img/takeWhile.png" width="100%">
14559  *
14560  * `takeWhile` subscribes and begins mirroring the source Observable. Each value
14561  * emitted on the source is given to the `predicate` function which returns a
14562  * boolean, representing a condition to be satisfied by the source values. The
14563  * output Observable emits the source values until such time as the `predicate`
14564  * returns false, at which point `takeWhile` stops mirroring the source
14565  * Observable and completes the output Observable.
14566  *
14567  * @example <caption>Emit click events only while the clientX property is greater than 200</caption>
14568  * var clicks = Rx.Observable.fromEvent(document, 'click');
14569  * var result = clicks.takeWhile(ev => ev.clientX > 200);
14570  * result.subscribe(x => console.log(x));
14571  *
14572  * @see {@link take}
14573  * @see {@link takeLast}
14574  * @see {@link takeUntil}
14575  * @see {@link skip}
14576  *
14577  * @param {function(value: T, index: number): boolean} predicate A function that
14578  * evaluates a value emitted by the source Observable and returns a boolean.
14579  * Also takes the (zero-based) index as the second argument.
14580  * @return {Observable<T>} An Observable that emits the values from the source
14581  * Observable so long as each value satisfies the condition defined by the
14582  * `predicate`, then completes.
14583  * @method takeWhile
14584  * @owner Observable
14585  */
14586 function takeWhile(predicate) {
14587     return function (source) { return source.lift(new TakeWhileOperator(predicate)); };
14588 }
14589 exports.takeWhile = takeWhile;
14590 var TakeWhileOperator = (function () {
14591     function TakeWhileOperator(predicate) {
14592         this.predicate = predicate;
14593     }
14594     TakeWhileOperator.prototype.call = function (subscriber, source) {
14595         return source.subscribe(new TakeWhileSubscriber(subscriber, this.predicate));
14596     };
14597     return TakeWhileOperator;
14598 }());
14599 /**
14600  * We need this JSDoc comment for affecting ESDoc.
14601  * @ignore
14602  * @extends {Ignored}
14603  */
14604 var TakeWhileSubscriber = (function (_super) {
14605     __extends(TakeWhileSubscriber, _super);
14606     function TakeWhileSubscriber(destination, predicate) {
14607         _super.call(this, destination);
14608         this.predicate = predicate;
14609         this.index = 0;
14610     }
14611     TakeWhileSubscriber.prototype._next = function (value) {
14612         var destination = this.destination;
14613         var result;
14614         try {
14615             result = this.predicate(value, this.index++);
14616         }
14617         catch (err) {
14618             destination.error(err);
14619             return;
14620         }
14621         this.nextOrComplete(value, result);
14622     };
14623     TakeWhileSubscriber.prototype.nextOrComplete = function (value, predicateResult) {
14624         var destination = this.destination;
14625         if (Boolean(predicateResult)) {
14626             destination.next(value);
14627         }
14628         else {
14629             destination.complete();
14630         }
14631     };
14632     return TakeWhileSubscriber;
14633 }(Subscriber_1.Subscriber));
14634
14635 },{"../Subscriber":36}],202:[function(require,module,exports){
14636 "use strict";
14637 var __extends = (this && this.__extends) || function (d, b) {
14638     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
14639     function __() { this.constructor = d; }
14640     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14641 };
14642 var Subscriber_1 = require('../Subscriber');
14643 /* tslint:enable:max-line-length */
14644 /**
14645  * Perform a side effect for every emission on the source Observable, but return
14646  * an Observable that is identical to the source.
14647  *
14648  * <span class="informal">Intercepts each emission on the source and runs a
14649  * function, but returns an output which is identical to the source as long as errors don't occur.</span>
14650  *
14651  * <img src="./img/do.png" width="100%">
14652  *
14653  * Returns a mirrored Observable of the source Observable, but modified so that
14654  * the provided Observer is called to perform a side effect for every value,
14655  * error, and completion emitted by the source. Any errors that are thrown in
14656  * the aforementioned Observer or handlers are safely sent down the error path
14657  * of the output Observable.
14658  *
14659  * This operator is useful for debugging your Observables for the correct values
14660  * or performing other side effects.
14661  *
14662  * Note: this is different to a `subscribe` on the Observable. If the Observable
14663  * returned by `do` is not subscribed, the side effects specified by the
14664  * Observer will never happen. `do` therefore simply spies on existing
14665  * execution, it does not trigger an execution to happen like `subscribe` does.
14666  *
14667  * @example <caption>Map every click to the clientX position of that click, while also logging the click event</caption>
14668  * var clicks = Rx.Observable.fromEvent(document, 'click');
14669  * var positions = clicks
14670  *   .do(ev => console.log(ev))
14671  *   .map(ev => ev.clientX);
14672  * positions.subscribe(x => console.log(x));
14673  *
14674  * @see {@link map}
14675  * @see {@link subscribe}
14676  *
14677  * @param {Observer|function} [nextOrObserver] A normal Observer object or a
14678  * callback for `next`.
14679  * @param {function} [error] Callback for errors in the source.
14680  * @param {function} [complete] Callback for the completion of the source.
14681  * @return {Observable} An Observable identical to the source, but runs the
14682  * specified Observer or callback(s) for each item.
14683  * @name tap
14684  */
14685 function tap(nextOrObserver, error, complete) {
14686     return function tapOperatorFunction(source) {
14687         return source.lift(new DoOperator(nextOrObserver, error, complete));
14688     };
14689 }
14690 exports.tap = tap;
14691 var DoOperator = (function () {
14692     function DoOperator(nextOrObserver, error, complete) {
14693         this.nextOrObserver = nextOrObserver;
14694         this.error = error;
14695         this.complete = complete;
14696     }
14697     DoOperator.prototype.call = function (subscriber, source) {
14698         return source.subscribe(new DoSubscriber(subscriber, this.nextOrObserver, this.error, this.complete));
14699     };
14700     return DoOperator;
14701 }());
14702 /**
14703  * We need this JSDoc comment for affecting ESDoc.
14704  * @ignore
14705  * @extends {Ignored}
14706  */
14707 var DoSubscriber = (function (_super) {
14708     __extends(DoSubscriber, _super);
14709     function DoSubscriber(destination, nextOrObserver, error, complete) {
14710         _super.call(this, destination);
14711         var safeSubscriber = new Subscriber_1.Subscriber(nextOrObserver, error, complete);
14712         safeSubscriber.syncErrorThrowable = true;
14713         this.add(safeSubscriber);
14714         this.safeSubscriber = safeSubscriber;
14715     }
14716     DoSubscriber.prototype._next = function (value) {
14717         var safeSubscriber = this.safeSubscriber;
14718         safeSubscriber.next(value);
14719         if (safeSubscriber.syncErrorThrown) {
14720             this.destination.error(safeSubscriber.syncErrorValue);
14721         }
14722         else {
14723             this.destination.next(value);
14724         }
14725     };
14726     DoSubscriber.prototype._error = function (err) {
14727         var safeSubscriber = this.safeSubscriber;
14728         safeSubscriber.error(err);
14729         if (safeSubscriber.syncErrorThrown) {
14730             this.destination.error(safeSubscriber.syncErrorValue);
14731         }
14732         else {
14733             this.destination.error(err);
14734         }
14735     };
14736     DoSubscriber.prototype._complete = function () {
14737         var safeSubscriber = this.safeSubscriber;
14738         safeSubscriber.complete();
14739         if (safeSubscriber.syncErrorThrown) {
14740             this.destination.error(safeSubscriber.syncErrorValue);
14741         }
14742         else {
14743             this.destination.complete();
14744         }
14745     };
14746     return DoSubscriber;
14747 }(Subscriber_1.Subscriber));
14748
14749 },{"../Subscriber":36}],203:[function(require,module,exports){
14750 "use strict";
14751 var __extends = (this && this.__extends) || function (d, b) {
14752     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
14753     function __() { this.constructor = d; }
14754     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14755 };
14756 var OuterSubscriber_1 = require('../OuterSubscriber');
14757 var subscribeToResult_1 = require('../util/subscribeToResult');
14758 exports.defaultThrottleConfig = {
14759     leading: true,
14760     trailing: false
14761 };
14762 /**
14763  * Emits a value from the source Observable, then ignores subsequent source
14764  * values for a duration determined by another Observable, then repeats this
14765  * process.
14766  *
14767  * <span class="informal">It's like {@link throttleTime}, but the silencing
14768  * duration is determined by a second Observable.</span>
14769  *
14770  * <img src="./img/throttle.png" width="100%">
14771  *
14772  * `throttle` emits the source Observable values on the output Observable
14773  * when its internal timer is disabled, and ignores source values when the timer
14774  * is enabled. Initially, the timer is disabled. As soon as the first source
14775  * value arrives, it is forwarded to the output Observable, and then the timer
14776  * is enabled by calling the `durationSelector` function with the source value,
14777  * which returns the "duration" Observable. When the duration Observable emits a
14778  * value or completes, the timer is disabled, and this process repeats for the
14779  * next source value.
14780  *
14781  * @example <caption>Emit clicks at a rate of at most one click per second</caption>
14782  * var clicks = Rx.Observable.fromEvent(document, 'click');
14783  * var result = clicks.throttle(ev => Rx.Observable.interval(1000));
14784  * result.subscribe(x => console.log(x));
14785  *
14786  * @see {@link audit}
14787  * @see {@link debounce}
14788  * @see {@link delayWhen}
14789  * @see {@link sample}
14790  * @see {@link throttleTime}
14791  *
14792  * @param {function(value: T): SubscribableOrPromise} durationSelector A function
14793  * that receives a value from the source Observable, for computing the silencing
14794  * duration for each source value, returned as an Observable or a Promise.
14795  * @param {Object} config a configuration object to define `leading` and `trailing` behavior. Defaults
14796  * to `{ leading: true, trailing: false }`.
14797  * @return {Observable<T>} An Observable that performs the throttle operation to
14798  * limit the rate of emissions from the source.
14799  * @method throttle
14800  * @owner Observable
14801  */
14802 function throttle(durationSelector, config) {
14803     if (config === void 0) { config = exports.defaultThrottleConfig; }
14804     return function (source) { return source.lift(new ThrottleOperator(durationSelector, config.leading, config.trailing)); };
14805 }
14806 exports.throttle = throttle;
14807 var ThrottleOperator = (function () {
14808     function ThrottleOperator(durationSelector, leading, trailing) {
14809         this.durationSelector = durationSelector;
14810         this.leading = leading;
14811         this.trailing = trailing;
14812     }
14813     ThrottleOperator.prototype.call = function (subscriber, source) {
14814         return source.subscribe(new ThrottleSubscriber(subscriber, this.durationSelector, this.leading, this.trailing));
14815     };
14816     return ThrottleOperator;
14817 }());
14818 /**
14819  * We need this JSDoc comment for affecting ESDoc
14820  * @ignore
14821  * @extends {Ignored}
14822  */
14823 var ThrottleSubscriber = (function (_super) {
14824     __extends(ThrottleSubscriber, _super);
14825     function ThrottleSubscriber(destination, durationSelector, _leading, _trailing) {
14826         _super.call(this, destination);
14827         this.destination = destination;
14828         this.durationSelector = durationSelector;
14829         this._leading = _leading;
14830         this._trailing = _trailing;
14831         this._hasTrailingValue = false;
14832     }
14833     ThrottleSubscriber.prototype._next = function (value) {
14834         if (this.throttled) {
14835             if (this._trailing) {
14836                 this._hasTrailingValue = true;
14837                 this._trailingValue = value;
14838             }
14839         }
14840         else {
14841             var duration = this.tryDurationSelector(value);
14842             if (duration) {
14843                 this.add(this.throttled = subscribeToResult_1.subscribeToResult(this, duration));
14844             }
14845             if (this._leading) {
14846                 this.destination.next(value);
14847                 if (this._trailing) {
14848                     this._hasTrailingValue = true;
14849                     this._trailingValue = value;
14850                 }
14851             }
14852         }
14853     };
14854     ThrottleSubscriber.prototype.tryDurationSelector = function (value) {
14855         try {
14856             return this.durationSelector(value);
14857         }
14858         catch (err) {
14859             this.destination.error(err);
14860             return null;
14861         }
14862     };
14863     ThrottleSubscriber.prototype._unsubscribe = function () {
14864         var _a = this, throttled = _a.throttled, _trailingValue = _a._trailingValue, _hasTrailingValue = _a._hasTrailingValue, _trailing = _a._trailing;
14865         this._trailingValue = null;
14866         this._hasTrailingValue = false;
14867         if (throttled) {
14868             this.remove(throttled);
14869             this.throttled = null;
14870             throttled.unsubscribe();
14871         }
14872     };
14873     ThrottleSubscriber.prototype._sendTrailing = function () {
14874         var _a = this, destination = _a.destination, throttled = _a.throttled, _trailing = _a._trailing, _trailingValue = _a._trailingValue, _hasTrailingValue = _a._hasTrailingValue;
14875         if (throttled && _trailing && _hasTrailingValue) {
14876             destination.next(_trailingValue);
14877             this._trailingValue = null;
14878             this._hasTrailingValue = false;
14879         }
14880     };
14881     ThrottleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
14882         this._sendTrailing();
14883         this._unsubscribe();
14884     };
14885     ThrottleSubscriber.prototype.notifyComplete = function () {
14886         this._sendTrailing();
14887         this._unsubscribe();
14888     };
14889     return ThrottleSubscriber;
14890 }(OuterSubscriber_1.OuterSubscriber));
14891
14892 },{"../OuterSubscriber":31,"../util/subscribeToResult":238}],204:[function(require,module,exports){
14893 "use strict";
14894 var __extends = (this && this.__extends) || function (d, b) {
14895     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
14896     function __() { this.constructor = d; }
14897     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14898 };
14899 var Subscriber_1 = require('../Subscriber');
14900 var async_1 = require('../scheduler/async');
14901 var throttle_1 = require('./throttle');
14902 /**
14903  * Emits a value from the source Observable, then ignores subsequent source
14904  * values for `duration` milliseconds, then repeats this process.
14905  *
14906  * <span class="informal">Lets a value pass, then ignores source values for the
14907  * next `duration` milliseconds.</span>
14908  *
14909  * <img src="./img/throttleTime.png" width="100%">
14910  *
14911  * `throttleTime` emits the source Observable values on the output Observable
14912  * when its internal timer is disabled, and ignores source values when the timer
14913  * is enabled. Initially, the timer is disabled. As soon as the first source
14914  * value arrives, it is forwarded to the output Observable, and then the timer
14915  * is enabled. After `duration` milliseconds (or the time unit determined
14916  * internally by the optional `scheduler`) has passed, the timer is disabled,
14917  * and this process repeats for the next source value. Optionally takes a
14918  * {@link IScheduler} for managing timers.
14919  *
14920  * @example <caption>Emit clicks at a rate of at most one click per second</caption>
14921  * var clicks = Rx.Observable.fromEvent(document, 'click');
14922  * var result = clicks.throttleTime(1000);
14923  * result.subscribe(x => console.log(x));
14924  *
14925  * @see {@link auditTime}
14926  * @see {@link debounceTime}
14927  * @see {@link delay}
14928  * @see {@link sampleTime}
14929  * @see {@link throttle}
14930  *
14931  * @param {number} duration Time to wait before emitting another value after
14932  * emitting the last value, measured in milliseconds or the time unit determined
14933  * internally by the optional `scheduler`.
14934  * @param {Scheduler} [scheduler=async] The {@link IScheduler} to use for
14935  * managing the timers that handle the throttling.
14936  * @return {Observable<T>} An Observable that performs the throttle operation to
14937  * limit the rate of emissions from the source.
14938  * @method throttleTime
14939  * @owner Observable
14940  */
14941 function throttleTime(duration, scheduler, config) {
14942     if (scheduler === void 0) { scheduler = async_1.async; }
14943     if (config === void 0) { config = throttle_1.defaultThrottleConfig; }
14944     return function (source) { return source.lift(new ThrottleTimeOperator(duration, scheduler, config.leading, config.trailing)); };
14945 }
14946 exports.throttleTime = throttleTime;
14947 var ThrottleTimeOperator = (function () {
14948     function ThrottleTimeOperator(duration, scheduler, leading, trailing) {
14949         this.duration = duration;
14950         this.scheduler = scheduler;
14951         this.leading = leading;
14952         this.trailing = trailing;
14953     }
14954     ThrottleTimeOperator.prototype.call = function (subscriber, source) {
14955         return source.subscribe(new ThrottleTimeSubscriber(subscriber, this.duration, this.scheduler, this.leading, this.trailing));
14956     };
14957     return ThrottleTimeOperator;
14958 }());
14959 /**
14960  * We need this JSDoc comment for affecting ESDoc.
14961  * @ignore
14962  * @extends {Ignored}
14963  */
14964 var ThrottleTimeSubscriber = (function (_super) {
14965     __extends(ThrottleTimeSubscriber, _super);
14966     function ThrottleTimeSubscriber(destination, duration, scheduler, leading, trailing) {
14967         _super.call(this, destination);
14968         this.duration = duration;
14969         this.scheduler = scheduler;
14970         this.leading = leading;
14971         this.trailing = trailing;
14972         this._hasTrailingValue = false;
14973         this._trailingValue = null;
14974     }
14975     ThrottleTimeSubscriber.prototype._next = function (value) {
14976         if (this.throttled) {
14977             if (this.trailing) {
14978                 this._trailingValue = value;
14979                 this._hasTrailingValue = true;
14980             }
14981         }
14982         else {
14983             this.add(this.throttled = this.scheduler.schedule(dispatchNext, this.duration, { subscriber: this }));
14984             if (this.leading) {
14985                 this.destination.next(value);
14986             }
14987         }
14988     };
14989     ThrottleTimeSubscriber.prototype.clearThrottle = function () {
14990         var throttled = this.throttled;
14991         if (throttled) {
14992             if (this.trailing && this._hasTrailingValue) {
14993                 this.destination.next(this._trailingValue);
14994                 this._trailingValue = null;
14995                 this._hasTrailingValue = false;
14996             }
14997             throttled.unsubscribe();
14998             this.remove(throttled);
14999             this.throttled = null;
15000         }
15001     };
15002     return ThrottleTimeSubscriber;
15003 }(Subscriber_1.Subscriber));
15004 function dispatchNext(arg) {
15005     var subscriber = arg.subscriber;
15006     subscriber.clearThrottle();
15007 }
15008
15009 },{"../Subscriber":36,"../scheduler/async":213,"./throttle":203}],205:[function(require,module,exports){
15010 "use strict";
15011 var __extends = (this && this.__extends) || function (d, b) {
15012     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
15013     function __() { this.constructor = d; }
15014     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15015 };
15016 var async_1 = require('../scheduler/async');
15017 var isDate_1 = require('../util/isDate');
15018 var Subscriber_1 = require('../Subscriber');
15019 var TimeoutError_1 = require('../util/TimeoutError');
15020 /**
15021  *
15022  * Errors if Observable does not emit a value in given time span.
15023  *
15024  * <span class="informal">Timeouts on Observable that doesn't emit values fast enough.</span>
15025  *
15026  * <img src="./img/timeout.png" width="100%">
15027  *
15028  * `timeout` operator accepts as an argument either a number or a Date.
15029  *
15030  * If number was provided, it returns an Observable that behaves like a source
15031  * Observable, unless there is a period of time where there is no value emitted.
15032  * So if you provide `100` as argument and first value comes after 50ms from
15033  * the moment of subscription, this value will be simply re-emitted by the resulting
15034  * Observable. If however after that 100ms passes without a second value being emitted,
15035  * stream will end with an error and source Observable will be unsubscribed.
15036  * These checks are performed throughout whole lifecycle of Observable - from the moment
15037  * it was subscribed to, until it completes or errors itself. Thus every value must be
15038  * emitted within specified period since previous value.
15039  *
15040  * If provided argument was Date, returned Observable behaves differently. It throws
15041  * if Observable did not complete before provided Date. This means that periods between
15042  * emission of particular values do not matter in this case. If Observable did not complete
15043  * before provided Date, source Observable will be unsubscribed. Other than that, resulting
15044  * stream behaves just as source Observable.
15045  *
15046  * `timeout` accepts also a Scheduler as a second parameter. It is used to schedule moment (or moments)
15047  * when returned Observable will check if source stream emitted value or completed.
15048  *
15049  * @example <caption>Check if ticks are emitted within certain timespan</caption>
15050  * const seconds = Rx.Observable.interval(1000);
15051  *
15052  * seconds.timeout(1100) // Let's use bigger timespan to be safe,
15053  *                       // since `interval` might fire a bit later then scheduled.
15054  * .subscribe(
15055  *     value => console.log(value), // Will emit numbers just as regular `interval` would.
15056  *     err => console.log(err) // Will never be called.
15057  * );
15058  *
15059  * seconds.timeout(900).subscribe(
15060  *     value => console.log(value), // Will never be called.
15061  *     err => console.log(err) // Will emit error before even first value is emitted,
15062  *                             // since it did not arrive within 900ms period.
15063  * );
15064  *
15065  * @example <caption>Use Date to check if Observable completed</caption>
15066  * const seconds = Rx.Observable.interval(1000);
15067  *
15068  * seconds.timeout(new Date("December 17, 2020 03:24:00"))
15069  * .subscribe(
15070  *     value => console.log(value), // Will emit values as regular `interval` would
15071  *                                  // until December 17, 2020 at 03:24:00.
15072  *     err => console.log(err) // On December 17, 2020 at 03:24:00 it will emit an error,
15073  *                             // since Observable did not complete by then.
15074  * );
15075  *
15076  * @see {@link timeoutWith}
15077  *
15078  * @param {number|Date} due Number specifying period within which Observable must emit values
15079  *                          or Date specifying before when Observable should complete
15080  * @param {Scheduler} [scheduler] Scheduler controlling when timeout checks occur.
15081  * @return {Observable<T>} Observable that mirrors behaviour of source, unless timeout checks fail.
15082  * @method timeout
15083  * @owner Observable
15084  */
15085 function timeout(due, scheduler) {
15086     if (scheduler === void 0) { scheduler = async_1.async; }
15087     var absoluteTimeout = isDate_1.isDate(due);
15088     var waitFor = absoluteTimeout ? (+due - scheduler.now()) : Math.abs(due);
15089     return function (source) { return source.lift(new TimeoutOperator(waitFor, absoluteTimeout, scheduler, new TimeoutError_1.TimeoutError())); };
15090 }
15091 exports.timeout = timeout;
15092 var TimeoutOperator = (function () {
15093     function TimeoutOperator(waitFor, absoluteTimeout, scheduler, errorInstance) {
15094         this.waitFor = waitFor;
15095         this.absoluteTimeout = absoluteTimeout;
15096         this.scheduler = scheduler;
15097         this.errorInstance = errorInstance;
15098     }
15099     TimeoutOperator.prototype.call = function (subscriber, source) {
15100         return source.subscribe(new TimeoutSubscriber(subscriber, this.absoluteTimeout, this.waitFor, this.scheduler, this.errorInstance));
15101     };
15102     return TimeoutOperator;
15103 }());
15104 /**
15105  * We need this JSDoc comment for affecting ESDoc.
15106  * @ignore
15107  * @extends {Ignored}
15108  */
15109 var TimeoutSubscriber = (function (_super) {
15110     __extends(TimeoutSubscriber, _super);
15111     function TimeoutSubscriber(destination, absoluteTimeout, waitFor, scheduler, errorInstance) {
15112         _super.call(this, destination);
15113         this.absoluteTimeout = absoluteTimeout;
15114         this.waitFor = waitFor;
15115         this.scheduler = scheduler;
15116         this.errorInstance = errorInstance;
15117         this.action = null;
15118         this.scheduleTimeout();
15119     }
15120     TimeoutSubscriber.dispatchTimeout = function (subscriber) {
15121         subscriber.error(subscriber.errorInstance);
15122     };
15123     TimeoutSubscriber.prototype.scheduleTimeout = function () {
15124         var action = this.action;
15125         if (action) {
15126             // Recycle the action if we've already scheduled one. All the production
15127             // Scheduler Actions mutate their state/delay time and return themeselves.
15128             // VirtualActions are immutable, so they create and return a clone. In this
15129             // case, we need to set the action reference to the most recent VirtualAction,
15130             // to ensure that's the one we clone from next time.
15131             this.action = action.schedule(this, this.waitFor);
15132         }
15133         else {
15134             this.add(this.action = this.scheduler.schedule(TimeoutSubscriber.dispatchTimeout, this.waitFor, this));
15135         }
15136     };
15137     TimeoutSubscriber.prototype._next = function (value) {
15138         if (!this.absoluteTimeout) {
15139             this.scheduleTimeout();
15140         }
15141         _super.prototype._next.call(this, value);
15142     };
15143     TimeoutSubscriber.prototype._unsubscribe = function () {
15144         this.action = null;
15145         this.scheduler = null;
15146         this.errorInstance = null;
15147     };
15148     return TimeoutSubscriber;
15149 }(Subscriber_1.Subscriber));
15150
15151 },{"../Subscriber":36,"../scheduler/async":213,"../util/TimeoutError":223,"../util/isDate":229}],206:[function(require,module,exports){
15152 "use strict";
15153 var __extends = (this && this.__extends) || function (d, b) {
15154     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
15155     function __() { this.constructor = d; }
15156     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15157 };
15158 var OuterSubscriber_1 = require('../OuterSubscriber');
15159 var subscribeToResult_1 = require('../util/subscribeToResult');
15160 /* tslint:enable:max-line-length */
15161 /**
15162  * Combines the source Observable with other Observables to create an Observable
15163  * whose values are calculated from the latest values of each, only when the
15164  * source emits.
15165  *
15166  * <span class="informal">Whenever the source Observable emits a value, it
15167  * computes a formula using that value plus the latest values from other input
15168  * Observables, then emits the output of that formula.</span>
15169  *
15170  * <img src="./img/withLatestFrom.png" width="100%">
15171  *
15172  * `withLatestFrom` combines each value from the source Observable (the
15173  * instance) with the latest values from the other input Observables only when
15174  * the source emits a value, optionally using a `project` function to determine
15175  * the value to be emitted on the output Observable. All input Observables must
15176  * emit at least one value before the output Observable will emit a value.
15177  *
15178  * @example <caption>On every click event, emit an array with the latest timer event plus the click event</caption>
15179  * var clicks = Rx.Observable.fromEvent(document, 'click');
15180  * var timer = Rx.Observable.interval(1000);
15181  * var result = clicks.withLatestFrom(timer);
15182  * result.subscribe(x => console.log(x));
15183  *
15184  * @see {@link combineLatest}
15185  *
15186  * @param {ObservableInput} other An input Observable to combine with the source
15187  * Observable. More than one input Observables may be given as argument.
15188  * @param {Function} [project] Projection function for combining values
15189  * together. Receives all values in order of the Observables passed, where the
15190  * first parameter is a value from the source Observable. (e.g.
15191  * `a.withLatestFrom(b, c, (a1, b1, c1) => a1 + b1 + c1)`). If this is not
15192  * passed, arrays will be emitted on the output Observable.
15193  * @return {Observable} An Observable of projected values from the most recent
15194  * values from each input Observable, or an array of the most recent values from
15195  * each input Observable.
15196  * @method withLatestFrom
15197  * @owner Observable
15198  */
15199 function withLatestFrom() {
15200     var args = [];
15201     for (var _i = 0; _i < arguments.length; _i++) {
15202         args[_i - 0] = arguments[_i];
15203     }
15204     return function (source) {
15205         var project;
15206         if (typeof args[args.length - 1] === 'function') {
15207             project = args.pop();
15208         }
15209         var observables = args;
15210         return source.lift(new WithLatestFromOperator(observables, project));
15211     };
15212 }
15213 exports.withLatestFrom = withLatestFrom;
15214 var WithLatestFromOperator = (function () {
15215     function WithLatestFromOperator(observables, project) {
15216         this.observables = observables;
15217         this.project = project;
15218     }
15219     WithLatestFromOperator.prototype.call = function (subscriber, source) {
15220         return source.subscribe(new WithLatestFromSubscriber(subscriber, this.observables, this.project));
15221     };
15222     return WithLatestFromOperator;
15223 }());
15224 /**
15225  * We need this JSDoc comment for affecting ESDoc.
15226  * @ignore
15227  * @extends {Ignored}
15228  */
15229 var WithLatestFromSubscriber = (function (_super) {
15230     __extends(WithLatestFromSubscriber, _super);
15231     function WithLatestFromSubscriber(destination, observables, project) {
15232         _super.call(this, destination);
15233         this.observables = observables;
15234         this.project = project;
15235         this.toRespond = [];
15236         var len = observables.length;
15237         this.values = new Array(len);
15238         for (var i = 0; i < len; i++) {
15239             this.toRespond.push(i);
15240         }
15241         for (var i = 0; i < len; i++) {
15242             var observable = observables[i];
15243             this.add(subscribeToResult_1.subscribeToResult(this, observable, observable, i));
15244         }
15245     }
15246     WithLatestFromSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
15247         this.values[outerIndex] = innerValue;
15248         var toRespond = this.toRespond;
15249         if (toRespond.length > 0) {
15250             var found = toRespond.indexOf(outerIndex);
15251             if (found !== -1) {
15252                 toRespond.splice(found, 1);
15253             }
15254         }
15255     };
15256     WithLatestFromSubscriber.prototype.notifyComplete = function () {
15257         // noop
15258     };
15259     WithLatestFromSubscriber.prototype._next = function (value) {
15260         if (this.toRespond.length === 0) {
15261             var args = [value].concat(this.values);
15262             if (this.project) {
15263                 this._tryProject(args);
15264             }
15265             else {
15266                 this.destination.next(args);
15267             }
15268         }
15269     };
15270     WithLatestFromSubscriber.prototype._tryProject = function (args) {
15271         var result;
15272         try {
15273             result = this.project.apply(this, args);
15274         }
15275         catch (err) {
15276             this.destination.error(err);
15277             return;
15278         }
15279         this.destination.next(result);
15280     };
15281     return WithLatestFromSubscriber;
15282 }(OuterSubscriber_1.OuterSubscriber));
15283
15284 },{"../OuterSubscriber":31,"../util/subscribeToResult":238}],207:[function(require,module,exports){
15285 "use strict";
15286 var __extends = (this && this.__extends) || function (d, b) {
15287     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
15288     function __() { this.constructor = d; }
15289     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15290 };
15291 var ArrayObservable_1 = require('../observable/ArrayObservable');
15292 var isArray_1 = require('../util/isArray');
15293 var Subscriber_1 = require('../Subscriber');
15294 var OuterSubscriber_1 = require('../OuterSubscriber');
15295 var subscribeToResult_1 = require('../util/subscribeToResult');
15296 var iterator_1 = require('../symbol/iterator');
15297 /* tslint:enable:max-line-length */
15298 /**
15299  * @param observables
15300  * @return {Observable<R>}
15301  * @method zip
15302  * @owner Observable
15303  */
15304 function zip() {
15305     var observables = [];
15306     for (var _i = 0; _i < arguments.length; _i++) {
15307         observables[_i - 0] = arguments[_i];
15308     }
15309     return function zipOperatorFunction(source) {
15310         return source.lift.call(zipStatic.apply(void 0, [source].concat(observables)));
15311     };
15312 }
15313 exports.zip = zip;
15314 /* tslint:enable:max-line-length */
15315 /**
15316  * Combines multiple Observables to create an Observable whose values are calculated from the values, in order, of each
15317  * of its input Observables.
15318  *
15319  * If the latest parameter is a function, this function is used to compute the created value from the input values.
15320  * Otherwise, an array of the input values is returned.
15321  *
15322  * @example <caption>Combine age and name from different sources</caption>
15323  *
15324  * let age$ = Observable.of<number>(27, 25, 29);
15325  * let name$ = Observable.of<string>('Foo', 'Bar', 'Beer');
15326  * let isDev$ = Observable.of<boolean>(true, true, false);
15327  *
15328  * Observable
15329  *     .zip(age$,
15330  *          name$,
15331  *          isDev$,
15332  *          (age: number, name: string, isDev: boolean) => ({ age, name, isDev }))
15333  *     .subscribe(x => console.log(x));
15334  *
15335  * // outputs
15336  * // { age: 27, name: 'Foo', isDev: true }
15337  * // { age: 25, name: 'Bar', isDev: true }
15338  * // { age: 29, name: 'Beer', isDev: false }
15339  *
15340  * @param observables
15341  * @return {Observable<R>}
15342  * @static true
15343  * @name zip
15344  * @owner Observable
15345  */
15346 function zipStatic() {
15347     var observables = [];
15348     for (var _i = 0; _i < arguments.length; _i++) {
15349         observables[_i - 0] = arguments[_i];
15350     }
15351     var project = observables[observables.length - 1];
15352     if (typeof project === 'function') {
15353         observables.pop();
15354     }
15355     return new ArrayObservable_1.ArrayObservable(observables).lift(new ZipOperator(project));
15356 }
15357 exports.zipStatic = zipStatic;
15358 var ZipOperator = (function () {
15359     function ZipOperator(project) {
15360         this.project = project;
15361     }
15362     ZipOperator.prototype.call = function (subscriber, source) {
15363         return source.subscribe(new ZipSubscriber(subscriber, this.project));
15364     };
15365     return ZipOperator;
15366 }());
15367 exports.ZipOperator = ZipOperator;
15368 /**
15369  * We need this JSDoc comment for affecting ESDoc.
15370  * @ignore
15371  * @extends {Ignored}
15372  */
15373 var ZipSubscriber = (function (_super) {
15374     __extends(ZipSubscriber, _super);
15375     function ZipSubscriber(destination, project, values) {
15376         if (values === void 0) { values = Object.create(null); }
15377         _super.call(this, destination);
15378         this.iterators = [];
15379         this.active = 0;
15380         this.project = (typeof project === 'function') ? project : null;
15381         this.values = values;
15382     }
15383     ZipSubscriber.prototype._next = function (value) {
15384         var iterators = this.iterators;
15385         if (isArray_1.isArray(value)) {
15386             iterators.push(new StaticArrayIterator(value));
15387         }
15388         else if (typeof value[iterator_1.iterator] === 'function') {
15389             iterators.push(new StaticIterator(value[iterator_1.iterator]()));
15390         }
15391         else {
15392             iterators.push(new ZipBufferIterator(this.destination, this, value));
15393         }
15394     };
15395     ZipSubscriber.prototype._complete = function () {
15396         var iterators = this.iterators;
15397         var len = iterators.length;
15398         if (len === 0) {
15399             this.destination.complete();
15400             return;
15401         }
15402         this.active = len;
15403         for (var i = 0; i < len; i++) {
15404             var iterator = iterators[i];
15405             if (iterator.stillUnsubscribed) {
15406                 this.add(iterator.subscribe(iterator, i));
15407             }
15408             else {
15409                 this.active--; // not an observable
15410             }
15411         }
15412     };
15413     ZipSubscriber.prototype.notifyInactive = function () {
15414         this.active--;
15415         if (this.active === 0) {
15416             this.destination.complete();
15417         }
15418     };
15419     ZipSubscriber.prototype.checkIterators = function () {
15420         var iterators = this.iterators;
15421         var len = iterators.length;
15422         var destination = this.destination;
15423         // abort if not all of them have values
15424         for (var i = 0; i < len; i++) {
15425             var iterator = iterators[i];
15426             if (typeof iterator.hasValue === 'function' && !iterator.hasValue()) {
15427                 return;
15428             }
15429         }
15430         var shouldComplete = false;
15431         var args = [];
15432         for (var i = 0; i < len; i++) {
15433             var iterator = iterators[i];
15434             var result = iterator.next();
15435             // check to see if it's completed now that you've gotten
15436             // the next value.
15437             if (iterator.hasCompleted()) {
15438                 shouldComplete = true;
15439             }
15440             if (result.done) {
15441                 destination.complete();
15442                 return;
15443             }
15444             args.push(result.value);
15445         }
15446         if (this.project) {
15447             this._tryProject(args);
15448         }
15449         else {
15450             destination.next(args);
15451         }
15452         if (shouldComplete) {
15453             destination.complete();
15454         }
15455     };
15456     ZipSubscriber.prototype._tryProject = function (args) {
15457         var result;
15458         try {
15459             result = this.project.apply(this, args);
15460         }
15461         catch (err) {
15462             this.destination.error(err);
15463             return;
15464         }
15465         this.destination.next(result);
15466     };
15467     return ZipSubscriber;
15468 }(Subscriber_1.Subscriber));
15469 exports.ZipSubscriber = ZipSubscriber;
15470 var StaticIterator = (function () {
15471     function StaticIterator(iterator) {
15472         this.iterator = iterator;
15473         this.nextResult = iterator.next();
15474     }
15475     StaticIterator.prototype.hasValue = function () {
15476         return true;
15477     };
15478     StaticIterator.prototype.next = function () {
15479         var result = this.nextResult;
15480         this.nextResult = this.iterator.next();
15481         return result;
15482     };
15483     StaticIterator.prototype.hasCompleted = function () {
15484         var nextResult = this.nextResult;
15485         return nextResult && nextResult.done;
15486     };
15487     return StaticIterator;
15488 }());
15489 var StaticArrayIterator = (function () {
15490     function StaticArrayIterator(array) {
15491         this.array = array;
15492         this.index = 0;
15493         this.length = 0;
15494         this.length = array.length;
15495     }
15496     StaticArrayIterator.prototype[iterator_1.iterator] = function () {
15497         return this;
15498     };
15499     StaticArrayIterator.prototype.next = function (value) {
15500         var i = this.index++;
15501         var array = this.array;
15502         return i < this.length ? { value: array[i], done: false } : { value: null, done: true };
15503     };
15504     StaticArrayIterator.prototype.hasValue = function () {
15505         return this.array.length > this.index;
15506     };
15507     StaticArrayIterator.prototype.hasCompleted = function () {
15508         return this.array.length === this.index;
15509     };
15510     return StaticArrayIterator;
15511 }());
15512 /**
15513  * We need this JSDoc comment for affecting ESDoc.
15514  * @ignore
15515  * @extends {Ignored}
15516  */
15517 var ZipBufferIterator = (function (_super) {
15518     __extends(ZipBufferIterator, _super);
15519     function ZipBufferIterator(destination, parent, observable) {
15520         _super.call(this, destination);
15521         this.parent = parent;
15522         this.observable = observable;
15523         this.stillUnsubscribed = true;
15524         this.buffer = [];
15525         this.isComplete = false;
15526     }
15527     ZipBufferIterator.prototype[iterator_1.iterator] = function () {
15528         return this;
15529     };
15530     // NOTE: there is actually a name collision here with Subscriber.next and Iterator.next
15531     //    this is legit because `next()` will never be called by a subscription in this case.
15532     ZipBufferIterator.prototype.next = function () {
15533         var buffer = this.buffer;
15534         if (buffer.length === 0 && this.isComplete) {
15535             return { value: null, done: true };
15536         }
15537         else {
15538             return { value: buffer.shift(), done: false };
15539         }
15540     };
15541     ZipBufferIterator.prototype.hasValue = function () {
15542         return this.buffer.length > 0;
15543     };
15544     ZipBufferIterator.prototype.hasCompleted = function () {
15545         return this.buffer.length === 0 && this.isComplete;
15546     };
15547     ZipBufferIterator.prototype.notifyComplete = function () {
15548         if (this.buffer.length > 0) {
15549             this.isComplete = true;
15550             this.parent.notifyInactive();
15551         }
15552         else {
15553             this.destination.complete();
15554         }
15555     };
15556     ZipBufferIterator.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
15557         this.buffer.push(innerValue);
15558         this.parent.checkIterators();
15559     };
15560     ZipBufferIterator.prototype.subscribe = function (value, index) {
15561         return subscribeToResult_1.subscribeToResult(this, this.observable, this, index);
15562     };
15563     return ZipBufferIterator;
15564 }(OuterSubscriber_1.OuterSubscriber));
15565
15566 },{"../OuterSubscriber":31,"../Subscriber":36,"../observable/ArrayObservable":93,"../symbol/iterator":215,"../util/isArray":227,"../util/subscribeToResult":238}],208:[function(require,module,exports){
15567 "use strict";
15568 var __extends = (this && this.__extends) || function (d, b) {
15569     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
15570     function __() { this.constructor = d; }
15571     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15572 };
15573 var Subscription_1 = require('../Subscription');
15574 /**
15575  * A unit of work to be executed in a {@link Scheduler}. An action is typically
15576  * created from within a Scheduler and an RxJS user does not need to concern
15577  * themselves about creating and manipulating an Action.
15578  *
15579  * ```ts
15580  * class Action<T> extends Subscription {
15581  *   new (scheduler: Scheduler, work: (state?: T) => void);
15582  *   schedule(state?: T, delay: number = 0): Subscription;
15583  * }
15584  * ```
15585  *
15586  * @class Action<T>
15587  */
15588 var Action = (function (_super) {
15589     __extends(Action, _super);
15590     function Action(scheduler, work) {
15591         _super.call(this);
15592     }
15593     /**
15594      * Schedules this action on its parent Scheduler for execution. May be passed
15595      * some context object, `state`. May happen at some point in the future,
15596      * according to the `delay` parameter, if specified.
15597      * @param {T} [state] Some contextual data that the `work` function uses when
15598      * called by the Scheduler.
15599      * @param {number} [delay] Time to wait before executing the work, where the
15600      * time unit is implicit and defined by the Scheduler.
15601      * @return {void}
15602      */
15603     Action.prototype.schedule = function (state, delay) {
15604         if (delay === void 0) { delay = 0; }
15605         return this;
15606     };
15607     return Action;
15608 }(Subscription_1.Subscription));
15609 exports.Action = Action;
15610
15611 },{"../Subscription":37}],209:[function(require,module,exports){
15612 "use strict";
15613 var __extends = (this && this.__extends) || function (d, b) {
15614     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
15615     function __() { this.constructor = d; }
15616     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15617 };
15618 var root_1 = require('../util/root');
15619 var Action_1 = require('./Action');
15620 /**
15621  * We need this JSDoc comment for affecting ESDoc.
15622  * @ignore
15623  * @extends {Ignored}
15624  */
15625 var AsyncAction = (function (_super) {
15626     __extends(AsyncAction, _super);
15627     function AsyncAction(scheduler, work) {
15628         _super.call(this, scheduler, work);
15629         this.scheduler = scheduler;
15630         this.work = work;
15631         this.pending = false;
15632     }
15633     AsyncAction.prototype.schedule = function (state, delay) {
15634         if (delay === void 0) { delay = 0; }
15635         if (this.closed) {
15636             return this;
15637         }
15638         // Always replace the current state with the new state.
15639         this.state = state;
15640         // Set the pending flag indicating that this action has been scheduled, or
15641         // has recursively rescheduled itself.
15642         this.pending = true;
15643         var id = this.id;
15644         var scheduler = this.scheduler;
15645         //
15646         // Important implementation note:
15647         //
15648         // Actions only execute once by default, unless rescheduled from within the
15649         // scheduled callback. This allows us to implement single and repeat
15650         // actions via the same code path, without adding API surface area, as well
15651         // as mimic traditional recursion but across asynchronous boundaries.
15652         //
15653         // However, JS runtimes and timers distinguish between intervals achieved by
15654         // serial `setTimeout` calls vs. a single `setInterval` call. An interval of
15655         // serial `setTimeout` calls can be individually delayed, which delays
15656         // scheduling the next `setTimeout`, and so on. `setInterval` attempts to
15657         // guarantee the interval callback will be invoked more precisely to the
15658         // interval period, regardless of load.
15659         //
15660         // Therefore, we use `setInterval` to schedule single and repeat actions.
15661         // If the action reschedules itself with the same delay, the interval is not
15662         // canceled. If the action doesn't reschedule, or reschedules with a
15663         // different delay, the interval will be canceled after scheduled callback
15664         // execution.
15665         //
15666         if (id != null) {
15667             this.id = this.recycleAsyncId(scheduler, id, delay);
15668         }
15669         this.delay = delay;
15670         // If this action has already an async Id, don't request a new one.
15671         this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);
15672         return this;
15673     };
15674     AsyncAction.prototype.requestAsyncId = function (scheduler, id, delay) {
15675         if (delay === void 0) { delay = 0; }
15676         return root_1.root.setInterval(scheduler.flush.bind(scheduler, this), delay);
15677     };
15678     AsyncAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
15679         if (delay === void 0) { delay = 0; }
15680         // If this action is rescheduled with the same delay time, don't clear the interval id.
15681         if (delay !== null && this.delay === delay && this.pending === false) {
15682             return id;
15683         }
15684         // Otherwise, if the action's delay time is different from the current delay,
15685         // or the action has been rescheduled before it's executed, clear the interval id
15686         return root_1.root.clearInterval(id) && undefined || undefined;
15687     };
15688     /**
15689      * Immediately executes this action and the `work` it contains.
15690      * @return {any}
15691      */
15692     AsyncAction.prototype.execute = function (state, delay) {
15693         if (this.closed) {
15694             return new Error('executing a cancelled action');
15695         }
15696         this.pending = false;
15697         var error = this._execute(state, delay);
15698         if (error) {
15699             return error;
15700         }
15701         else if (this.pending === false && this.id != null) {
15702             // Dequeue if the action didn't reschedule itself. Don't call
15703             // unsubscribe(), because the action could reschedule later.
15704             // For example:
15705             // ```
15706             // scheduler.schedule(function doWork(counter) {
15707             //   /* ... I'm a busy worker bee ... */
15708             //   var originalAction = this;
15709             //   /* wait 100ms before rescheduling the action */
15710             //   setTimeout(function () {
15711             //     originalAction.schedule(counter + 1);
15712             //   }, 100);
15713             // }, 1000);
15714             // ```
15715             this.id = this.recycleAsyncId(this.scheduler, this.id, null);
15716         }
15717     };
15718     AsyncAction.prototype._execute = function (state, delay) {
15719         var errored = false;
15720         var errorValue = undefined;
15721         try {
15722             this.work(state);
15723         }
15724         catch (e) {
15725             errored = true;
15726             errorValue = !!e && e || new Error(e);
15727         }
15728         if (errored) {
15729             this.unsubscribe();
15730             return errorValue;
15731         }
15732     };
15733     AsyncAction.prototype._unsubscribe = function () {
15734         var id = this.id;
15735         var scheduler = this.scheduler;
15736         var actions = scheduler.actions;
15737         var index = actions.indexOf(this);
15738         this.work = null;
15739         this.state = null;
15740         this.pending = false;
15741         this.scheduler = null;
15742         if (index !== -1) {
15743             actions.splice(index, 1);
15744         }
15745         if (id != null) {
15746             this.id = this.recycleAsyncId(scheduler, id, null);
15747         }
15748         this.delay = null;
15749     };
15750     return AsyncAction;
15751 }(Action_1.Action));
15752 exports.AsyncAction = AsyncAction;
15753
15754 },{"../util/root":237,"./Action":208}],210:[function(require,module,exports){
15755 "use strict";
15756 var __extends = (this && this.__extends) || function (d, b) {
15757     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
15758     function __() { this.constructor = d; }
15759     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15760 };
15761 var Scheduler_1 = require('../Scheduler');
15762 var AsyncScheduler = (function (_super) {
15763     __extends(AsyncScheduler, _super);
15764     function AsyncScheduler() {
15765         _super.apply(this, arguments);
15766         this.actions = [];
15767         /**
15768          * A flag to indicate whether the Scheduler is currently executing a batch of
15769          * queued actions.
15770          * @type {boolean}
15771          */
15772         this.active = false;
15773         /**
15774          * An internal ID used to track the latest asynchronous task such as those
15775          * coming from `setTimeout`, `setInterval`, `requestAnimationFrame`, and
15776          * others.
15777          * @type {any}
15778          */
15779         this.scheduled = undefined;
15780     }
15781     AsyncScheduler.prototype.flush = function (action) {
15782         var actions = this.actions;
15783         if (this.active) {
15784             actions.push(action);
15785             return;
15786         }
15787         var error;
15788         this.active = true;
15789         do {
15790             if (error = action.execute(action.state, action.delay)) {
15791                 break;
15792             }
15793         } while (action = actions.shift()); // exhaust the scheduler queue
15794         this.active = false;
15795         if (error) {
15796             while (action = actions.shift()) {
15797                 action.unsubscribe();
15798             }
15799             throw error;
15800         }
15801     };
15802     return AsyncScheduler;
15803 }(Scheduler_1.Scheduler));
15804 exports.AsyncScheduler = AsyncScheduler;
15805
15806 },{"../Scheduler":33}],211:[function(require,module,exports){
15807 "use strict";
15808 var __extends = (this && this.__extends) || function (d, b) {
15809     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
15810     function __() { this.constructor = d; }
15811     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15812 };
15813 var AsyncAction_1 = require('./AsyncAction');
15814 /**
15815  * We need this JSDoc comment for affecting ESDoc.
15816  * @ignore
15817  * @extends {Ignored}
15818  */
15819 var QueueAction = (function (_super) {
15820     __extends(QueueAction, _super);
15821     function QueueAction(scheduler, work) {
15822         _super.call(this, scheduler, work);
15823         this.scheduler = scheduler;
15824         this.work = work;
15825     }
15826     QueueAction.prototype.schedule = function (state, delay) {
15827         if (delay === void 0) { delay = 0; }
15828         if (delay > 0) {
15829             return _super.prototype.schedule.call(this, state, delay);
15830         }
15831         this.delay = delay;
15832         this.state = state;
15833         this.scheduler.flush(this);
15834         return this;
15835     };
15836     QueueAction.prototype.execute = function (state, delay) {
15837         return (delay > 0 || this.closed) ?
15838             _super.prototype.execute.call(this, state, delay) :
15839             this._execute(state, delay);
15840     };
15841     QueueAction.prototype.requestAsyncId = function (scheduler, id, delay) {
15842         if (delay === void 0) { delay = 0; }
15843         // If delay exists and is greater than 0, or if the delay is null (the
15844         // action wasn't rescheduled) but was originally scheduled as an async
15845         // action, then recycle as an async action.
15846         if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
15847             return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
15848         }
15849         // Otherwise flush the scheduler starting with this action.
15850         return scheduler.flush(this);
15851     };
15852     return QueueAction;
15853 }(AsyncAction_1.AsyncAction));
15854 exports.QueueAction = QueueAction;
15855
15856 },{"./AsyncAction":209}],212:[function(require,module,exports){
15857 "use strict";
15858 var __extends = (this && this.__extends) || function (d, b) {
15859     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
15860     function __() { this.constructor = d; }
15861     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15862 };
15863 var AsyncScheduler_1 = require('./AsyncScheduler');
15864 var QueueScheduler = (function (_super) {
15865     __extends(QueueScheduler, _super);
15866     function QueueScheduler() {
15867         _super.apply(this, arguments);
15868     }
15869     return QueueScheduler;
15870 }(AsyncScheduler_1.AsyncScheduler));
15871 exports.QueueScheduler = QueueScheduler;
15872
15873 },{"./AsyncScheduler":210}],213:[function(require,module,exports){
15874 "use strict";
15875 var AsyncAction_1 = require('./AsyncAction');
15876 var AsyncScheduler_1 = require('./AsyncScheduler');
15877 /**
15878  *
15879  * Async Scheduler
15880  *
15881  * <span class="informal">Schedule task as if you used setTimeout(task, duration)</span>
15882  *
15883  * `async` scheduler schedules tasks asynchronously, by putting them on the JavaScript
15884  * event loop queue. It is best used to delay tasks in time or to schedule tasks repeating
15885  * in intervals.
15886  *
15887  * If you just want to "defer" task, that is to perform it right after currently
15888  * executing synchronous code ends (commonly achieved by `setTimeout(deferredTask, 0)`),
15889  * better choice will be the {@link asap} scheduler.
15890  *
15891  * @example <caption>Use async scheduler to delay task</caption>
15892  * const task = () => console.log('it works!');
15893  *
15894  * Rx.Scheduler.async.schedule(task, 2000);
15895  *
15896  * // After 2 seconds logs:
15897  * // "it works!"
15898  *
15899  *
15900  * @example <caption>Use async scheduler to repeat task in intervals</caption>
15901  * function task(state) {
15902  *   console.log(state);
15903  *   this.schedule(state + 1, 1000); // `this` references currently executing Action,
15904  *                                   // which we reschedule with new state and delay
15905  * }
15906  *
15907  * Rx.Scheduler.async.schedule(task, 3000, 0);
15908  *
15909  * // Logs:
15910  * // 0 after 3s
15911  * // 1 after 4s
15912  * // 2 after 5s
15913  * // 3 after 6s
15914  *
15915  * @static true
15916  * @name async
15917  * @owner Scheduler
15918  */
15919 exports.async = new AsyncScheduler_1.AsyncScheduler(AsyncAction_1.AsyncAction);
15920
15921 },{"./AsyncAction":209,"./AsyncScheduler":210}],214:[function(require,module,exports){
15922 "use strict";
15923 var QueueAction_1 = require('./QueueAction');
15924 var QueueScheduler_1 = require('./QueueScheduler');
15925 /**
15926  *
15927  * Queue Scheduler
15928  *
15929  * <span class="informal">Put every next task on a queue, instead of executing it immediately</span>
15930  *
15931  * `queue` scheduler, when used with delay, behaves the same as {@link async} scheduler.
15932  *
15933  * When used without delay, it schedules given task synchronously - executes it right when
15934  * it is scheduled. However when called recursively, that is when inside the scheduled task,
15935  * another task is scheduled with queue scheduler, instead of executing immediately as well,
15936  * that task will be put on a queue and wait for current one to finish.
15937  *
15938  * This means that when you execute task with `queue` scheduler, you are sure it will end
15939  * before any other task scheduled with that scheduler will start.
15940  *
15941  * @examples <caption>Schedule recursively first, then do something</caption>
15942  *
15943  * Rx.Scheduler.queue.schedule(() => {
15944  *   Rx.Scheduler.queue.schedule(() => console.log('second')); // will not happen now, but will be put on a queue
15945  *
15946  *   console.log('first');
15947  * });
15948  *
15949  * // Logs:
15950  * // "first"
15951  * // "second"
15952  *
15953  *
15954  * @example <caption>Reschedule itself recursively</caption>
15955  *
15956  * Rx.Scheduler.queue.schedule(function(state) {
15957  *   if (state !== 0) {
15958  *     console.log('before', state);
15959  *     this.schedule(state - 1); // `this` references currently executing Action,
15960  *                               // which we reschedule with new state
15961  *     console.log('after', state);
15962  *   }
15963  * }, 0, 3);
15964  *
15965  * // In scheduler that runs recursively, you would expect:
15966  * // "before", 3
15967  * // "before", 2
15968  * // "before", 1
15969  * // "after", 1
15970  * // "after", 2
15971  * // "after", 3
15972  *
15973  * // But with queue it logs:
15974  * // "before", 3
15975  * // "after", 3
15976  * // "before", 2
15977  * // "after", 2
15978  * // "before", 1
15979  * // "after", 1
15980  *
15981  *
15982  * @static true
15983  * @name queue
15984  * @owner Scheduler
15985  */
15986 exports.queue = new QueueScheduler_1.QueueScheduler(QueueAction_1.QueueAction);
15987
15988 },{"./QueueAction":211,"./QueueScheduler":212}],215:[function(require,module,exports){
15989 "use strict";
15990 var root_1 = require('../util/root');
15991 function symbolIteratorPonyfill(root) {
15992     var Symbol = root.Symbol;
15993     if (typeof Symbol === 'function') {
15994         if (!Symbol.iterator) {
15995             Symbol.iterator = Symbol('iterator polyfill');
15996         }
15997         return Symbol.iterator;
15998     }
15999     else {
16000         // [for Mozilla Gecko 27-35:](https://mzl.la/2ewE1zC)
16001         var Set_1 = root.Set;
16002         if (Set_1 && typeof new Set_1()['@@iterator'] === 'function') {
16003             return '@@iterator';
16004         }
16005         var Map_1 = root.Map;
16006         // required for compatability with es6-shim
16007         if (Map_1) {
16008             var keys = Object.getOwnPropertyNames(Map_1.prototype);
16009             for (var i = 0; i < keys.length; ++i) {
16010                 var key = keys[i];
16011                 // according to spec, Map.prototype[@@iterator] and Map.orototype.entries must be equal.
16012                 if (key !== 'entries' && key !== 'size' && Map_1.prototype[key] === Map_1.prototype['entries']) {
16013                     return key;
16014                 }
16015             }
16016         }
16017         return '@@iterator';
16018     }
16019 }
16020 exports.symbolIteratorPonyfill = symbolIteratorPonyfill;
16021 exports.iterator = symbolIteratorPonyfill(root_1.root);
16022 /**
16023  * @deprecated use iterator instead
16024  */
16025 exports.$$iterator = exports.iterator;
16026
16027 },{"../util/root":237}],216:[function(require,module,exports){
16028 "use strict";
16029 var root_1 = require('../util/root');
16030 function getSymbolObservable(context) {
16031     var $$observable;
16032     var Symbol = context.Symbol;
16033     if (typeof Symbol === 'function') {
16034         if (Symbol.observable) {
16035             $$observable = Symbol.observable;
16036         }
16037         else {
16038             $$observable = Symbol('observable');
16039             Symbol.observable = $$observable;
16040         }
16041     }
16042     else {
16043         $$observable = '@@observable';
16044     }
16045     return $$observable;
16046 }
16047 exports.getSymbolObservable = getSymbolObservable;
16048 exports.observable = getSymbolObservable(root_1.root);
16049 /**
16050  * @deprecated use observable instead
16051  */
16052 exports.$$observable = exports.observable;
16053
16054 },{"../util/root":237}],217:[function(require,module,exports){
16055 "use strict";
16056 var root_1 = require('../util/root');
16057 var Symbol = root_1.root.Symbol;
16058 exports.rxSubscriber = (typeof Symbol === 'function' && typeof Symbol.for === 'function') ?
16059     Symbol.for('rxSubscriber') : '@@rxSubscriber';
16060 /**
16061  * @deprecated use rxSubscriber instead
16062  */
16063 exports.$$rxSubscriber = exports.rxSubscriber;
16064
16065 },{"../util/root":237}],218:[function(require,module,exports){
16066 "use strict";
16067 var root_1 = require('./root');
16068 var RequestAnimationFrameDefinition = (function () {
16069     function RequestAnimationFrameDefinition(root) {
16070         if (root.requestAnimationFrame) {
16071             this.cancelAnimationFrame = root.cancelAnimationFrame.bind(root);
16072             this.requestAnimationFrame = root.requestAnimationFrame.bind(root);
16073         }
16074         else if (root.mozRequestAnimationFrame) {
16075             this.cancelAnimationFrame = root.mozCancelAnimationFrame.bind(root);
16076             this.requestAnimationFrame = root.mozRequestAnimationFrame.bind(root);
16077         }
16078         else if (root.webkitRequestAnimationFrame) {
16079             this.cancelAnimationFrame = root.webkitCancelAnimationFrame.bind(root);
16080             this.requestAnimationFrame = root.webkitRequestAnimationFrame.bind(root);
16081         }
16082         else if (root.msRequestAnimationFrame) {
16083             this.cancelAnimationFrame = root.msCancelAnimationFrame.bind(root);
16084             this.requestAnimationFrame = root.msRequestAnimationFrame.bind(root);
16085         }
16086         else if (root.oRequestAnimationFrame) {
16087             this.cancelAnimationFrame = root.oCancelAnimationFrame.bind(root);
16088             this.requestAnimationFrame = root.oRequestAnimationFrame.bind(root);
16089         }
16090         else {
16091             this.cancelAnimationFrame = root.clearTimeout.bind(root);
16092             this.requestAnimationFrame = function (cb) { return root.setTimeout(cb, 1000 / 60); };
16093         }
16094     }
16095     return RequestAnimationFrameDefinition;
16096 }());
16097 exports.RequestAnimationFrameDefinition = RequestAnimationFrameDefinition;
16098 exports.AnimationFrame = new RequestAnimationFrameDefinition(root_1.root);
16099
16100 },{"./root":237}],219:[function(require,module,exports){
16101 "use strict";
16102 var __extends = (this && this.__extends) || function (d, b) {
16103     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
16104     function __() { this.constructor = d; }
16105     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
16106 };
16107 /**
16108  * An error thrown when an element was queried at a certain index of an
16109  * Observable, but no such index or position exists in that sequence.
16110  *
16111  * @see {@link elementAt}
16112  * @see {@link take}
16113  * @see {@link takeLast}
16114  *
16115  * @class ArgumentOutOfRangeError
16116  */
16117 var ArgumentOutOfRangeError = (function (_super) {
16118     __extends(ArgumentOutOfRangeError, _super);
16119     function ArgumentOutOfRangeError() {
16120         var err = _super.call(this, 'argument out of range');
16121         this.name = err.name = 'ArgumentOutOfRangeError';
16122         this.stack = err.stack;
16123         this.message = err.message;
16124     }
16125     return ArgumentOutOfRangeError;
16126 }(Error));
16127 exports.ArgumentOutOfRangeError = ArgumentOutOfRangeError;
16128
16129 },{}],220:[function(require,module,exports){
16130 "use strict";
16131 var __extends = (this && this.__extends) || function (d, b) {
16132     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
16133     function __() { this.constructor = d; }
16134     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
16135 };
16136 /**
16137  * An error thrown when an Observable or a sequence was queried but has no
16138  * elements.
16139  *
16140  * @see {@link first}
16141  * @see {@link last}
16142  * @see {@link single}
16143  *
16144  * @class EmptyError
16145  */
16146 var EmptyError = (function (_super) {
16147     __extends(EmptyError, _super);
16148     function EmptyError() {
16149         var err = _super.call(this, 'no elements in sequence');
16150         this.name = err.name = 'EmptyError';
16151         this.stack = err.stack;
16152         this.message = err.message;
16153     }
16154     return EmptyError;
16155 }(Error));
16156 exports.EmptyError = EmptyError;
16157
16158 },{}],221:[function(require,module,exports){
16159 "use strict";
16160 var __extends = (this && this.__extends) || function (d, b) {
16161     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
16162     function __() { this.constructor = d; }
16163     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
16164 };
16165 /**
16166  * An error thrown when an action is invalid because the object has been
16167  * unsubscribed.
16168  *
16169  * @see {@link Subject}
16170  * @see {@link BehaviorSubject}
16171  *
16172  * @class ObjectUnsubscribedError
16173  */
16174 var ObjectUnsubscribedError = (function (_super) {
16175     __extends(ObjectUnsubscribedError, _super);
16176     function ObjectUnsubscribedError() {
16177         var err = _super.call(this, 'object unsubscribed');
16178         this.name = err.name = 'ObjectUnsubscribedError';
16179         this.stack = err.stack;
16180         this.message = err.message;
16181     }
16182     return ObjectUnsubscribedError;
16183 }(Error));
16184 exports.ObjectUnsubscribedError = ObjectUnsubscribedError;
16185
16186 },{}],222:[function(require,module,exports){
16187 "use strict";
16188 var root_1 = require('./root');
16189 function minimalSetImpl() {
16190     // THIS IS NOT a full impl of Set, this is just the minimum
16191     // bits of functionality we need for this library.
16192     return (function () {
16193         function MinimalSet() {
16194             this._values = [];
16195         }
16196         MinimalSet.prototype.add = function (value) {
16197             if (!this.has(value)) {
16198                 this._values.push(value);
16199             }
16200         };
16201         MinimalSet.prototype.has = function (value) {
16202             return this._values.indexOf(value) !== -1;
16203         };
16204         Object.defineProperty(MinimalSet.prototype, "size", {
16205             get: function () {
16206                 return this._values.length;
16207             },
16208             enumerable: true,
16209             configurable: true
16210         });
16211         MinimalSet.prototype.clear = function () {
16212             this._values.length = 0;
16213         };
16214         return MinimalSet;
16215     }());
16216 }
16217 exports.minimalSetImpl = minimalSetImpl;
16218 exports.Set = root_1.root.Set || minimalSetImpl();
16219
16220 },{"./root":237}],223:[function(require,module,exports){
16221 "use strict";
16222 var __extends = (this && this.__extends) || function (d, b) {
16223     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
16224     function __() { this.constructor = d; }
16225     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
16226 };
16227 /**
16228  * An error thrown when duetime elapses.
16229  *
16230  * @see {@link timeout}
16231  *
16232  * @class TimeoutError
16233  */
16234 var TimeoutError = (function (_super) {
16235     __extends(TimeoutError, _super);
16236     function TimeoutError() {
16237         var err = _super.call(this, 'Timeout has occurred');
16238         this.name = err.name = 'TimeoutError';
16239         this.stack = err.stack;
16240         this.message = err.message;
16241     }
16242     return TimeoutError;
16243 }(Error));
16244 exports.TimeoutError = TimeoutError;
16245
16246 },{}],224:[function(require,module,exports){
16247 "use strict";
16248 var __extends = (this && this.__extends) || function (d, b) {
16249     for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
16250     function __() { this.constructor = d; }
16251     d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
16252 };
16253 /**
16254  * An error thrown when one or more errors have occurred during the
16255  * `unsubscribe` of a {@link Subscription}.
16256  */
16257 var UnsubscriptionError = (function (_super) {
16258     __extends(UnsubscriptionError, _super);
16259     function UnsubscriptionError(errors) {
16260         _super.call(this);
16261         this.errors = errors;
16262         var err = Error.call(this, errors ?
16263             errors.length + " errors occurred during unsubscription:\n  " + errors.map(function (err, i) { return ((i + 1) + ") " + err.toString()); }).join('\n  ') : '');
16264         this.name = err.name = 'UnsubscriptionError';
16265         this.stack = err.stack;
16266         this.message = err.message;
16267     }
16268     return UnsubscriptionError;
16269 }(Error));
16270 exports.UnsubscriptionError = UnsubscriptionError;
16271
16272 },{}],225:[function(require,module,exports){
16273 "use strict";
16274 // typeof any so that it we don't have to cast when comparing a result to the error object
16275 exports.errorObject = { e: {} };
16276
16277 },{}],226:[function(require,module,exports){
16278 "use strict";
16279 function identity(x) {
16280     return x;
16281 }
16282 exports.identity = identity;
16283
16284 },{}],227:[function(require,module,exports){
16285 "use strict";
16286 exports.isArray = Array.isArray || (function (x) { return x && typeof x.length === 'number'; });
16287
16288 },{}],228:[function(require,module,exports){
16289 "use strict";
16290 exports.isArrayLike = (function (x) { return x && typeof x.length === 'number'; });
16291
16292 },{}],229:[function(require,module,exports){
16293 "use strict";
16294 function isDate(value) {
16295     return value instanceof Date && !isNaN(+value);
16296 }
16297 exports.isDate = isDate;
16298
16299 },{}],230:[function(require,module,exports){
16300 "use strict";
16301 function isFunction(x) {
16302     return typeof x === 'function';
16303 }
16304 exports.isFunction = isFunction;
16305
16306 },{}],231:[function(require,module,exports){
16307 "use strict";
16308 var isArray_1 = require('../util/isArray');
16309 function isNumeric(val) {
16310     // parseFloat NaNs numeric-cast false positives (null|true|false|"")
16311     // ...but misinterprets leading-number strings, particularly hex literals ("0x...")
16312     // subtraction forces infinities to NaN
16313     // adding 1 corrects loss of precision from parseFloat (#15100)
16314     return !isArray_1.isArray(val) && (val - parseFloat(val) + 1) >= 0;
16315 }
16316 exports.isNumeric = isNumeric;
16317 ;
16318
16319 },{"../util/isArray":227}],232:[function(require,module,exports){
16320 "use strict";
16321 function isObject(x) {
16322     return x != null && typeof x === 'object';
16323 }
16324 exports.isObject = isObject;
16325
16326 },{}],233:[function(require,module,exports){
16327 "use strict";
16328 function isPromise(value) {
16329     return value && typeof value.subscribe !== 'function' && typeof value.then === 'function';
16330 }
16331 exports.isPromise = isPromise;
16332
16333 },{}],234:[function(require,module,exports){
16334 "use strict";
16335 function isScheduler(value) {
16336     return value && typeof value.schedule === 'function';
16337 }
16338 exports.isScheduler = isScheduler;
16339
16340 },{}],235:[function(require,module,exports){
16341 "use strict";
16342 /* tslint:disable:no-empty */
16343 function noop() { }
16344 exports.noop = noop;
16345
16346 },{}],236:[function(require,module,exports){
16347 "use strict";
16348 var noop_1 = require('./noop');
16349 /* tslint:enable:max-line-length */
16350 function pipe() {
16351     var fns = [];
16352     for (var _i = 0; _i < arguments.length; _i++) {
16353         fns[_i - 0] = arguments[_i];
16354     }
16355     return pipeFromArray(fns);
16356 }
16357 exports.pipe = pipe;
16358 /* @internal */
16359 function pipeFromArray(fns) {
16360     if (!fns) {
16361         return noop_1.noop;
16362     }
16363     if (fns.length === 1) {
16364         return fns[0];
16365     }
16366     return function piped(input) {
16367         return fns.reduce(function (prev, fn) { return fn(prev); }, input);
16368     };
16369 }
16370 exports.pipeFromArray = pipeFromArray;
16371
16372 },{"./noop":235}],237:[function(require,module,exports){
16373 (function (global){
16374 "use strict";
16375 // CommonJS / Node have global context exposed as "global" variable.
16376 // We don't want to include the whole node.d.ts this this compilation unit so we'll just fake
16377 // the global "global" var for now.
16378 var __window = typeof window !== 'undefined' && window;
16379 var __self = typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' &&
16380     self instanceof WorkerGlobalScope && self;
16381 var __global = typeof global !== 'undefined' && global;
16382 var _root = __window || __global || __self;
16383 exports.root = _root;
16384 // Workaround Closure Compiler restriction: The body of a goog.module cannot use throw.
16385 // This is needed when used with angular/tsickle which inserts a goog.module statement.
16386 // Wrap in IIFE
16387 (function () {
16388     if (!_root) {
16389         throw new Error('RxJS could not find any global context (window, self, global)');
16390     }
16391 })();
16392
16393 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
16394
16395 },{}],238:[function(require,module,exports){
16396 "use strict";
16397 var root_1 = require('./root');
16398 var isArrayLike_1 = require('./isArrayLike');
16399 var isPromise_1 = require('./isPromise');
16400 var isObject_1 = require('./isObject');
16401 var Observable_1 = require('../Observable');
16402 var iterator_1 = require('../symbol/iterator');
16403 var InnerSubscriber_1 = require('../InnerSubscriber');
16404 var observable_1 = require('../symbol/observable');
16405 function subscribeToResult(outerSubscriber, result, outerValue, outerIndex) {
16406     var destination = new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex);
16407     if (destination.closed) {
16408         return null;
16409     }
16410     if (result instanceof Observable_1.Observable) {
16411         if (result._isScalar) {
16412             destination.next(result.value);
16413             destination.complete();
16414             return null;
16415         }
16416         else {
16417             destination.syncErrorThrowable = true;
16418             return result.subscribe(destination);
16419         }
16420     }
16421     else if (isArrayLike_1.isArrayLike(result)) {
16422         for (var i = 0, len = result.length; i < len && !destination.closed; i++) {
16423             destination.next(result[i]);
16424         }
16425         if (!destination.closed) {
16426             destination.complete();
16427         }
16428     }
16429     else if (isPromise_1.isPromise(result)) {
16430         result.then(function (value) {
16431             if (!destination.closed) {
16432                 destination.next(value);
16433                 destination.complete();
16434             }
16435         }, function (err) { return destination.error(err); })
16436             .then(null, function (err) {
16437             // Escaping the Promise trap: globally throw unhandled errors
16438             root_1.root.setTimeout(function () { throw err; });
16439         });
16440         return destination;
16441     }
16442     else if (result && typeof result[iterator_1.iterator] === 'function') {
16443         var iterator = result[iterator_1.iterator]();
16444         do {
16445             var item = iterator.next();
16446             if (item.done) {
16447                 destination.complete();
16448                 break;
16449             }
16450             destination.next(item.value);
16451             if (destination.closed) {
16452                 break;
16453             }
16454         } while (true);
16455     }
16456     else if (result && typeof result[observable_1.observable] === 'function') {
16457         var obs = result[observable_1.observable]();
16458         if (typeof obs.subscribe !== 'function') {
16459             destination.error(new TypeError('Provided object does not correctly implement Symbol.observable'));
16460         }
16461         else {
16462             return obs.subscribe(new InnerSubscriber_1.InnerSubscriber(outerSubscriber, outerValue, outerIndex));
16463         }
16464     }
16465     else {
16466         var value = isObject_1.isObject(result) ? 'an invalid object' : "'" + result + "'";
16467         var msg = ("You provided " + value + " where a stream was expected.")
16468             + ' You can provide an Observable, Promise, Array, or Iterable.';
16469         destination.error(new TypeError(msg));
16470     }
16471     return null;
16472 }
16473 exports.subscribeToResult = subscribeToResult;
16474
16475 },{"../InnerSubscriber":27,"../Observable":29,"../symbol/iterator":215,"../symbol/observable":216,"./isArrayLike":228,"./isObject":232,"./isPromise":233,"./root":237}],239:[function(require,module,exports){
16476 "use strict";
16477 var Subscriber_1 = require('../Subscriber');
16478 var rxSubscriber_1 = require('../symbol/rxSubscriber');
16479 var Observer_1 = require('../Observer');
16480 function toSubscriber(nextOrObserver, error, complete) {
16481     if (nextOrObserver) {
16482         if (nextOrObserver instanceof Subscriber_1.Subscriber) {
16483             return nextOrObserver;
16484         }
16485         if (nextOrObserver[rxSubscriber_1.rxSubscriber]) {
16486             return nextOrObserver[rxSubscriber_1.rxSubscriber]();
16487         }
16488     }
16489     if (!nextOrObserver && !error && !complete) {
16490         return new Subscriber_1.Subscriber(Observer_1.empty);
16491     }
16492     return new Subscriber_1.Subscriber(nextOrObserver, error, complete);
16493 }
16494 exports.toSubscriber = toSubscriber;
16495
16496 },{"../Observer":30,"../Subscriber":36,"../symbol/rxSubscriber":217}],240:[function(require,module,exports){
16497 "use strict";
16498 var errorObject_1 = require('./errorObject');
16499 var tryCatchTarget;
16500 function tryCatcher() {
16501     try {
16502         return tryCatchTarget.apply(this, arguments);
16503     }
16504     catch (e) {
16505         errorObject_1.errorObject.e = e;
16506         return errorObject_1.errorObject;
16507     }
16508 }
16509 function tryCatch(fn) {
16510     tryCatchTarget = fn;
16511     return tryCatcher;
16512 }
16513 exports.tryCatch = tryCatch;
16514 ;
16515
16516 },{"./errorObject":225}],241:[function(require,module,exports){
16517 // threejs.org/license
16518 (function(m,ja){"object"===typeof exports&&"undefined"!==typeof module?ja(exports):"function"===typeof define&&define.amd?define(["exports"],ja):ja(m.THREE=m.THREE||{})})(this,function(m){function ja(){}function C(a,b){this.x=a||0;this.y=b||0}function K(){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];0<arguments.length&&console.error("THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.")}function Z(a,b,c,d){this._x=a||0;this._y=b||0;this._z=c||0;this._w=void 0!==d?d:1}
16519 function p(a,b,c){this.x=a||0;this.y=b||0;this.z=c||0}function ra(){this.elements=[1,0,0,0,1,0,0,0,1];0<arguments.length&&console.error("THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.")}function ea(a,b,c,d,e,f,g,h,k,l){Object.defineProperty(this,"id",{value:kf++});this.uuid=R.generateUUID();this.name="";this.image=void 0!==a?a:ea.DEFAULT_IMAGE;this.mipmaps=[];this.mapping=void 0!==b?b:ea.DEFAULT_MAPPING;this.wrapS=void 0!==c?c:1001;this.wrapT=void 0!==d?d:1001;this.magFilter=
16520 void 0!==e?e:1006;this.minFilter=void 0!==f?f:1008;this.anisotropy=void 0!==k?k:1;this.format=void 0!==g?g:1023;this.type=void 0!==h?h:1009;this.offset=new C(0,0);this.repeat=new C(1,1);this.center=new C(0,0);this.rotation=0;this.matrixAutoUpdate=!0;this.matrix=new ra;this.generateMipmaps=!0;this.premultiplyAlpha=!1;this.flipY=!0;this.unpackAlignment=4;this.encoding=void 0!==l?l:3E3;this.version=0;this.onUpdate=null}function da(a,b,c,d){this.x=a||0;this.y=b||0;this.z=c||0;this.w=void 0!==d?d:1}function Hb(a,
16521 b,c){this.uuid=R.generateUUID();this.width=a;this.height=b;this.scissor=new da(0,0,a,b);this.scissorTest=!1;this.viewport=new da(0,0,a,b);c=c||{};void 0===c.minFilter&&(c.minFilter=1006);this.texture=new ea(void 0,void 0,c.wrapS,c.wrapT,c.magFilter,c.minFilter,c.format,c.type,c.anisotropy,c.encoding);this.depthBuffer=void 0!==c.depthBuffer?c.depthBuffer:!0;this.stencilBuffer=void 0!==c.stencilBuffer?c.stencilBuffer:!0;this.depthTexture=void 0!==c.depthTexture?c.depthTexture:null}function Ib(a,b,c){Hb.call(this,
16522 a,b,c);this.activeMipMapLevel=this.activeCubeFace=0}function fb(a,b,c,d,e,f,g,h,k,l,q,n){ea.call(this,null,f,g,h,k,l,d,e,q,n);this.image={data:a,width:b,height:c};this.magFilter=void 0!==k?k:1003;this.minFilter=void 0!==l?l:1003;this.flipY=this.generateMipmaps=!1;this.unpackAlignment=1}function Ua(a,b,c,d,e,f,g,h,k,l){a=void 0!==a?a:[];ea.call(this,a,void 0!==b?b:301,c,d,e,f,g,h,k,l);this.flipY=!1}function Jb(a,b,c){var d=a[0];if(0>=d||0<d)return a;var e=b*c,f=we[e];void 0===f&&(f=new Float32Array(e),
16523 we[e]=f);if(0!==b)for(d.toArray(f,0),d=1,e=0;d!==b;++d)e+=c,a[d].toArray(f,e);return f}function xe(a,b){var c=ye[b];void 0===c&&(c=new Int32Array(b),ye[b]=c);for(var d=0;d!==b;++d)c[d]=a.allocTextureUnit();return c}function lf(a,b){a.uniform1f(this.addr,b)}function mf(a,b){a.uniform1i(this.addr,b)}function nf(a,b){void 0===b.x?a.uniform2fv(this.addr,b):a.uniform2f(this.addr,b.x,b.y)}function of(a,b){void 0!==b.x?a.uniform3f(this.addr,b.x,b.y,b.z):void 0!==b.r?a.uniform3f(this.addr,b.r,b.g,b.b):a.uniform3fv(this.addr,
16524 b)}function pf(a,b){void 0===b.x?a.uniform4fv(this.addr,b):a.uniform4f(this.addr,b.x,b.y,b.z,b.w)}function qf(a,b){a.uniformMatrix2fv(this.addr,!1,b.elements||b)}function rf(a,b){void 0===b.elements?a.uniformMatrix3fv(this.addr,!1,b):(ze.set(b.elements),a.uniformMatrix3fv(this.addr,!1,ze))}function sf(a,b){void 0===b.elements?a.uniformMatrix4fv(this.addr,!1,b):(Ae.set(b.elements),a.uniformMatrix4fv(this.addr,!1,Ae))}function tf(a,b,c){var d=c.allocTextureUnit();a.uniform1i(this.addr,d);c.setTexture2D(b||
16525 Be,d)}function uf(a,b,c){var d=c.allocTextureUnit();a.uniform1i(this.addr,d);c.setTextureCube(b||Ce,d)}function De(a,b){a.uniform2iv(this.addr,b)}function Ee(a,b){a.uniform3iv(this.addr,b)}function Fe(a,b){a.uniform4iv(this.addr,b)}function vf(a){switch(a){case 5126:return lf;case 35664:return nf;case 35665:return of;case 35666:return pf;case 35674:return qf;case 35675:return rf;case 35676:return sf;case 35678:case 36198:return tf;case 35680:return uf;case 5124:case 35670:return mf;case 35667:case 35671:return De;
16526 case 35668:case 35672:return Ee;case 35669:case 35673:return Fe}}function wf(a,b){a.uniform1fv(this.addr,b)}function xf(a,b){a.uniform1iv(this.addr,b)}function yf(a,b){a.uniform2fv(this.addr,Jb(b,this.size,2))}function zf(a,b){a.uniform3fv(this.addr,Jb(b,this.size,3))}function Af(a,b){a.uniform4fv(this.addr,Jb(b,this.size,4))}function Bf(a,b){a.uniformMatrix2fv(this.addr,!1,Jb(b,this.size,4))}function Cf(a,b){a.uniformMatrix3fv(this.addr,!1,Jb(b,this.size,9))}function Df(a,b){a.uniformMatrix4fv(this.addr,
16527 !1,Jb(b,this.size,16))}function Ef(a,b,c){var d=b.length,e=xe(c,d);a.uniform1iv(this.addr,e);for(a=0;a!==d;++a)c.setTexture2D(b[a]||Be,e[a])}function Ff(a,b,c){var d=b.length,e=xe(c,d);a.uniform1iv(this.addr,e);for(a=0;a!==d;++a)c.setTextureCube(b[a]||Ce,e[a])}function Gf(a){switch(a){case 5126:return wf;case 35664:return yf;case 35665:return zf;case 35666:return Af;case 35674:return Bf;case 35675:return Cf;case 35676:return Df;case 35678:return Ef;case 35680:return Ff;case 5124:case 35670:return xf;
16528 case 35667:case 35671:return De;case 35668:case 35672:return Ee;case 35669:case 35673:return Fe}}function Hf(a,b,c){this.id=a;this.addr=c;this.setValue=vf(b.type)}function If(a,b,c){this.id=a;this.addr=c;this.size=b.size;this.setValue=Gf(b.type)}function Ge(a){this.id=a;this.seq=[];this.map={}}function gb(a,b,c){this.seq=[];this.map={};this.renderer=c;c=a.getProgramParameter(b,a.ACTIVE_UNIFORMS);for(var d=0;d<c;++d){var e=a.getActiveUniform(b,d),f=a.getUniformLocation(b,e.name),g=this,h=e.name,k=
16529 h.length;for(Od.lastIndex=0;;){var l=Od.exec(h),q=Od.lastIndex,n=l[1],t=l[3];"]"===l[2]&&(n|=0);if(void 0===t||"["===t&&q+2===k){h=g;e=void 0===t?new Hf(n,e,f):new If(n,e,f);h.seq.push(e);h.map[e.id]=e;break}else t=g.map[n],void 0===t&&(t=new Ge(n),n=g,g=t,n.seq.push(g),n.map[g.id]=g),g=t}}}function H(a,b,c){return void 0===b&&void 0===c?this.set(a):this.setRGB(a,b,c)}function kd(a,b){this.min=void 0!==a?a:new C(Infinity,Infinity);this.max=void 0!==b?b:new C(-Infinity,-Infinity)}function Jf(a,b,c,
16530 d,e){var f,g,h,k,l,q,n,t,r,m,v,w,x,z,I,B;this.render=function(a,u,za,la){if(0!==a.length){u=new p;var J=la.w/la.z,ta=.5*la.z,Va=.5*la.w,L=16/la.w,Y=new C(L*J,L),ua=new p(1,1,0),M=new C(1,1),V=new kd;V.min.set(la.x,la.y);V.max.set(la.x+(la.z-16),la.y+(la.w-16));if(void 0===z){var L=new Float32Array([-1,-1,0,0,1,-1,1,0,1,1,1,1,-1,1,0,1]),y=new Uint16Array([0,1,2,0,2,3]);v=b.createBuffer();w=b.createBuffer();b.bindBuffer(b.ARRAY_BUFFER,v);b.bufferData(b.ARRAY_BUFFER,L,b.STATIC_DRAW);b.bindBuffer(b.ELEMENT_ARRAY_BUFFER,
16531 w);b.bufferData(b.ELEMENT_ARRAY_BUFFER,y,b.STATIC_DRAW);I=b.createTexture();B=b.createTexture();c.bindTexture(b.TEXTURE_2D,I);b.texImage2D(b.TEXTURE_2D,0,b.RGB,16,16,0,b.RGB,b.UNSIGNED_BYTE,null);b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_S,b.CLAMP_TO_EDGE);b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_T,b.CLAMP_TO_EDGE);b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MAG_FILTER,b.NEAREST);b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MIN_FILTER,b.NEAREST);c.bindTexture(b.TEXTURE_2D,B);b.texImage2D(b.TEXTURE_2D,0,
16532 b.RGBA,16,16,0,b.RGBA,b.UNSIGNED_BYTE,null);b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_S,b.CLAMP_TO_EDGE);b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_T,b.CLAMP_TO_EDGE);b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MAG_FILTER,b.NEAREST);b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MIN_FILTER,b.NEAREST);var L=x={vertexShader:"uniform lowp int renderType;\nuniform vec3 screenPosition;\nuniform vec2 scale;\nuniform float rotation;\nuniform sampler2D occlusionMap;\nattribute vec2 position;\nattribute vec2 uv;\nvarying vec2 vUV;\nvarying float vVisibility;\nvoid main() {\n\tvUV = uv;\n\tvec2 pos = position;\n\tif ( renderType == 2 ) {\n\t\tvec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );\n\t\tvisibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );\n\t\tvisibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );\n\t\tvisibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );\n\t\tvisibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );\n\t\tvisibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );\n\t\tvisibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );\n\t\tvisibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );\n\t\tvisibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );\n\t\tvVisibility =        visibility.r / 9.0;\n\t\tvVisibility *= 1.0 - visibility.g / 9.0;\n\t\tvVisibility *=       visibility.b / 9.0;\n\t\tvVisibility *= 1.0 - visibility.a / 9.0;\n\t\tpos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;\n\t\tpos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;\n\t}\n\tgl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );\n}",
16533 fragmentShader:"uniform lowp int renderType;\nuniform sampler2D map;\nuniform float opacity;\nuniform vec3 color;\nvarying vec2 vUV;\nvarying float vVisibility;\nvoid main() {\n\tif ( renderType == 0 ) {\n\t\tgl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );\n\t} else if ( renderType == 1 ) {\n\t\tgl_FragColor = texture2D( map, vUV );\n\t} else {\n\t\tvec4 texture = texture2D( map, vUV );\n\t\ttexture.a *= opacity * vVisibility;\n\t\tgl_FragColor = texture;\n\t\tgl_FragColor.rgb *= color;\n\t}\n}"},y=b.createProgram(),
16534 A=b.createShader(b.FRAGMENT_SHADER),aa=b.createShader(b.VERTEX_SHADER),D="precision "+e.precision+" float;\n";b.shaderSource(A,D+L.fragmentShader);b.shaderSource(aa,D+L.vertexShader);b.compileShader(A);b.compileShader(aa);b.attachShader(y,A);b.attachShader(y,aa);b.linkProgram(y);z=y;r=b.getAttribLocation(z,"position");m=b.getAttribLocation(z,"uv");f=b.getUniformLocation(z,"renderType");g=b.getUniformLocation(z,"map");h=b.getUniformLocation(z,"occlusionMap");k=b.getUniformLocation(z,"opacity");l=b.getUniformLocation(z,
16535 "color");q=b.getUniformLocation(z,"scale");n=b.getUniformLocation(z,"rotation");t=b.getUniformLocation(z,"screenPosition")}c.useProgram(z);c.initAttributes();c.enableAttribute(r);c.enableAttribute(m);c.disableUnusedAttributes();b.uniform1i(h,0);b.uniform1i(g,1);b.bindBuffer(b.ARRAY_BUFFER,v);b.vertexAttribPointer(r,2,b.FLOAT,!1,16,0);b.vertexAttribPointer(m,2,b.FLOAT,!1,16,8);b.bindBuffer(b.ELEMENT_ARRAY_BUFFER,w);c.disable(b.CULL_FACE);c.buffers.depth.setMask(!1);y=0;for(A=a.length;y<A;y++)if(L=
16536 16/la.w,Y.set(L*J,L),aa=a[y],u.set(aa.matrixWorld.elements[12],aa.matrixWorld.elements[13],aa.matrixWorld.elements[14]),u.applyMatrix4(za.matrixWorldInverse),u.applyMatrix4(za.projectionMatrix),ua.copy(u),M.x=la.x+ua.x*ta+ta-8,M.y=la.y+ua.y*Va+Va-8,!0===V.containsPoint(M)){c.activeTexture(b.TEXTURE0);c.bindTexture(b.TEXTURE_2D,null);c.activeTexture(b.TEXTURE1);c.bindTexture(b.TEXTURE_2D,I);b.copyTexImage2D(b.TEXTURE_2D,0,b.RGB,M.x,M.y,16,16,0);b.uniform1i(f,0);b.uniform2f(q,Y.x,Y.y);b.uniform3f(t,
16537 ua.x,ua.y,ua.z);c.disable(b.BLEND);c.enable(b.DEPTH_TEST);b.drawElements(b.TRIANGLES,6,b.UNSIGNED_SHORT,0);c.activeTexture(b.TEXTURE0);c.bindTexture(b.TEXTURE_2D,B);b.copyTexImage2D(b.TEXTURE_2D,0,b.RGBA,M.x,M.y,16,16,0);b.uniform1i(f,1);c.disable(b.DEPTH_TEST);c.activeTexture(b.TEXTURE1);c.bindTexture(b.TEXTURE_2D,I);b.drawElements(b.TRIANGLES,6,b.UNSIGNED_SHORT,0);aa.positionScreen.copy(ua);aa.customUpdateCallback?aa.customUpdateCallback(aa):aa.updateLensFlares();b.uniform1i(f,2);c.enable(b.BLEND);
16538 for(var D=0,H=aa.lensFlares.length;D<H;D++){var E=aa.lensFlares[D];.001<E.opacity&&.001<E.scale&&(ua.x=E.x,ua.y=E.y,ua.z=E.z,L=E.size*E.scale/la.w,Y.x=L*J,Y.y=L,b.uniform3f(t,ua.x,ua.y,ua.z),b.uniform2f(q,Y.x,Y.y),b.uniform1f(n,E.rotation),b.uniform1f(k,E.opacity),b.uniform3f(l,E.color.r,E.color.g,E.color.b),c.setBlending(E.blending,E.blendEquation,E.blendSrc,E.blendDst),d.setTexture2D(E.texture,1),b.drawElements(b.TRIANGLES,6,b.UNSIGNED_SHORT,0))}}c.enable(b.CULL_FACE);c.enable(b.DEPTH_TEST);c.buffers.depth.setMask(!0);
16539 c.reset()}}}function tc(a,b,c,d,e,f,g,h,k){ea.call(this,a,b,c,d,e,f,g,h,k);this.needsUpdate=!0}function Kf(a,b,c,d,e){var f,g,h,k,l,q,n,t,r,m,v,w,x,z,I,B,J;function ta(a,b){return a.renderOrder!==b.renderOrder?a.renderOrder-b.renderOrder:a.z!==b.z?b.z-a.z:b.id-a.id}var za,la,ha,He,Va=new p,L=new Z,C=new p;this.render=function(u,p,V){if(0!==u.length){if(void 0===ha){var M=new Float32Array([-.5,-.5,0,0,.5,-.5,1,0,.5,.5,1,1,-.5,.5,0,1]),y=new Uint16Array([0,1,2,0,2,3]);za=b.createBuffer();la=b.createBuffer();
16540 b.bindBuffer(b.ARRAY_BUFFER,za);b.bufferData(b.ARRAY_BUFFER,M,b.STATIC_DRAW);b.bindBuffer(b.ELEMENT_ARRAY_BUFFER,la);b.bufferData(b.ELEMENT_ARRAY_BUFFER,y,b.STATIC_DRAW);M=b.createProgram();y=b.createShader(b.VERTEX_SHADER);var Y=b.createShader(b.FRAGMENT_SHADER);b.shaderSource(y,["precision "+e.precision+" float;","#define SHADER_NAME SpriteMaterial\nuniform mat4 modelViewMatrix;\nuniform mat4 projectionMatrix;\nuniform float rotation;\nuniform vec2 scale;\nuniform vec2 uvOffset;\nuniform vec2 uvScale;\nattribute vec2 position;\nattribute vec2 uv;\nvarying vec2 vUV;\nvarying float fogDepth;\nvoid main() {\n\tvUV = uvOffset + uv * uvScale;\n\tvec2 alignedPosition = position * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tvec4 mvPosition;\n\tmvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\tfogDepth = - mvPosition.z;\n}"].join("\n"));
16541 b.shaderSource(Y,["precision "+e.precision+" float;","#define SHADER_NAME SpriteMaterial\nuniform vec3 color;\nuniform sampler2D map;\nuniform float opacity;\nuniform int fogType;\nuniform vec3 fogColor;\nuniform float fogDensity;\nuniform float fogNear;\nuniform float fogFar;\nuniform float alphaTest;\nvarying vec2 vUV;\nvarying float fogDepth;\nvoid main() {\n\tvec4 texture = texture2D( map, vUV );\n\tgl_FragColor = vec4( color * texture.xyz, texture.a * opacity );\n\tif ( gl_FragColor.a < alphaTest ) discard;\n\tif ( fogType > 0 ) {\n\t\tfloat fogFactor = 0.0;\n\t\tif ( fogType == 1 ) {\n\t\t\tfogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t\t} else {\n\t\t\tconst float LOG2 = 1.442695;\n\t\t\tfogFactor = exp2( - fogDensity * fogDensity * fogDepth * fogDepth * LOG2 );\n\t\t\tfogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );\n\t\t}\n\t\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n\t}\n}"].join("\n"));
16542 b.compileShader(y);b.compileShader(Y);b.attachShader(M,y);b.attachShader(M,Y);b.linkProgram(M);ha=M;B=b.getAttribLocation(ha,"position");J=b.getAttribLocation(ha,"uv");f=b.getUniformLocation(ha,"uvOffset");g=b.getUniformLocation(ha,"uvScale");h=b.getUniformLocation(ha,"rotation");k=b.getUniformLocation(ha,"scale");l=b.getUniformLocation(ha,"color");q=b.getUniformLocation(ha,"map");n=b.getUniformLocation(ha,"opacity");t=b.getUniformLocation(ha,"modelViewMatrix");r=b.getUniformLocation(ha,"projectionMatrix");
16543 m=b.getUniformLocation(ha,"fogType");v=b.getUniformLocation(ha,"fogDensity");w=b.getUniformLocation(ha,"fogNear");x=b.getUniformLocation(ha,"fogFar");z=b.getUniformLocation(ha,"fogColor");b.getUniformLocation(ha,"fogDepth");I=b.getUniformLocation(ha,"alphaTest");M=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");M.width=8;M.height=8;y=M.getContext("2d");y.fillStyle="white";y.fillRect(0,0,8,8);He=new tc(M)}c.useProgram(ha);c.initAttributes();c.enableAttribute(B);c.enableAttribute(J);
16544 c.disableUnusedAttributes();c.disable(b.CULL_FACE);c.enable(b.BLEND);b.bindBuffer(b.ARRAY_BUFFER,za);b.vertexAttribPointer(B,2,b.FLOAT,!1,16,0);b.vertexAttribPointer(J,2,b.FLOAT,!1,16,8);b.bindBuffer(b.ELEMENT_ARRAY_BUFFER,la);b.uniformMatrix4fv(r,!1,V.projectionMatrix.elements);c.activeTexture(b.TEXTURE0);b.uniform1i(q,0);y=M=0;(Y=p.fog)?(b.uniform3f(z,Y.color.r,Y.color.g,Y.color.b),Y.isFog?(b.uniform1f(w,Y.near),b.uniform1f(x,Y.far),b.uniform1i(m,1),y=M=1):Y.isFogExp2&&(b.uniform1f(v,Y.density),
16545 b.uniform1i(m,2),y=M=2)):(b.uniform1i(m,0),y=M=0);for(var A=0,ua=u.length;A<ua;A++)Y=u[A],Y.modelViewMatrix.multiplyMatrices(V.matrixWorldInverse,Y.matrixWorld),Y.z=-Y.modelViewMatrix.elements[14];u.sort(ta);for(var E=[],A=0,ua=u.length;A<ua;A++){Y=u[A];var G=Y.material;if(!1!==G.visible){Y.onBeforeRender(a,p,V,void 0,G,void 0);b.uniform1f(I,G.alphaTest);b.uniformMatrix4fv(t,!1,Y.modelViewMatrix.elements);Y.matrixWorld.decompose(Va,L,C);E[0]=C.x;E[1]=C.y;var D=0;p.fog&&G.fog&&(D=y);M!==D&&(b.uniform1i(m,
16546 D),M=D);null!==G.map?(b.uniform2f(f,G.map.offset.x,G.map.offset.y),b.uniform2f(g,G.map.repeat.x,G.map.repeat.y)):(b.uniform2f(f,0,0),b.uniform2f(g,1,1));b.uniform1f(n,G.opacity);b.uniform3f(l,G.color.r,G.color.g,G.color.b);b.uniform1f(h,G.rotation);b.uniform2fv(k,E);c.setBlending(G.blending,G.blendEquation,G.blendSrc,G.blendDst,G.blendEquationAlpha,G.blendSrcAlpha,G.blendDstAlpha,G.premultipliedAlpha);c.buffers.depth.setTest(G.depthTest);c.buffers.depth.setMask(G.depthWrite);c.buffers.color.setMask(G.colorWrite);
16547 d.setTexture2D(G.map||He,0);b.drawElements(b.TRIANGLES,6,b.UNSIGNED_SHORT,0);Y.onAfterRender(a,p,V,void 0,G,void 0)}}c.enable(b.CULL_FACE);c.reset()}}}function Q(){Object.defineProperty(this,"id",{value:Lf++});this.uuid=R.generateUUID();this.name="";this.type="Material";this.lights=this.fog=!0;this.blending=1;this.side=0;this.flatShading=!1;this.vertexColors=0;this.opacity=1;this.transparent=!1;this.blendSrc=204;this.blendDst=205;this.blendEquation=100;this.blendEquationAlpha=this.blendDstAlpha=this.blendSrcAlpha=
16548 null;this.depthFunc=3;this.depthWrite=this.depthTest=!0;this.clippingPlanes=null;this.clipShadows=this.clipIntersection=!1;this.colorWrite=!0;this.precision=null;this.polygonOffset=!1;this.polygonOffsetUnits=this.polygonOffsetFactor=0;this.dithering=!1;this.alphaTest=0;this.premultipliedAlpha=!1;this.overdraw=0;this.visible=!0;this.userData={};this.needsUpdate=!0}function Wa(a){Q.call(this);this.type="MeshDepthMaterial";this.depthPacking=3200;this.morphTargets=this.skinning=!1;this.displacementMap=
16549 this.alphaMap=this.map=null;this.displacementScale=1;this.displacementBias=0;this.wireframe=!1;this.wireframeLinewidth=1;this.lights=this.fog=!1;this.setValues(a)}function Xa(a){Q.call(this);this.type="MeshDistanceMaterial";this.referencePosition=new p;this.nearDistance=1;this.farDistance=1E3;this.morphTargets=this.skinning=!1;this.displacementMap=this.alphaMap=this.map=null;this.displacementScale=1;this.displacementBias=0;this.lights=this.fog=!1;this.setValues(a)}function Oa(a,b){this.min=void 0!==
16550 a?a:new p(Infinity,Infinity,Infinity);this.max=void 0!==b?b:new p(-Infinity,-Infinity,-Infinity)}function Da(a,b){this.center=void 0!==a?a:new p;this.radius=void 0!==b?b:0}function Aa(a,b){this.normal=void 0!==a?a:new p(1,0,0);this.constant=void 0!==b?b:0}function ld(a,b,c,d,e,f){this.planes=[void 0!==a?a:new Aa,void 0!==b?b:new Aa,void 0!==c?c:new Aa,void 0!==d?d:new Aa,void 0!==e?e:new Aa,void 0!==f?f:new Aa]}function Ie(a,b,c){function d(b,c,d,e,f,g){var h=b.geometry;var k=n;var l=b.customDepthMaterial;
16551 d&&(k=t,l=b.customDistanceMaterial);l?k=l:(l=!1,c.morphTargets&&(h&&h.isBufferGeometry?l=h.morphAttributes&&h.morphAttributes.position&&0<h.morphAttributes.position.length:h&&h.isGeometry&&(l=h.morphTargets&&0<h.morphTargets.length)),b.isSkinnedMesh&&!1===c.skinning&&console.warn("THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:",b),b=b.isSkinnedMesh&&c.skinning,h=0,l&&(h|=1),b&&(h|=2),k=k[h]);a.localClippingEnabled&&!0===c.clipShadows&&0!==c.clippingPlanes.length&&(h=
16552 k.uuid,l=c.uuid,b=r[h],void 0===b&&(b={},r[h]=b),h=b[l],void 0===h&&(h=k.clone(),b[l]=h),k=h);k.visible=c.visible;k.wireframe=c.wireframe;l=c.side;B.renderSingleSided&&2==l&&(l=0);B.renderReverseSided&&(0===l?l=1:1===l&&(l=0));k.side=l;k.clipShadows=c.clipShadows;k.clippingPlanes=c.clippingPlanes;k.clipIntersection=c.clipIntersection;k.wireframeLinewidth=c.wireframeLinewidth;k.linewidth=c.linewidth;d&&k.isMeshDistanceMaterial&&(k.referencePosition.copy(e),k.nearDistance=f,k.farDistance=g);return k}
16553 function e(c,g,h,k){var l;if(!1!==c.visible){if(c.layers.test(g.layers)&&(c.isMesh||c.isLine||c.isPoints)&&c.castShadow&&(!c.frustumCulled||f.intersectsObject(c))){c.modelViewMatrix.multiplyMatrices(h.matrixWorldInverse,c.matrixWorld);var n=b.update(c),t=c.material;if(Array.isArray(t))for(var r=n.groups,m=0,z=r.length;m<z;m++){var u=r[m];(l=t[u.materialIndex])&&l.visible&&(l=d(c,l,k,q,h.near,h.far),a.renderBufferDirect(h,null,n,l,c,u))}else t.visible&&(l=d(c,t,k,q,h.near,h.far),a.renderBufferDirect(h,
16554 null,n,l,c,null))}c=c.children;n=0;for(t=c.length;n<t;n++)e(c[n],g,h,k)}}var f=new ld,g=new K,h=new C,k=new C(c,c),l=new p,q=new p,n=Array(4),t=Array(4),r={},m=[new p(1,0,0),new p(-1,0,0),new p(0,0,1),new p(0,0,-1),new p(0,1,0),new p(0,-1,0)],v=[new p(0,1,0),new p(0,1,0),new p(0,1,0),new p(0,1,0),new p(0,0,1),new p(0,0,-1)],w=[new da,new da,new da,new da,new da,new da];for(c=0;4!==c;++c){var x=0!==(c&1),z=0!==(c&2),I=new Wa({depthPacking:3201,morphTargets:x,skinning:z});n[c]=I;x=new Xa({morphTargets:x,
16555 skinning:z});t[c]=x}var B=this;this.enabled=!1;this.autoUpdate=!0;this.needsUpdate=!1;this.type=1;this.renderSingleSided=this.renderReverseSided=!0;this.render=function(b,c,d){if(!1!==B.enabled&&(!1!==B.autoUpdate||!1!==B.needsUpdate)&&0!==b.length){var n=a.state;n.disable(a.context.BLEND);n.buffers.color.setClear(1,1,1,1);n.buffers.depth.setTest(!0);n.setScissorTest(!1);for(var t,r=0,z=b.length;r<z;r++){var u=b[r];t=u.shadow;var I=u&&u.isPointLight;if(void 0===t)console.warn("THREE.WebGLShadowMap:",
16556 u,"has no shadow.");else{var p=t.camera;h.copy(t.mapSize);h.min(k);if(I){var x=h.x,J=h.y;w[0].set(2*x,J,x,J);w[1].set(0,J,x,J);w[2].set(3*x,J,x,J);w[3].set(x,J,x,J);w[4].set(3*x,0,x,J);w[5].set(x,0,x,J);h.x*=4;h.y*=2}null===t.map&&(t.map=new Hb(h.x,h.y,{minFilter:1003,magFilter:1003,format:1023}),t.map.texture.name=u.name+".shadowMap",p.updateProjectionMatrix());t.isSpotLightShadow&&t.update(u);x=t.map;J=t.matrix;q.setFromMatrixPosition(u.matrixWorld);p.position.copy(q);I?(t=6,J.makeTranslation(-q.x,
16557 -q.y,-q.z)):(t=1,l.setFromMatrixPosition(u.target.matrixWorld),p.lookAt(l),p.updateMatrixWorld(),J.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),J.multiply(p.projectionMatrix),J.multiply(p.matrixWorldInverse));a.setRenderTarget(x);a.clear();for(u=0;u<t;u++)I&&(l.copy(p.position),l.add(m[u]),p.up.copy(v[u]),p.lookAt(l),p.updateMatrixWorld(),n.viewport(w[u])),g.multiplyMatrices(p.projectionMatrix,p.matrixWorldInverse),f.setFromMatrix(g),e(c,d,p,I)}}B.needsUpdate=!1}}}function Mf(a){var b={};return{get:function(a){a.isInterleavedBufferAttribute&&
16558 (a=a.data);return b[a.uuid]},remove:function(c){c.isInterleavedBufferAttribute&&(c=c.data);var d=b[c.uuid];d&&(a.deleteBuffer(d.buffer),delete b[c.uuid])},update:function(c,d){c.isInterleavedBufferAttribute&&(c=c.data);var e=b[c.uuid];if(void 0===e){var e=c.uuid,f=c.array,g=c.dynamic?a.DYNAMIC_DRAW:a.STATIC_DRAW,h=a.createBuffer();a.bindBuffer(d,h);a.bufferData(d,f,g);c.onUploadCallback();d=a.FLOAT;f instanceof Float32Array?d=a.FLOAT:f instanceof Float64Array?console.warn("THREE.WebGLAttributes: Unsupported data buffer format: Float64Array."):
16559 f instanceof Uint16Array?d=a.UNSIGNED_SHORT:f instanceof Int16Array?d=a.SHORT:f instanceof Uint32Array?d=a.UNSIGNED_INT:f instanceof Int32Array?d=a.INT:f instanceof Int8Array?d=a.BYTE:f instanceof Uint8Array&&(d=a.UNSIGNED_BYTE);b[e]={buffer:h,type:d,bytesPerElement:f.BYTES_PER_ELEMENT,version:c.version}}else e.version<c.version&&(f=c,h=f.array,g=f.updateRange,a.bindBuffer(d,e.buffer),!1===f.dynamic?a.bufferData(d,h,a.STATIC_DRAW):-1===g.count?a.bufferSubData(d,0,h):0===g.count?console.error("THREE.WebGLObjects.updateBuffer: dynamic THREE.BufferAttribute marked as needsUpdate but updateRange.count is 0, ensure you are using set methods or updating manually."):
16560 (a.bufferSubData(d,g.offset*h.BYTES_PER_ELEMENT,h.subarray(g.offset,g.offset+g.count)),g.count=-1),e.version=c.version)}}}function Ya(a,b,c,d){this._x=a||0;this._y=b||0;this._z=c||0;this._order=d||Ya.DefaultOrder}function Pd(){this.mask=1}function A(){Object.defineProperty(this,"id",{value:Nf++});this.uuid=R.generateUUID();this.name="";this.type="Object3D";this.parent=null;this.children=[];this.up=A.DefaultUp.clone();var a=new p,b=new Ya,c=new Z,d=new p(1,1,1);b.onChange(function(){c.setFromEuler(b,
16561 !1)});c.onChange(function(){b.setFromQuaternion(c,void 0,!1)});Object.defineProperties(this,{position:{enumerable:!0,value:a},rotation:{enumerable:!0,value:b},quaternion:{enumerable:!0,value:c},scale:{enumerable:!0,value:d},modelViewMatrix:{value:new K},normalMatrix:{value:new ra}});this.matrix=new K;this.matrixWorld=new K;this.matrixAutoUpdate=A.DefaultMatrixAutoUpdate;this.matrixWorldNeedsUpdate=!1;this.layers=new Pd;this.visible=!0;this.receiveShadow=this.castShadow=!1;this.frustumCulled=!0;this.renderOrder=
16562 0;this.userData={}}function La(){A.call(this);this.type="Camera";this.matrixWorldInverse=new K;this.projectionMatrix=new K}function Kb(a,b,c,d,e,f){La.call(this);this.type="OrthographicCamera";this.zoom=1;this.view=null;this.left=a;this.right=b;this.top=c;this.bottom=d;this.near=void 0!==e?e:.1;this.far=void 0!==f?f:2E3;this.updateProjectionMatrix()}function Pa(a,b,c,d,e,f){this.a=a;this.b=b;this.c=c;this.normal=d&&d.isVector3?d:new p;this.vertexNormals=Array.isArray(d)?d:[];this.color=e&&e.isColor?
16563 e:new H;this.vertexColors=Array.isArray(e)?e:[];this.materialIndex=void 0!==f?f:0}function N(){Object.defineProperty(this,"id",{value:Of+=2});this.uuid=R.generateUUID();this.name="";this.type="Geometry";this.vertices=[];this.colors=[];this.faces=[];this.faceVertexUvs=[[]];this.morphTargets=[];this.morphNormals=[];this.skinWeights=[];this.skinIndices=[];this.lineDistances=[];this.boundingSphere=this.boundingBox=null;this.groupsNeedUpdate=this.lineDistancesNeedUpdate=this.colorsNeedUpdate=this.normalsNeedUpdate=
16564 this.uvsNeedUpdate=this.verticesNeedUpdate=this.elementsNeedUpdate=!1}function P(a,b,c){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.uuid=R.generateUUID();this.name="";this.array=a;this.itemSize=b;this.count=void 0!==a?a.length/b:0;this.normalized=!0===c;this.dynamic=!1;this.updateRange={offset:0,count:-1};this.onUploadCallback=function(){};this.version=0}function uc(a,b,c){P.call(this,new Int8Array(a),b,c)}function vc(a,b,c){P.call(this,new Uint8Array(a),
16565 b,c)}function wc(a,b,c){P.call(this,new Uint8ClampedArray(a),b,c)}function xc(a,b,c){P.call(this,new Int16Array(a),b,c)}function hb(a,b,c){P.call(this,new Uint16Array(a),b,c)}function yc(a,b,c){P.call(this,new Int32Array(a),b,c)}function ib(a,b,c){P.call(this,new Uint32Array(a),b,c)}function y(a,b,c){P.call(this,new Float32Array(a),b,c)}function zc(a,b,c){P.call(this,new Float64Array(a),b,c)}function Je(){this.indices=[];this.vertices=[];this.normals=[];this.colors=[];this.uvs=[];this.uvs2=[];this.groups=
16566 [];this.morphTargets={};this.skinWeights=[];this.skinIndices=[];this.boundingSphere=this.boundingBox=null;this.groupsNeedUpdate=this.uvsNeedUpdate=this.colorsNeedUpdate=this.normalsNeedUpdate=this.verticesNeedUpdate=!1}function Qd(a){if(0===a.length)return-Infinity;for(var b=a[0],c=1,d=a.length;c<d;++c)a[c]>b&&(b=a[c]);return b}function D(){Object.defineProperty(this,"id",{value:Pf+=2});this.uuid=R.generateUUID();this.name="";this.type="BufferGeometry";this.index=null;this.attributes={};this.morphAttributes=
16567 {};this.groups=[];this.boundingSphere=this.boundingBox=null;this.drawRange={start:0,count:Infinity}}function Lb(a,b,c,d,e,f){N.call(this);this.type="BoxGeometry";this.parameters={width:a,height:b,depth:c,widthSegments:d,heightSegments:e,depthSegments:f};this.fromBufferGeometry(new jb(a,b,c,d,e,f));this.mergeVertices()}function jb(a,b,c,d,e,f){function g(a,b,c,d,e,f,g,m,ta,za,la){var z=f/ta,u=g/za,v=f/2,w=g/2,I=m/2;g=ta+1;var B=za+1,x=f=0,J,y,C=new p;for(y=0;y<B;y++){var A=y*u-w;for(J=0;J<g;J++)C[a]=
16568 (J*z-v)*d,C[b]=A*e,C[c]=I,l.push(C.x,C.y,C.z),C[a]=0,C[b]=0,C[c]=0<m?1:-1,q.push(C.x,C.y,C.z),n.push(J/ta),n.push(1-y/za),f+=1}for(y=0;y<za;y++)for(J=0;J<ta;J++)a=t+J+g*(y+1),b=t+(J+1)+g*(y+1),c=t+(J+1)+g*y,k.push(t+J+g*y,a,c),k.push(a,b,c),x+=6;h.addGroup(r,x,la);r+=x;t+=f}D.call(this);this.type="BoxBufferGeometry";this.parameters={width:a,height:b,depth:c,widthSegments:d,heightSegments:e,depthSegments:f};var h=this;a=a||1;b=b||1;c=c||1;d=Math.floor(d)||1;e=Math.floor(e)||1;f=Math.floor(f)||1;var k=
16569 [],l=[],q=[],n=[],t=0,r=0;g("z","y","x",-1,-1,c,b,a,f,e,0);g("z","y","x",1,-1,c,b,-a,f,e,1);g("x","z","y",1,1,a,c,b,d,f,2);g("x","z","y",1,-1,a,c,-b,d,f,3);g("x","y","z",1,-1,a,b,c,d,e,4);g("x","y","z",-1,-1,a,b,-c,d,e,5);this.setIndex(k);this.addAttribute("position",new y(l,3));this.addAttribute("normal",new y(q,3));this.addAttribute("uv",new y(n,2))}function Ac(a,b,c,d){N.call(this);this.type="PlaneGeometry";this.parameters={width:a,height:b,widthSegments:c,heightSegments:d};this.fromBufferGeometry(new kb(a,
16570 b,c,d));this.mergeVertices()}function kb(a,b,c,d){D.call(this);this.type="PlaneBufferGeometry";this.parameters={width:a,height:b,widthSegments:c,heightSegments:d};a=a||1;b=b||1;var e=a/2,f=b/2;c=Math.floor(c)||1;d=Math.floor(d)||1;var g=c+1,h=d+1,k=a/c,l=b/d,q=[],n=[],t=[],r=[];for(a=0;a<h;a++){var m=a*l-f;for(b=0;b<g;b++)n.push(b*k-e,-m,0),t.push(0,0,1),r.push(b/c),r.push(1-a/d)}for(a=0;a<d;a++)for(b=0;b<c;b++)e=b+g*(a+1),f=b+1+g*(a+1),h=b+1+g*a,q.push(b+g*a,e,h),q.push(e,f,h);this.setIndex(q);this.addAttribute("position",
16571 new y(n,3));this.addAttribute("normal",new y(t,3));this.addAttribute("uv",new y(r,2))}function va(a){Q.call(this);this.type="MeshBasicMaterial";this.color=new H(16777215);this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.envMap=this.alphaMap=this.specularMap=null;this.combine=0;this.reflectivity=1;this.refractionRatio=.98;this.wireframe=!1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.lights=this.morphTargets=this.skinning=
16572 !1;this.setValues(a)}function oa(a){Q.call(this);this.type="ShaderMaterial";this.defines={};this.uniforms={};this.vertexShader="void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";this.fragmentShader="void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";this.linewidth=1;this.wireframe=!1;this.wireframeLinewidth=1;this.morphNormals=this.morphTargets=this.skinning=this.clipping=this.lights=this.fog=!1;this.extensions={derivatives:!1,fragDepth:!1,
16573 drawBuffers:!1,shaderTextureLOD:!1};this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv2:[0,0]};this.index0AttributeName=void 0;void 0!==a&&(void 0!==a.attributes&&console.error("THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead."),this.setValues(a))}function lb(a,b){this.origin=void 0!==a?a:new p;this.direction=void 0!==b?b:new p}function Mb(a,b){this.start=void 0!==a?a:new p;this.end=void 0!==b?b:new p}function Qa(a,b,c){this.a=void 0!==a?a:new p;this.b=void 0!==
16574 b?b:new p;this.c=void 0!==c?c:new p}function pa(a,b){A.call(this);this.type="Mesh";this.geometry=void 0!==a?a:new D;this.material=void 0!==b?b:new va({color:16777215*Math.random()});this.drawMode=0;this.updateMorphTargets()}function Qf(a,b,c,d){function e(a,c){b.buffers.color.setClear(a.r,a.g,a.b,c,d)}var f=new H(0),g=0,h,k,l;return{getClearColor:function(){return f},setClearColor:function(a,b){f.set(a);g=void 0!==b?b:1;e(f,g)},getClearAlpha:function(){return g},setClearAlpha:function(a){g=a;e(f,
16575 g)},render:function(b,d,t,r){d=d.background;null===d?e(f,g):d&&d.isColor&&(e(d,1),r=!0);(a.autoClear||r)&&a.clear(a.autoClearColor,a.autoClearDepth,a.autoClearStencil);d&&d.isCubeTexture?(void 0===l&&(l=new pa(new jb(1,1,1),new oa({uniforms:mb.cube.uniforms,vertexShader:mb.cube.vertexShader,fragmentShader:mb.cube.fragmentShader,side:1,depthTest:!0,depthWrite:!1,fog:!1})),l.geometry.removeAttribute("normal"),l.geometry.removeAttribute("uv"),l.onBeforeRender=function(a,b,c){this.matrixWorld.copyPosition(c.matrixWorld)},
16576 c.update(l.geometry)),l.material.uniforms.tCube.value=d,b.push(l,l.geometry,l.material,0,null)):d&&d.isTexture&&(void 0===h&&(h=new Kb(-1,1,1,-1,0,1),k=new pa(new kb(2,2),new va({depthTest:!1,depthWrite:!1,fog:!1})),c.update(k.geometry)),k.material.map=d,a.renderBufferDirect(h,null,k.geometry,k.material,k,null))}}}function Rf(a,b){return a.renderOrder!==b.renderOrder?a.renderOrder-b.renderOrder:a.program&&b.program&&a.program!==b.program?a.program.id-b.program.id:a.material.id!==b.material.id?a.material.id-
16577 b.material.id:a.z!==b.z?a.z-b.z:a.id-b.id}function Sf(a,b){return a.renderOrder!==b.renderOrder?a.renderOrder-b.renderOrder:a.z!==b.z?b.z-a.z:a.id-b.id}function Tf(){var a=[],b=0,c=[],d=[];return{opaque:c,transparent:d,init:function(){b=0;c.length=0;d.length=0},push:function(e,f,g,h,k){var l=a[b];void 0===l?(l={id:e.id,object:e,geometry:f,material:g,program:g.program,renderOrder:e.renderOrder,z:h,group:k},a[b]=l):(l.id=e.id,l.object=e,l.geometry=f,l.material=g,l.program=g.program,l.renderOrder=e.renderOrder,
16578 l.z=h,l.group=k);(!0===g.transparent?d:c).push(l);b++},sort:function(){1<c.length&&c.sort(Rf);1<d.length&&d.sort(Sf)}}}function Uf(){var a={};return{get:function(b,c){b=b.id+","+c.id;c=a[b];void 0===c&&(c=new Tf,a[b]=c);return c},dispose:function(){a={}}}}function Vf(a,b){return Math.abs(b[1])-Math.abs(a[1])}function Wf(a){var b={},c=new Float32Array(8);return{update:function(d,e,f,g){var h=d.morphTargetInfluences,k=h.length;d=b[e.id];if(void 0===d){d=[];for(var l=0;l<k;l++)d[l]=[l,0];b[e.id]=d}var q=
16579 f.morphTargets&&e.morphAttributes.position;f=f.morphNormals&&e.morphAttributes.normal;for(l=0;l<k;l++){var n=d[l];0!==n[1]&&(q&&e.removeAttribute("morphTarget"+l),f&&e.removeAttribute("morphNormal"+l))}for(l=0;l<k;l++)n=d[l],n[0]=l,n[1]=h[l];d.sort(Vf);for(l=0;8>l;l++){if(n=d[l])if(h=n[0],n=n[1]){q&&e.addAttribute("morphTarget"+l,q[h]);f&&e.addAttribute("morphNormal"+l,f[h]);c[l]=n;continue}c[l]=0}g.getUniforms().setValue(a,"morphTargetInfluences",c)}}}function Xf(a,b,c){var d,e,f;this.setMode=function(a){d=
16580 a};this.setIndex=function(a){e=a.type;f=a.bytesPerElement};this.render=function(b,h){a.drawElements(d,h,e,b*f);c.calls++;c.vertices+=h;d===a.TRIANGLES?c.faces+=h/3:d===a.POINTS&&(c.points+=h)};this.renderInstances=function(g,h,k){var l=b.get("ANGLE_instanced_arrays");null===l?console.error("THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays."):(l.drawElementsInstancedANGLE(d,k,e,h*f,g.maxInstancedCount),c.calls++,c.vertices+=
16581 k*g.maxInstancedCount,d===a.TRIANGLES?c.faces+=g.maxInstancedCount*k/3:d===a.POINTS&&(c.points+=g.maxInstancedCount*k))}}function Yf(a,b,c){var d;this.setMode=function(a){d=a};this.render=function(b,f){a.drawArrays(d,b,f);c.calls++;c.vertices+=f;d===a.TRIANGLES?c.faces+=f/3:d===a.POINTS&&(c.points+=f)};this.renderInstances=function(e,f,g){var h=b.get("ANGLE_instanced_arrays");if(null===h)console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");
16582 else{var k=e.attributes.position;k.isInterleavedBufferAttribute?(g=k.data.count,h.drawArraysInstancedANGLE(d,0,g,e.maxInstancedCount)):h.drawArraysInstancedANGLE(d,f,g,e.maxInstancedCount);c.calls++;c.vertices+=g*e.maxInstancedCount;d===a.TRIANGLES?c.faces+=e.maxInstancedCount*g/3:d===a.POINTS&&(c.points+=e.maxInstancedCount*g)}}}function Zf(a,b,c){function d(a){a=a.target;var g=e[a.id];null!==g.index&&b.remove(g.index);for(var k in g.attributes)b.remove(g.attributes[k]);a.removeEventListener("dispose",
16583 d);delete e[a.id];if(k=f[a.id])b.remove(k),delete f[a.id];if(k=f[g.id])b.remove(k),delete f[g.id];c.geometries--}var e={},f={};return{get:function(a,b){var f=e[b.id];if(f)return f;b.addEventListener("dispose",d);b.isBufferGeometry?f=b:b.isGeometry&&(void 0===b._bufferGeometry&&(b._bufferGeometry=(new D).setFromObject(a)),f=b._bufferGeometry);e[b.id]=f;c.geometries++;return f},update:function(c){var d=c.index,e=c.attributes;null!==d&&b.update(d,a.ELEMENT_ARRAY_BUFFER);for(var f in e)b.update(e[f],
16584 a.ARRAY_BUFFER);c=c.morphAttributes;for(f in c)for(var d=c[f],e=0,g=d.length;e<g;e++)b.update(d[e],a.ARRAY_BUFFER)},getWireframeAttribute:function(c){var d=f[c.id];if(d)return d;d=[];var e=c.index;var g=c.attributes;if(null!==e){var q=e.array;for(var n=0,t=q.length;n<t;n+=3){var r=q[n+0];g=q[n+1];e=q[n+2];d.push(r,g,g,e,e,r)}}else for(q=g.position.array,n=0,t=q.length/3-1;n<t;n+=3)r=n+0,g=n+1,e=n+2,d.push(r,g,g,e,e,r);d=new (65535<Qd(d)?ib:hb)(d,1);b.update(d,a.ELEMENT_ARRAY_BUFFER);return f[c.id]=
16585 d}}}function $f(){var a={};return{get:function(b){if(void 0!==a[b.id])return a[b.id];switch(b.type){case "DirectionalLight":var c={direction:new p,color:new H,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new C};break;case "SpotLight":c={position:new p,direction:new p,color:new H,distance:0,coneCos:0,penumbraCos:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new C};break;case "PointLight":c={position:new p,color:new H,distance:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new C,
16586 shadowCameraNear:1,shadowCameraFar:1E3};break;case "HemisphereLight":c={direction:new p,skyColor:new H,groundColor:new H};break;case "RectAreaLight":c={color:new H,position:new p,halfWidth:new p,halfHeight:new p}}return a[b.id]=c}}}function ag(){var a=new $f,b={hash:"",ambient:[0,0,0],directional:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotShadowMap:[],spotShadowMatrix:[],rectArea:[],point:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[]},c=new p,d=new K,e=new K;return{setup:function(f,
16587 g,h){for(var k,l=0,q=0,n=0,t=0,r=0,m=0,v=0,w=0,p=h.matrixWorldInverse,z=0,I=f.length;z<I;z++){var B=f[z];k=B.color;var J=B.intensity,ta=B.distance,za=B.shadow&&B.shadow.map?B.shadow.map.texture:null;if(B.isAmbientLight)l+=k.r*J,q+=k.g*J,n+=k.b*J;else if(B.isDirectionalLight){h=a.get(B);h.color.copy(B.color).multiplyScalar(B.intensity);h.direction.setFromMatrixPosition(B.matrixWorld);c.setFromMatrixPosition(B.target.matrixWorld);h.direction.sub(c);h.direction.transformDirection(p);if(h.shadow=B.castShadow)k=
16588 B.shadow,h.shadowBias=k.bias,h.shadowRadius=k.radius,h.shadowMapSize=k.mapSize;b.directionalShadowMap[t]=za;b.directionalShadowMatrix[t]=B.shadow.matrix;b.directional[t]=h;t++}else if(B.isSpotLight){h=a.get(B);h.position.setFromMatrixPosition(B.matrixWorld);h.position.applyMatrix4(p);h.color.copy(k).multiplyScalar(J);h.distance=ta;h.direction.setFromMatrixPosition(B.matrixWorld);c.setFromMatrixPosition(B.target.matrixWorld);h.direction.sub(c);h.direction.transformDirection(p);h.coneCos=Math.cos(B.angle);
16589 h.penumbraCos=Math.cos(B.angle*(1-B.penumbra));h.decay=0===B.distance?0:B.decay;if(h.shadow=B.castShadow)k=B.shadow,h.shadowBias=k.bias,h.shadowRadius=k.radius,h.shadowMapSize=k.mapSize;b.spotShadowMap[m]=za;b.spotShadowMatrix[m]=B.shadow.matrix;b.spot[m]=h;m++}else if(B.isRectAreaLight)h=a.get(B),h.color.copy(k).multiplyScalar(J/(B.width*B.height)),h.position.setFromMatrixPosition(B.matrixWorld),h.position.applyMatrix4(p),e.identity(),d.copy(B.matrixWorld),d.premultiply(p),e.extractRotation(d),h.halfWidth.set(.5*
16590 B.width,0,0),h.halfHeight.set(0,.5*B.height,0),h.halfWidth.applyMatrix4(e),h.halfHeight.applyMatrix4(e),b.rectArea[v]=h,v++;else if(B.isPointLight){h=a.get(B);h.position.setFromMatrixPosition(B.matrixWorld);h.position.applyMatrix4(p);h.color.copy(B.color).multiplyScalar(B.intensity);h.distance=B.distance;h.decay=0===B.distance?0:B.decay;if(h.shadow=B.castShadow)k=B.shadow,h.shadowBias=k.bias,h.shadowRadius=k.radius,h.shadowMapSize=k.mapSize,h.shadowCameraNear=k.camera.near,h.shadowCameraFar=k.camera.far;
16591 b.pointShadowMap[r]=za;b.pointShadowMatrix[r]=B.shadow.matrix;b.point[r]=h;r++}else B.isHemisphereLight&&(h=a.get(B),h.direction.setFromMatrixPosition(B.matrixWorld),h.direction.transformDirection(p),h.direction.normalize(),h.skyColor.copy(B.color).multiplyScalar(J),h.groundColor.copy(B.groundColor).multiplyScalar(J),b.hemi[w]=h,w++)}b.ambient[0]=l;b.ambient[1]=q;b.ambient[2]=n;b.directional.length=t;b.spot.length=m;b.rectArea.length=v;b.point.length=r;b.hemi.length=w;b.hash=t+","+r+","+m+","+v+","+
16592 w+","+g.length},state:b}}function bg(a,b){var c={};return{update:function(d){var e=b.frame,f=d.geometry,g=a.get(d,f);c[g.id]!==e&&(f.isGeometry&&g.updateFromObject(d),a.update(g),c[g.id]=e);return g},clear:function(){c={}}}}function cg(a){a=a.split("\n");for(var b=0;b<a.length;b++)a[b]=b+1+": "+a[b];return a.join("\n")}function Ke(a,b,c){var d=a.createShader(b);a.shaderSource(d,c);a.compileShader(d);!1===a.getShaderParameter(d,a.COMPILE_STATUS)&&console.error("THREE.WebGLShader: Shader couldn't compile.");
16593 ""!==a.getShaderInfoLog(d)&&console.warn("THREE.WebGLShader: gl.getShaderInfoLog()",b===a.VERTEX_SHADER?"vertex":"fragment",a.getShaderInfoLog(d),cg(c));return d}function Le(a){switch(a){case 3E3:return["Linear","( value )"];case 3001:return["sRGB","( value )"];case 3002:return["RGBE","( value )"];case 3004:return["RGBM","( value, 7.0 )"];case 3005:return["RGBM","( value, 16.0 )"];case 3006:return["RGBD","( value, 256.0 )"];case 3007:return["Gamma","( value, float( GAMMA_FACTOR ) )"];default:throw Error("unsupported encoding: "+
16594 a);}}function Rd(a,b){b=Le(b);return"vec4 "+a+"( vec4 value ) { return "+b[0]+"ToLinear"+b[1]+"; }"}function dg(a,b){b=Le(b);return"vec4 "+a+"( vec4 value ) { return LinearTo"+b[0]+b[1]+"; }"}function eg(a,b){switch(b){case 1:b="Linear";break;case 2:b="Reinhard";break;case 3:b="Uncharted2";break;case 4:b="OptimizedCineon";break;default:throw Error("unsupported toneMapping: "+b);}return"vec3 "+a+"( vec3 color ) { return "+b+"ToneMapping( color ); }"}function fg(a,b,c){a=a||{};return[a.derivatives||
16595 b.envMapCubeUV||b.bumpMap||b.normalMap||b.flatShading?"#extension GL_OES_standard_derivatives : enable":"",(a.fragDepth||b.logarithmicDepthBuffer)&&c.get("EXT_frag_depth")?"#extension GL_EXT_frag_depth : enable":"",a.drawBuffers&&c.get("WEBGL_draw_buffers")?"#extension GL_EXT_draw_buffers : require":"",(a.shaderTextureLOD||b.envMap)&&c.get("EXT_shader_texture_lod")?"#extension GL_EXT_shader_texture_lod : enable":""].filter(Bc).join("\n")}function gg(a){var b=[],c;for(c in a){var d=a[c];!1!==d&&b.push("#define "+
16596 c+" "+d)}return b.join("\n")}function Bc(a){return""!==a}function Me(a,b){return a.replace(/NUM_DIR_LIGHTS/g,b.numDirLights).replace(/NUM_SPOT_LIGHTS/g,b.numSpotLights).replace(/NUM_RECT_AREA_LIGHTS/g,b.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,b.numPointLights).replace(/NUM_HEMI_LIGHTS/g,b.numHemiLights)}function Sd(a){return a.replace(/^[ \t]*#include +<([\w\d.]+)>/gm,function(a,c){a=W[c];if(void 0===a)throw Error("Can not resolve #include <"+c+">");return Sd(a)})}function Ne(a){return a.replace(/for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g,
16597 function(a,c,d,e){a="";for(c=parseInt(c);c<parseInt(d);c++)a+=e.replace(/\[ i \]/g,"[ "+c+" ]");return a})}function hg(a,b,c,d,e,f){var g=a.context,h=d.defines,k=e.vertexShader,l=e.fragmentShader,q="SHADOWMAP_TYPE_BASIC";1===f.shadowMapType?q="SHADOWMAP_TYPE_PCF":2===f.shadowMapType&&(q="SHADOWMAP_TYPE_PCF_SOFT");var n="ENVMAP_TYPE_CUBE",t="ENVMAP_MODE_REFLECTION",r="ENVMAP_BLENDING_MULTIPLY";if(f.envMap){switch(d.envMap.mapping){case 301:case 302:n="ENVMAP_TYPE_CUBE";break;case 306:case 307:n="ENVMAP_TYPE_CUBE_UV";
16598 break;case 303:case 304:n="ENVMAP_TYPE_EQUIREC";break;case 305:n="ENVMAP_TYPE_SPHERE"}switch(d.envMap.mapping){case 302:case 304:t="ENVMAP_MODE_REFRACTION"}switch(d.combine){case 0:r="ENVMAP_BLENDING_MULTIPLY";break;case 1:r="ENVMAP_BLENDING_MIX";break;case 2:r="ENVMAP_BLENDING_ADD"}}var m=0<a.gammaFactor?a.gammaFactor:1,v=fg(d.extensions,f,b),w=gg(h),p=g.createProgram();d.isRawShaderMaterial?(h=[w].filter(Bc).join("\n"),0<h.length&&(h+="\n"),b=[v,w].filter(Bc).join("\n"),0<b.length&&(b+="\n")):(h=
16599 ["precision "+f.precision+" float;","precision "+f.precision+" int;","#define SHADER_NAME "+e.name,w,f.supportsVertexTextures?"#define VERTEX_TEXTURES":"","#define GAMMA_FACTOR "+m,"#define MAX_BONES "+f.maxBones,f.useFog&&f.fog?"#define USE_FOG":"",f.useFog&&f.fogExp?"#define FOG_EXP2":"",f.map?"#define USE_MAP":"",f.envMap?"#define USE_ENVMAP":"",f.envMap?"#define "+t:"",f.lightMap?"#define USE_LIGHTMAP":"",f.aoMap?"#define USE_AOMAP":"",f.emissiveMap?"#define USE_EMISSIVEMAP":"",f.bumpMap?"#define USE_BUMPMAP":
16600 "",f.normalMap?"#define USE_NORMALMAP":"",f.displacementMap&&f.supportsVertexTextures?"#define USE_DISPLACEMENTMAP":"",f.specularMap?"#define USE_SPECULARMAP":"",f.roughnessMap?"#define USE_ROUGHNESSMAP":"",f.metalnessMap?"#define USE_METALNESSMAP":"",f.alphaMap?"#define USE_ALPHAMAP":"",f.vertexColors?"#define USE_COLOR":"",f.flatShading?"#define FLAT_SHADED":"",f.skinning?"#define USE_SKINNING":"",f.useVertexTexture?"#define BONE_TEXTURE":"",f.morphTargets?"#define USE_MORPHTARGETS":"",f.morphNormals&&
16601 !1===f.flatShading?"#define USE_MORPHNORMALS":"",f.doubleSided?"#define DOUBLE_SIDED":"",f.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+f.numClippingPlanes,f.shadowMapEnabled?"#define USE_SHADOWMAP":"",f.shadowMapEnabled?"#define "+q:"",f.sizeAttenuation?"#define USE_SIZEATTENUATION":"",f.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",f.logarithmicDepthBuffer&&b.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;",
16602 "uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_COLOR","\tattribute vec3 color;","#endif","#ifdef USE_MORPHTARGETS","\tattribute vec3 morphTarget0;","\tattribute vec3 morphTarget1;","\tattribute vec3 morphTarget2;","\tattribute vec3 morphTarget3;","\t#ifdef USE_MORPHNORMALS","\t\tattribute vec3 morphNormal0;","\t\tattribute vec3 morphNormal1;",
16603 "\t\tattribute vec3 morphNormal2;","\t\tattribute vec3 morphNormal3;","\t#else","\t\tattribute vec3 morphTarget4;","\t\tattribute vec3 morphTarget5;","\t\tattribute vec3 morphTarget6;","\t\tattribute vec3 morphTarget7;","\t#endif","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(Bc).join("\n"),b=[v,"precision "+f.precision+" float;","precision "+f.precision+" int;","#define SHADER_NAME "+e.name,w,f.alphaTest?"#define ALPHATEST "+f.alphaTest:
16604 "","#define GAMMA_FACTOR "+m,f.useFog&&f.fog?"#define USE_FOG":"",f.useFog&&f.fogExp?"#define FOG_EXP2":"",f.map?"#define USE_MAP":"",f.envMap?"#define USE_ENVMAP":"",f.envMap?"#define "+n:"",f.envMap?"#define "+t:"",f.envMap?"#define "+r:"",f.lightMap?"#define USE_LIGHTMAP":"",f.aoMap?"#define USE_AOMAP":"",f.emissiveMap?"#define USE_EMISSIVEMAP":"",f.bumpMap?"#define USE_BUMPMAP":"",f.normalMap?"#define USE_NORMALMAP":"",f.specularMap?"#define USE_SPECULARMAP":"",f.roughnessMap?"#define USE_ROUGHNESSMAP":
16605 "",f.metalnessMap?"#define USE_METALNESSMAP":"",f.alphaMap?"#define USE_ALPHAMAP":"",f.vertexColors?"#define USE_COLOR":"",f.gradientMap?"#define USE_GRADIENTMAP":"",f.flatShading?"#define FLAT_SHADED":"",f.doubleSided?"#define DOUBLE_SIDED":"",f.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+f.numClippingPlanes,"#define UNION_CLIPPING_PLANES "+(f.numClippingPlanes-f.numClipIntersection),f.shadowMapEnabled?"#define USE_SHADOWMAP":"",f.shadowMapEnabled?"#define "+q:"",f.premultipliedAlpha?
16606 "#define PREMULTIPLIED_ALPHA":"",f.physicallyCorrectLights?"#define PHYSICALLY_CORRECT_LIGHTS":"",f.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",f.logarithmicDepthBuffer&&b.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"",f.envMap&&b.get("EXT_shader_texture_lod")?"#define TEXTURE_LOD_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;",0!==f.toneMapping?"#define TONE_MAPPING":"",0!==f.toneMapping?W.tonemapping_pars_fragment:"",0!==f.toneMapping?eg("toneMapping",f.toneMapping):
16607 "",f.dithering?"#define DITHERING":"",f.outputEncoding||f.mapEncoding||f.envMapEncoding||f.emissiveMapEncoding?W.encodings_pars_fragment:"",f.mapEncoding?Rd("mapTexelToLinear",f.mapEncoding):"",f.envMapEncoding?Rd("envMapTexelToLinear",f.envMapEncoding):"",f.emissiveMapEncoding?Rd("emissiveMapTexelToLinear",f.emissiveMapEncoding):"",f.outputEncoding?dg("linearToOutputTexel",f.outputEncoding):"",f.depthPacking?"#define DEPTH_PACKING "+d.depthPacking:"","\n"].filter(Bc).join("\n"));k=Sd(k);k=Me(k,f);
16608 l=Sd(l);l=Me(l,f);d.isShaderMaterial||(k=Ne(k),l=Ne(l));l=b+l;k=Ke(g,g.VERTEX_SHADER,h+k);l=Ke(g,g.FRAGMENT_SHADER,l);g.attachShader(p,k);g.attachShader(p,l);void 0!==d.index0AttributeName?g.bindAttribLocation(p,0,d.index0AttributeName):!0===f.morphTargets&&g.bindAttribLocation(p,0,"position");g.linkProgram(p);f=g.getProgramInfoLog(p);e=g.getShaderInfoLog(k);q=g.getShaderInfoLog(l);t=n=!0;if(!1===g.getProgramParameter(p,g.LINK_STATUS))n=!1,console.error("THREE.WebGLProgram: shader error: ",g.getError(),
16609 "gl.VALIDATE_STATUS",g.getProgramParameter(p,g.VALIDATE_STATUS),"gl.getProgramInfoLog",f,e,q);else if(""!==f)console.warn("THREE.WebGLProgram: gl.getProgramInfoLog()",f);else if(""===e||""===q)t=!1;t&&(this.diagnostics={runnable:n,material:d,programLog:f,vertexShader:{log:e,prefix:h},fragmentShader:{log:q,prefix:b}});g.deleteShader(k);g.deleteShader(l);var z;this.getUniforms=function(){void 0===z&&(z=new gb(g,p,a));return z};var I;this.getAttributes=function(){if(void 0===I){for(var a={},b=g.getProgramParameter(p,
16610 g.ACTIVE_ATTRIBUTES),c=0;c<b;c++){var d=g.getActiveAttrib(p,c).name;a[d]=g.getAttribLocation(p,d)}I=a}return I};this.destroy=function(){g.deleteProgram(p);this.program=void 0};Object.defineProperties(this,{uniforms:{get:function(){console.warn("THREE.WebGLProgram: .uniforms is now .getUniforms().");return this.getUniforms()}},attributes:{get:function(){console.warn("THREE.WebGLProgram: .attributes is now .getAttributes().");return this.getAttributes()}}});this.id=ig++;this.code=c;this.usedTimes=1;
16611 this.program=p;this.vertexShader=k;this.fragmentShader=l;return this}function jg(a,b,c){function d(a,b){if(a)a.isTexture?c=a.encoding:a.isWebGLRenderTarget&&(console.warn("THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead."),c=a.texture.encoding);else var c=3E3;3E3===c&&b&&(c=3007);return c}var e=[],f={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",
16612 MeshPhongMaterial:"phong",MeshToonMaterial:"phong",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow"},g="precision supportsVertexTextures map mapEncoding envMap envMapMode envMapEncoding lightMap aoMap emissiveMap emissiveMapEncoding bumpMap normalMap displacementMap specularMap roughnessMap metalnessMap gradientMap alphaMap combine vertexColors fog useFog fogExp flatShading sizeAttenuation logarithmicDepthBuffer skinning maxBones useVertexTexture morphTargets morphNormals maxMorphTargets maxMorphNormals premultipliedAlpha numDirLights numPointLights numSpotLights numHemiLights numRectAreaLights shadowMapEnabled shadowMapType toneMapping physicallyCorrectLights alphaTest doubleSided flipSided numClippingPlanes numClipIntersection depthPacking dithering".split(" ");
16613 this.getParameters=function(b,e,g,q,n,t,r){var h=f[b.type];if(r.isSkinnedMesh){var l=r.skeleton.bones;if(c.floatVertexTextures)l=1024;else{var k=Math.min(Math.floor((c.maxVertexUniforms-20)/4),l.length);k<l.length?(console.warn("THREE.WebGLRenderer: Skeleton has "+l.length+" bones. This GPU supports "+k+"."),l=0):l=k}}else l=0;k=c.precision;null!==b.precision&&(k=c.getMaxPrecision(b.precision),k!==b.precision&&console.warn("THREE.WebGLProgram.getParameters:",b.precision,"not supported, using",k,"instead."));
16614 var m=a.getRenderTarget();return{shaderID:h,precision:k,supportsVertexTextures:c.vertexTextures,outputEncoding:d(m?m.texture:null,a.gammaOutput),map:!!b.map,mapEncoding:d(b.map,a.gammaInput),envMap:!!b.envMap,envMapMode:b.envMap&&b.envMap.mapping,envMapEncoding:d(b.envMap,a.gammaInput),envMapCubeUV:!!b.envMap&&(306===b.envMap.mapping||307===b.envMap.mapping),lightMap:!!b.lightMap,aoMap:!!b.aoMap,emissiveMap:!!b.emissiveMap,emissiveMapEncoding:d(b.emissiveMap,a.gammaInput),bumpMap:!!b.bumpMap,normalMap:!!b.normalMap,
16615 displacementMap:!!b.displacementMap,roughnessMap:!!b.roughnessMap,metalnessMap:!!b.metalnessMap,specularMap:!!b.specularMap,alphaMap:!!b.alphaMap,gradientMap:!!b.gradientMap,combine:b.combine,vertexColors:b.vertexColors,fog:!!q,useFog:b.fog,fogExp:q&&q.isFogExp2,flatShading:b.flatShading,sizeAttenuation:b.sizeAttenuation,logarithmicDepthBuffer:c.logarithmicDepthBuffer,skinning:b.skinning&&0<l,maxBones:l,useVertexTexture:c.floatVertexTextures,morphTargets:b.morphTargets,morphNormals:b.morphNormals,
16616 maxMorphTargets:a.maxMorphTargets,maxMorphNormals:a.maxMorphNormals,numDirLights:e.directional.length,numPointLights:e.point.length,numSpotLights:e.spot.length,numRectAreaLights:e.rectArea.length,numHemiLights:e.hemi.length,numClippingPlanes:n,numClipIntersection:t,dithering:b.dithering,shadowMapEnabled:a.shadowMap.enabled&&r.receiveShadow&&0<g.length,shadowMapType:a.shadowMap.type,toneMapping:a.toneMapping,physicallyCorrectLights:a.physicallyCorrectLights,premultipliedAlpha:b.premultipliedAlpha,
16617 alphaTest:b.alphaTest,doubleSided:2===b.side,flipSided:1===b.side,depthPacking:void 0!==b.depthPacking?b.depthPacking:!1}};this.getProgramCode=function(b,c){var d=[];c.shaderID?d.push(c.shaderID):(d.push(b.fragmentShader),d.push(b.vertexShader));if(void 0!==b.defines)for(var e in b.defines)d.push(e),d.push(b.defines[e]);for(e=0;e<g.length;e++)d.push(c[g[e]]);d.push(b.onBeforeCompile.toString());d.push(a.gammaOutput);return d.join()};this.acquireProgram=function(c,d,f,g){for(var h,l=0,k=e.length;l<
16618 k;l++){var q=e[l];if(q.code===g){h=q;++h.usedTimes;break}}void 0===h&&(h=new hg(a,b,g,c,d,f),e.push(h));return h};this.releaseProgram=function(a){if(0===--a.usedTimes){var b=e.indexOf(a);e[b]=e[e.length-1];e.pop();a.destroy()}};this.programs=e}function kg(a,b,c,d,e,f,g){function h(a,b){if(a.width>b||a.height>b){b/=Math.max(a.width,a.height);var c=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");c.width=Math.floor(a.width*b);c.height=Math.floor(a.height*b);c.getContext("2d").drawImage(a,
16619 0,0,a.width,a.height,0,0,c.width,c.height);console.warn("THREE.WebGLRenderer: image is too big ("+a.width+"x"+a.height+"). Resized to "+c.width+"x"+c.height,a);return c}return a}function k(a){return R.isPowerOfTwo(a.width)&&R.isPowerOfTwo(a.height)}function l(a,b){return a.generateMipmaps&&b&&1003!==a.minFilter&&1006!==a.minFilter}function q(b){return 1003===b||1004===b||1005===b?a.NEAREST:a.LINEAR}function n(b){b=b.target;b.removeEventListener("dispose",n);a:{var c=d.get(b);if(b.image&&c.__image__webglTextureCube)a.deleteTexture(c.__image__webglTextureCube);
16620 else{if(void 0===c.__webglInit)break a;a.deleteTexture(c.__webglTexture)}d.remove(b)}g.textures--}function t(b){b=b.target;b.removeEventListener("dispose",t);var c=d.get(b),e=d.get(b.texture);if(b){void 0!==e.__webglTexture&&a.deleteTexture(e.__webglTexture);b.depthTexture&&b.depthTexture.dispose();if(b.isWebGLRenderTargetCube)for(e=0;6>e;e++)a.deleteFramebuffer(c.__webglFramebuffer[e]),c.__webglDepthbuffer&&a.deleteRenderbuffer(c.__webglDepthbuffer[e]);else a.deleteFramebuffer(c.__webglFramebuffer),
16621 c.__webglDepthbuffer&&a.deleteRenderbuffer(c.__webglDepthbuffer);d.remove(b.texture);d.remove(b)}g.textures--}function r(b,q){var t=d.get(b);if(0<b.version&&t.__version!==b.version){var r=b.image;if(void 0===r)console.warn("THREE.WebGLRenderer: Texture marked for update but image is undefined",b);else if(!1===r.complete)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete",b);else{void 0===t.__webglInit&&(t.__webglInit=!0,b.addEventListener("dispose",n),t.__webglTexture=
16622 a.createTexture(),g.textures++);c.activeTexture(a.TEXTURE0+q);c.bindTexture(a.TEXTURE_2D,t.__webglTexture);a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,b.flipY);a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,b.premultiplyAlpha);a.pixelStorei(a.UNPACK_ALIGNMENT,b.unpackAlignment);var u=h(b.image,e.maxTextureSize);(1001!==b.wrapS||1001!==b.wrapT||1003!==b.minFilter&&1006!==b.minFilter)&&!1===k(u)&&(q=u,q instanceof HTMLImageElement||q instanceof HTMLCanvasElement||q instanceof ImageBitmap?(r=document.createElementNS("http://www.w3.org/1999/xhtml",
16623 "canvas"),r.width=R.floorPowerOfTwo(q.width),r.height=R.floorPowerOfTwo(q.height),r.getContext("2d").drawImage(q,0,0,r.width,r.height),console.warn("THREE.WebGLRenderer: image is not power of two ("+q.width+"x"+q.height+"). Resized to "+r.width+"x"+r.height,q),u=r):u=q);q=k(u);var r=f.convert(b.format),z=f.convert(b.type);m(a.TEXTURE_2D,b,q);var p=b.mipmaps;if(b.isDepthTexture){p=a.DEPTH_COMPONENT;if(1015===b.type){if(!x)throw Error("Float Depth Texture only supported in WebGL2.0");p=a.DEPTH_COMPONENT32F}else x&&
16624 (p=a.DEPTH_COMPONENT16);1026===b.format&&p===a.DEPTH_COMPONENT&&1012!==b.type&&1014!==b.type&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),b.type=1012,z=f.convert(b.type));1027===b.format&&(p=a.DEPTH_STENCIL,1020!==b.type&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),b.type=1020,z=f.convert(b.type)));c.texImage2D(a.TEXTURE_2D,0,p,u.width,u.height,0,r,z,null)}else if(b.isDataTexture)if(0<
16625 p.length&&q){for(var v=0,w=p.length;v<w;v++)u=p[v],c.texImage2D(a.TEXTURE_2D,v,r,u.width,u.height,0,r,z,u.data);b.generateMipmaps=!1}else c.texImage2D(a.TEXTURE_2D,0,r,u.width,u.height,0,r,z,u.data);else if(b.isCompressedTexture)for(v=0,w=p.length;v<w;v++)u=p[v],1023!==b.format&&1022!==b.format?-1<c.getCompressedTextureFormats().indexOf(r)?c.compressedTexImage2D(a.TEXTURE_2D,v,r,u.width,u.height,0,u.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):
16626 c.texImage2D(a.TEXTURE_2D,v,r,u.width,u.height,0,r,z,u.data);else if(0<p.length&&q){v=0;for(w=p.length;v<w;v++)u=p[v],c.texImage2D(a.TEXTURE_2D,v,r,r,z,u);b.generateMipmaps=!1}else c.texImage2D(a.TEXTURE_2D,0,r,r,z,u);l(b,q)&&a.generateMipmap(a.TEXTURE_2D);t.__version=b.version;if(b.onUpdate)b.onUpdate(b);return}}c.activeTexture(a.TEXTURE0+q);c.bindTexture(a.TEXTURE_2D,t.__webglTexture)}function m(c,g,h){h?(a.texParameteri(c,a.TEXTURE_WRAP_S,f.convert(g.wrapS)),a.texParameteri(c,a.TEXTURE_WRAP_T,
16627 f.convert(g.wrapT)),a.texParameteri(c,a.TEXTURE_MAG_FILTER,f.convert(g.magFilter)),a.texParameteri(c,a.TEXTURE_MIN_FILTER,f.convert(g.minFilter))):(a.texParameteri(c,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(c,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),1001===g.wrapS&&1001===g.wrapT||console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.",g),a.texParameteri(c,a.TEXTURE_MAG_FILTER,q(g.magFilter)),a.texParameteri(c,
16628 a.TEXTURE_MIN_FILTER,q(g.minFilter)),1003!==g.minFilter&&1006!==g.minFilter&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.",g));!(h=b.get("EXT_texture_filter_anisotropic"))||1015===g.type&&null===b.get("OES_texture_float_linear")||1016===g.type&&null===b.get("OES_texture_half_float_linear")||!(1<g.anisotropy||d.get(g).__currentAnisotropy)||(a.texParameterf(c,h.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(g.anisotropy,
16629 e.getMaxAnisotropy())),d.get(g).__currentAnisotropy=g.anisotropy)}function p(b,e,g,h){var l=f.convert(e.texture.format),k=f.convert(e.texture.type);c.texImage2D(h,0,l,e.width,e.height,0,l,k,null);a.bindFramebuffer(a.FRAMEBUFFER,b);a.framebufferTexture2D(a.FRAMEBUFFER,g,h,d.get(e.texture).__webglTexture,0);a.bindFramebuffer(a.FRAMEBUFFER,null)}function w(b,c){a.bindRenderbuffer(a.RENDERBUFFER,b);c.depthBuffer&&!c.stencilBuffer?(a.renderbufferStorage(a.RENDERBUFFER,a.DEPTH_COMPONENT16,c.width,c.height),
16630 a.framebufferRenderbuffer(a.FRAMEBUFFER,a.DEPTH_ATTACHMENT,a.RENDERBUFFER,b)):c.depthBuffer&&c.stencilBuffer?(a.renderbufferStorage(a.RENDERBUFFER,a.DEPTH_STENCIL,c.width,c.height),a.framebufferRenderbuffer(a.FRAMEBUFFER,a.DEPTH_STENCIL_ATTACHMENT,a.RENDERBUFFER,b)):a.renderbufferStorage(a.RENDERBUFFER,a.RGBA4,c.width,c.height);a.bindRenderbuffer(a.RENDERBUFFER,null)}var x="undefined"!==typeof WebGL2RenderingContext&&a instanceof window.WebGL2RenderingContext;this.setTexture2D=r;this.setTextureCube=
16631 function(b,q){var t=d.get(b);if(6===b.image.length)if(0<b.version&&t.__version!==b.version){t.__image__webglTextureCube||(b.addEventListener("dispose",n),t.__image__webglTextureCube=a.createTexture(),g.textures++);c.activeTexture(a.TEXTURE0+q);c.bindTexture(a.TEXTURE_CUBE_MAP,t.__image__webglTextureCube);a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,b.flipY);q=b&&b.isCompressedTexture;for(var r=b.image[0]&&b.image[0].isDataTexture,u=[],p=0;6>p;p++)u[p]=q||r?r?b.image[p].image:b.image[p]:h(b.image[p],e.maxCubemapSize);
16632 var v=k(u[0]),w=f.convert(b.format),z=f.convert(b.type);m(a.TEXTURE_CUBE_MAP,b,v);for(p=0;6>p;p++)if(q)for(var x,I=u[p].mipmaps,y=0,C=I.length;y<C;y++)x=I[y],1023!==b.format&&1022!==b.format?-1<c.getCompressedTextureFormats().indexOf(w)?c.compressedTexImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+p,y,w,x.width,x.height,0,x.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+p,y,w,x.width,x.height,
16633 0,w,z,x.data);else r?c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+p,0,w,u[p].width,u[p].height,0,w,z,u[p].data):c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+p,0,w,w,z,u[p]);l(b,v)&&a.generateMipmap(a.TEXTURE_CUBE_MAP);t.__version=b.version;if(b.onUpdate)b.onUpdate(b)}else c.activeTexture(a.TEXTURE0+q),c.bindTexture(a.TEXTURE_CUBE_MAP,t.__image__webglTextureCube)};this.setTextureCubeDynamic=function(b,e){c.activeTexture(a.TEXTURE0+e);c.bindTexture(a.TEXTURE_CUBE_MAP,d.get(b).__webglTexture)};this.setupRenderTarget=
16634 function(b){var e=d.get(b),f=d.get(b.texture);b.addEventListener("dispose",t);f.__webglTexture=a.createTexture();g.textures++;var h=!0===b.isWebGLRenderTargetCube,n=k(b);if(h){e.__webglFramebuffer=[];for(var q=0;6>q;q++)e.__webglFramebuffer[q]=a.createFramebuffer()}else e.__webglFramebuffer=a.createFramebuffer();if(h){c.bindTexture(a.TEXTURE_CUBE_MAP,f.__webglTexture);m(a.TEXTURE_CUBE_MAP,b.texture,n);for(q=0;6>q;q++)p(e.__webglFramebuffer[q],b,a.COLOR_ATTACHMENT0,a.TEXTURE_CUBE_MAP_POSITIVE_X+q);
16635 l(b.texture,n)&&a.generateMipmap(a.TEXTURE_CUBE_MAP);c.bindTexture(a.TEXTURE_CUBE_MAP,null)}else c.bindTexture(a.TEXTURE_2D,f.__webglTexture),m(a.TEXTURE_2D,b.texture,n),p(e.__webglFramebuffer,b,a.COLOR_ATTACHMENT0,a.TEXTURE_2D),l(b.texture,n)&&a.generateMipmap(a.TEXTURE_2D),c.bindTexture(a.TEXTURE_2D,null);if(b.depthBuffer){e=d.get(b);f=!0===b.isWebGLRenderTargetCube;if(b.depthTexture){if(f)throw Error("target.depthTexture not supported in Cube render targets");if(b&&b.isWebGLRenderTargetCube)throw Error("Depth Texture with cube render targets is not supported");
16636 a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer);if(!b.depthTexture||!b.depthTexture.isDepthTexture)throw Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");d.get(b.depthTexture).__webglTexture&&b.depthTexture.image.width===b.width&&b.depthTexture.image.height===b.height||(b.depthTexture.image.width=b.width,b.depthTexture.image.height=b.height,b.depthTexture.needsUpdate=!0);r(b.depthTexture,0);e=d.get(b.depthTexture).__webglTexture;if(1026===b.depthTexture.format)a.framebufferTexture2D(a.FRAMEBUFFER,
16637 a.DEPTH_ATTACHMENT,a.TEXTURE_2D,e,0);else if(1027===b.depthTexture.format)a.framebufferTexture2D(a.FRAMEBUFFER,a.DEPTH_STENCIL_ATTACHMENT,a.TEXTURE_2D,e,0);else throw Error("Unknown depthTexture format");}else if(f)for(e.__webglDepthbuffer=[],f=0;6>f;f++)a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer[f]),e.__webglDepthbuffer[f]=a.createRenderbuffer(),w(e.__webglDepthbuffer[f],b);else a.bindFramebuffer(a.FRAMEBUFFER,e.__webglFramebuffer),e.__webglDepthbuffer=a.createRenderbuffer(),w(e.__webglDepthbuffer,
16638 b);a.bindFramebuffer(a.FRAMEBUFFER,null)}};this.updateRenderTargetMipmap=function(b){var e=b.texture,f=k(b);l(e,f)&&(b=b.isWebGLRenderTargetCube?a.TEXTURE_CUBE_MAP:a.TEXTURE_2D,e=d.get(e).__webglTexture,c.bindTexture(b,e),a.generateMipmap(b),c.bindTexture(b,null))}}function lg(){var a={};return{get:function(b){b=b.uuid;var c=a[b];void 0===c&&(c={},a[b]=c);return c},remove:function(b){delete a[b.uuid]},clear:function(){a={}}}}function mg(a,b,c){function d(b,c,d){var e=new Uint8Array(4),f=a.createTexture();
16639 a.bindTexture(b,f);a.texParameteri(b,a.TEXTURE_MIN_FILTER,a.NEAREST);a.texParameteri(b,a.TEXTURE_MAG_FILTER,a.NEAREST);for(b=0;b<d;b++)a.texImage2D(c+b,0,a.RGBA,1,1,0,a.RGBA,a.UNSIGNED_BYTE,e);return f}function e(b){!0!==z[b]&&(a.enable(b),z[b]=!0)}function f(b){!1!==z[b]&&(a.disable(b),z[b]=!1)}function g(b,d,g,h,l,k,n,q){0!==b?e(a.BLEND):f(a.BLEND);if(5!==b){if(b!==J||q!==L)switch(b){case 2:q?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ONE,a.ONE,a.ONE,a.ONE)):(a.blendEquation(a.FUNC_ADD),
16640 a.blendFunc(a.SRC_ALPHA,a.ONE));break;case 3:q?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ZERO,a.ZERO,a.ONE_MINUS_SRC_COLOR,a.ONE_MINUS_SRC_ALPHA)):(a.blendEquation(a.FUNC_ADD),a.blendFunc(a.ZERO,a.ONE_MINUS_SRC_COLOR));break;case 4:q?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ZERO,a.SRC_COLOR,a.ZERO,a.SRC_ALPHA)):(a.blendEquation(a.FUNC_ADD),a.blendFunc(a.ZERO,a.SRC_COLOR));break;default:q?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ONE,
16641 a.ONE_MINUS_SRC_ALPHA,a.ONE,a.ONE_MINUS_SRC_ALPHA)):(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.SRC_ALPHA,a.ONE_MINUS_SRC_ALPHA,a.ONE,a.ONE_MINUS_SRC_ALPHA))}E=A=ha=C=y=ta=null}else{l=l||d;k=k||g;n=n||h;if(d!==ta||l!==ha)a.blendEquationSeparate(c.convert(d),c.convert(l)),ta=d,ha=l;if(g!==y||h!==C||k!==A||n!==E)a.blendFuncSeparate(c.convert(g),c.convert(h),c.convert(k),c.convert(n)),y=g,C=h,A=k,E=n}J=b;L=q}function h(b){D!==b&&(b?a.frontFace(a.CW):a.frontFace(a.CCW),D=b)}
16642 function k(b){0!==b?(e(a.CULL_FACE),b!==H&&(1===b?a.cullFace(a.BACK):2===b?a.cullFace(a.FRONT):a.cullFace(a.FRONT_AND_BACK))):f(a.CULL_FACE);H=b}function l(b,c,d){if(b){if(e(a.POLYGON_OFFSET_FILL),V!==c||K!==d)a.polygonOffset(c,d),V=c,K=d}else f(a.POLYGON_OFFSET_FILL)}function q(b){void 0===b&&(b=a.TEXTURE0+N-1);R!==b&&(a.activeTexture(b),R=b)}var n=new function(){var b=!1,c=new da,d=null,e=new da(0,0,0,0);return{setMask:function(c){d===c||b||(a.colorMask(c,c,c,c),d=c)},setLocked:function(a){b=a},
16643 setClear:function(b,d,f,g,h){!0===h&&(b*=g,d*=g,f*=g);c.set(b,d,f,g);!1===e.equals(c)&&(a.clearColor(b,d,f,g),e.copy(c))},reset:function(){b=!1;d=null;e.set(-1,0,0,0)}}},t=new function(){var b=!1,c=null,d=null,g=null;return{setTest:function(b){b?e(a.DEPTH_TEST):f(a.DEPTH_TEST)},setMask:function(d){c===d||b||(a.depthMask(d),c=d)},setFunc:function(b){if(d!==b){if(b)switch(b){case 0:a.depthFunc(a.NEVER);break;case 1:a.depthFunc(a.ALWAYS);break;case 2:a.depthFunc(a.LESS);break;case 3:a.depthFunc(a.LEQUAL);
16644 break;case 4:a.depthFunc(a.EQUAL);break;case 5:a.depthFunc(a.GEQUAL);break;case 6:a.depthFunc(a.GREATER);break;case 7:a.depthFunc(a.NOTEQUAL);break;default:a.depthFunc(a.LEQUAL)}else a.depthFunc(a.LEQUAL);d=b}},setLocked:function(a){b=a},setClear:function(b){g!==b&&(a.clearDepth(b),g=b)},reset:function(){b=!1;g=d=c=null}}},r=new function(){var b=!1,c=null,d=null,g=null,h=null,l=null,k=null,n=null,q=null;return{setTest:function(b){b?e(a.STENCIL_TEST):f(a.STENCIL_TEST)},setMask:function(d){c===d||b||
16645 (a.stencilMask(d),c=d)},setFunc:function(b,c,e){if(d!==b||g!==c||h!==e)a.stencilFunc(b,c,e),d=b,g=c,h=e},setOp:function(b,c,d){if(l!==b||k!==c||n!==d)a.stencilOp(b,c,d),l=b,k=c,n=d},setLocked:function(a){b=a},setClear:function(b){q!==b&&(a.clearStencil(b),q=b)},reset:function(){b=!1;q=n=k=l=h=g=d=c=null}}},m=a.getParameter(a.MAX_VERTEX_ATTRIBS),p=new Uint8Array(m),w=new Uint8Array(m),x=new Uint8Array(m),z={},I=null,B=null,J=null,ta=null,y=null,C=null,ha=null,A=null,E=null,L=!1,D=null,H=null,M=null,
16646 V=null,K=null,N=a.getParameter(a.MAX_COMBINED_TEXTURE_IMAGE_UNITS),m=parseFloat(/^WebGL\ ([0-9])/.exec(a.getParameter(a.VERSION))[1]),aa=1<=parseFloat(m),R=null,P={},Q=new da,G=new da,X={};X[a.TEXTURE_2D]=d(a.TEXTURE_2D,a.TEXTURE_2D,1);X[a.TEXTURE_CUBE_MAP]=d(a.TEXTURE_CUBE_MAP,a.TEXTURE_CUBE_MAP_POSITIVE_X,6);n.setClear(0,0,0,1);t.setClear(1);r.setClear(0);e(a.DEPTH_TEST);t.setFunc(3);h(!1);k(1);e(a.CULL_FACE);e(a.BLEND);g(1);return{buffers:{color:n,depth:t,stencil:r},initAttributes:function(){for(var a=
16647 0,b=p.length;a<b;a++)p[a]=0},enableAttribute:function(c){p[c]=1;0===w[c]&&(a.enableVertexAttribArray(c),w[c]=1);0!==x[c]&&(b.get("ANGLE_instanced_arrays").vertexAttribDivisorANGLE(c,0),x[c]=0)},enableAttributeAndDivisor:function(c,d){p[c]=1;0===w[c]&&(a.enableVertexAttribArray(c),w[c]=1);x[c]!==d&&(b.get("ANGLE_instanced_arrays").vertexAttribDivisorANGLE(c,d),x[c]=d)},disableUnusedAttributes:function(){for(var b=0,c=w.length;b!==c;++b)w[b]!==p[b]&&(a.disableVertexAttribArray(b),w[b]=0)},enable:e,
16648 disable:f,getCompressedTextureFormats:function(){if(null===I&&(I=[],b.get("WEBGL_compressed_texture_pvrtc")||b.get("WEBGL_compressed_texture_s3tc")||b.get("WEBGL_compressed_texture_etc1")))for(var c=a.getParameter(a.COMPRESSED_TEXTURE_FORMATS),d=0;d<c.length;d++)I.push(c[d]);return I},useProgram:function(b){return B!==b?(a.useProgram(b),B=b,!0):!1},setBlending:g,setMaterial:function(b){2===b.side?f(a.CULL_FACE):e(a.CULL_FACE);h(1===b.side);!0===b.transparent?g(b.blending,b.blendEquation,b.blendSrc,
16649 b.blendDst,b.blendEquationAlpha,b.blendSrcAlpha,b.blendDstAlpha,b.premultipliedAlpha):g(0);t.setFunc(b.depthFunc);t.setTest(b.depthTest);t.setMask(b.depthWrite);n.setMask(b.colorWrite);l(b.polygonOffset,b.polygonOffsetFactor,b.polygonOffsetUnits)},setFlipSided:h,setCullFace:k,setLineWidth:function(b){b!==M&&(aa&&a.lineWidth(b),M=b)},setPolygonOffset:l,setScissorTest:function(b){b?e(a.SCISSOR_TEST):f(a.SCISSOR_TEST)},activeTexture:q,bindTexture:function(b,c){null===R&&q();var d=P[R];void 0===d&&(d=
16650 {type:void 0,texture:void 0},P[R]=d);if(d.type!==b||d.texture!==c)a.bindTexture(b,c||X[b]),d.type=b,d.texture=c},compressedTexImage2D:function(){try{a.compressedTexImage2D.apply(a,arguments)}catch(fa){console.error("THREE.WebGLState:",fa)}},texImage2D:function(){try{a.texImage2D.apply(a,arguments)}catch(fa){console.error("THREE.WebGLState:",fa)}},scissor:function(b){!1===Q.equals(b)&&(a.scissor(b.x,b.y,b.z,b.w),Q.copy(b))},viewport:function(b){!1===G.equals(b)&&(a.viewport(b.x,b.y,b.z,b.w),G.copy(b))},
16651 reset:function(){for(var b=0;b<w.length;b++)1===w[b]&&(a.disableVertexAttribArray(b),w[b]=0);z={};R=I=null;P={};H=D=J=B=null;n.reset();t.reset();r.reset()}}}function ng(a,b,c){function d(b){if("highp"===b){if(0<a.getShaderPrecisionFormat(a.VERTEX_SHADER,a.HIGH_FLOAT).precision&&0<a.getShaderPrecisionFormat(a.FRAGMENT_SHADER,a.HIGH_FLOAT).precision)return"highp";b="mediump"}return"mediump"===b&&0<a.getShaderPrecisionFormat(a.VERTEX_SHADER,a.MEDIUM_FLOAT).precision&&0<a.getShaderPrecisionFormat(a.FRAGMENT_SHADER,
16652 a.MEDIUM_FLOAT).precision?"mediump":"lowp"}var e,f=void 0!==c.precision?c.precision:"highp",g=d(f);g!==f&&(console.warn("THREE.WebGLRenderer:",f,"not supported, using",g,"instead."),f=g);c=!0===c.logarithmicDepthBuffer;var g=a.getParameter(a.MAX_TEXTURE_IMAGE_UNITS),h=a.getParameter(a.MAX_VERTEX_TEXTURE_IMAGE_UNITS),k=a.getParameter(a.MAX_TEXTURE_SIZE),l=a.getParameter(a.MAX_CUBE_MAP_TEXTURE_SIZE),q=a.getParameter(a.MAX_VERTEX_ATTRIBS),n=a.getParameter(a.MAX_VERTEX_UNIFORM_VECTORS),t=a.getParameter(a.MAX_VARYING_VECTORS),
16653 r=a.getParameter(a.MAX_FRAGMENT_UNIFORM_VECTORS),m=0<h,p=!!b.get("OES_texture_float");return{getMaxAnisotropy:function(){if(void 0!==e)return e;var c=b.get("EXT_texture_filter_anisotropic");return e=null!==c?a.getParameter(c.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0},getMaxPrecision:d,precision:f,logarithmicDepthBuffer:c,maxTextures:g,maxVertexTextures:h,maxTextureSize:k,maxCubemapSize:l,maxAttributes:q,maxVertexUniforms:n,maxVaryings:t,maxFragmentUniforms:r,vertexTextures:m,floatFragmentTextures:p,floatVertexTextures:m&&
16654 p}}function U(a,b,c,d){La.call(this);this.type="PerspectiveCamera";this.fov=void 0!==a?a:50;this.zoom=1;this.near=void 0!==c?c:.1;this.far=void 0!==d?d:2E3;this.focus=10;this.aspect=void 0!==b?b:1;this.view=null;this.filmGauge=35;this.filmOffset=0;this.updateProjectionMatrix()}function nd(a){U.call(this);this.cameras=a||[]}function og(a){function b(){if(null!==d&&d.isPresenting){var b=d.getEyeParameters("left"),e=b.renderWidth,b=b.renderHeight;t=a.getPixelRatio();n=a.getSize();a.setDrawingBufferSize(2*
16655 e,b,1)}else c.enabled&&a.setDrawingBufferSize(n.width,n.height,t)}var c=this,d=null,e=null;"undefined"!==typeof window&&"VRFrameData"in window&&(e=new window.VRFrameData);var f=new K,g=new K,h=new K,k=new U;k.bounds=new da(0,0,.5,1);k.layers.enable(1);var l=new U;l.bounds=new da(.5,0,.5,1);l.layers.enable(2);var q=new nd([k,l]);q.layers.enable(1);q.layers.enable(2);var n,t;"undefined"!==typeof window&&window.addEventListener("vrdisplaypresentchange",b,!1);this.standing=this.enabled=!1;this.getDevice=
16656 function(){return d};this.setDevice=function(a){void 0!==a&&(d=a)};this.getCamera=function(a){if(null===d)return a;d.depthNear=a.near;d.depthFar=a.far;d.getFrameData(e);var b=e.pose;null!==b.position?a.position.fromArray(b.position):a.position.set(0,0,0);null!==b.orientation&&a.quaternion.fromArray(b.orientation);a.updateMatrixWorld();b=d.stageParameters;this.standing&&b&&(g.fromArray(b.sittingToStandingTransform),h.getInverse(g),a.matrixWorld.multiply(g),a.matrixWorldInverse.multiply(h));if(!1===
16657 d.isPresenting)return a;k.near=a.near;l.near=a.near;k.far=a.far;l.far=a.far;q.matrixWorld.copy(a.matrixWorld);q.matrixWorldInverse.copy(a.matrixWorldInverse);k.matrixWorldInverse.fromArray(e.leftViewMatrix);l.matrixWorldInverse.fromArray(e.rightViewMatrix);this.standing&&b&&(k.matrixWorldInverse.multiply(h),l.matrixWorldInverse.multiply(h));a=a.parent;null!==a&&(f.getInverse(a.matrixWorld),k.matrixWorldInverse.multiply(f),l.matrixWorldInverse.multiply(f));k.matrixWorld.getInverse(k.matrixWorldInverse);
16658 l.matrixWorld.getInverse(l.matrixWorldInverse);k.projectionMatrix.fromArray(e.leftProjectionMatrix);l.projectionMatrix.fromArray(e.rightProjectionMatrix);q.projectionMatrix.copy(k.projectionMatrix);a=d.getLayers();a.length&&(a=a[0],null!==a.leftBounds&&4===a.leftBounds.length&&k.bounds.fromArray(a.leftBounds),null!==a.rightBounds&&4===a.rightBounds.length&&l.bounds.fromArray(a.rightBounds));return q};this.getStandingMatrix=function(){return g};this.submitFrame=function(){d&&d.isPresenting&&d.submitFrame()};
16659 this.dispose=function(){"undefined"!==typeof window&&window.removeEventListener("vrdisplaypresentchange",b)}}function pg(a){var b={};return{get:function(c){if(void 0!==b[c])return b[c];switch(c){case "WEBGL_depth_texture":var d=a.getExtension("WEBGL_depth_texture")||a.getExtension("MOZ_WEBGL_depth_texture")||a.getExtension("WEBKIT_WEBGL_depth_texture");break;case "EXT_texture_filter_anisotropic":d=a.getExtension("EXT_texture_filter_anisotropic")||a.getExtension("MOZ_EXT_texture_filter_anisotropic")||
16660 a.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case "WEBGL_compressed_texture_s3tc":d=a.getExtension("WEBGL_compressed_texture_s3tc")||a.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||a.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case "WEBGL_compressed_texture_pvrtc":d=a.getExtension("WEBGL_compressed_texture_pvrtc")||a.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;case "WEBGL_compressed_texture_etc1":d=a.getExtension("WEBGL_compressed_texture_etc1");
16661 break;default:d=a.getExtension(c)}null===d&&console.warn("THREE.WebGLRenderer: "+c+" extension not supported.");return b[c]=d}}}function qg(){function a(){l.value!==d&&(l.value=d,l.needsUpdate=0<e);c.numPlanes=e;c.numIntersection=0}function b(a,b,d,e){var f=null!==a?a.length:0,g=null;if(0!==f){g=l.value;if(!0!==e||null===g){e=d+4*f;b=b.matrixWorldInverse;k.getNormalMatrix(b);if(null===g||g.length<e)g=new Float32Array(e);for(e=0;e!==f;++e,d+=4)h.copy(a[e]).applyMatrix4(b,k),h.normal.toArray(g,d),g[d+
16662 3]=h.constant}l.value=g;l.needsUpdate=!0}c.numPlanes=f;return g}var c=this,d=null,e=0,f=!1,g=!1,h=new Aa,k=new ra,l={value:null,needsUpdate:!1};this.uniform=l;this.numIntersection=this.numPlanes=0;this.init=function(a,c,g){var h=0!==a.length||c||0!==e||f;f=c;d=b(a,g,0);e=a.length;return h};this.beginShadows=function(){g=!0;b(null)};this.endShadows=function(){g=!1;a()};this.setState=function(c,h,k,r,m,p){if(!f||null===c||0===c.length||g&&!k)g?b(null):a();else{k=g?0:e;var n=4*k,q=m.clippingState||null;
16663 l.value=q;q=b(c,r,n,p);for(c=0;c!==n;++c)q[c]=d[c];m.clippingState=q;this.numIntersection=h?this.numPlanes:0;this.numPlanes+=k}}}function Pe(a,b){return{convert:function(c){if(1E3===c)return a.REPEAT;if(1001===c)return a.CLAMP_TO_EDGE;if(1002===c)return a.MIRRORED_REPEAT;if(1003===c)return a.NEAREST;if(1004===c)return a.NEAREST_MIPMAP_NEAREST;if(1005===c)return a.NEAREST_MIPMAP_LINEAR;if(1006===c)return a.LINEAR;if(1007===c)return a.LINEAR_MIPMAP_NEAREST;if(1008===c)return a.LINEAR_MIPMAP_LINEAR;
16664 if(1009===c)return a.UNSIGNED_BYTE;if(1017===c)return a.UNSIGNED_SHORT_4_4_4_4;if(1018===c)return a.UNSIGNED_SHORT_5_5_5_1;if(1019===c)return a.UNSIGNED_SHORT_5_6_5;if(1010===c)return a.BYTE;if(1011===c)return a.SHORT;if(1012===c)return a.UNSIGNED_SHORT;if(1013===c)return a.INT;if(1014===c)return a.UNSIGNED_INT;if(1015===c)return a.FLOAT;if(1016===c){var d=b.get("OES_texture_half_float");if(null!==d)return d.HALF_FLOAT_OES}if(1021===c)return a.ALPHA;if(1022===c)return a.RGB;if(1023===c)return a.RGBA;
16665 if(1024===c)return a.LUMINANCE;if(1025===c)return a.LUMINANCE_ALPHA;if(1026===c)return a.DEPTH_COMPONENT;if(1027===c)return a.DEPTH_STENCIL;if(100===c)return a.FUNC_ADD;if(101===c)return a.FUNC_SUBTRACT;if(102===c)return a.FUNC_REVERSE_SUBTRACT;if(200===c)return a.ZERO;if(201===c)return a.ONE;if(202===c)return a.SRC_COLOR;if(203===c)return a.ONE_MINUS_SRC_COLOR;if(204===c)return a.SRC_ALPHA;if(205===c)return a.ONE_MINUS_SRC_ALPHA;if(206===c)return a.DST_ALPHA;if(207===c)return a.ONE_MINUS_DST_ALPHA;
16666 if(208===c)return a.DST_COLOR;if(209===c)return a.ONE_MINUS_DST_COLOR;if(210===c)return a.SRC_ALPHA_SATURATE;if(2001===c||2002===c||2003===c||2004===c)if(d=b.get("WEBGL_compressed_texture_s3tc"),null!==d){if(2001===c)return d.COMPRESSED_RGB_S3TC_DXT1_EXT;if(2002===c)return d.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(2003===c)return d.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(2004===c)return d.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(2100===c||2101===c||2102===c||2103===c)if(d=b.get("WEBGL_compressed_texture_pvrtc"),null!==
16667 d){if(2100===c)return d.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(2101===c)return d.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(2102===c)return d.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(2103===c)return d.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(2151===c&&(d=b.get("WEBGL_compressed_texture_etc1"),null!==d))return d.COMPRESSED_RGB_ETC1_WEBGL;if(103===c||104===c)if(d=b.get("EXT_blend_minmax"),null!==d){if(103===c)return d.MIN_EXT;if(104===c)return d.MAX_EXT}return 1020===c&&(d=b.get("WEBGL_depth_texture"),null!==d)?d.UNSIGNED_INT_24_8_WEBGL:
16668 0}}}function Wd(a){function b(){ia=new pg(F);ia.get("WEBGL_depth_texture");ia.get("OES_texture_float");ia.get("OES_texture_float_linear");ia.get("OES_texture_half_float");ia.get("OES_texture_half_float_linear");ia.get("OES_standard_derivatives");ia.get("OES_element_index_uint");ia.get("ANGLE_instanced_arrays");oa=new Pe(F,ia);Z=new ng(F,ia,a);ba=new mg(F,ia,oa);ba.scissor(S.copy(ea).multiplyScalar(O));ba.viewport(Q.copy(ca).multiplyScalar(O));U=new lg;T=new kg(F,ia,ba,U,Z,oa,Vd);na=new Mf(F);pa=new Zf(F,
16669 na,Vd);ra=new bg(pa,Ra);va=new Wf(F);ma=new jg(L,ia,Z);sa=new ag;qa=new Uf;ja=new Qf(L,ba,pa,J);wa=new Yf(F,ia,Ra);xa=new Xf(F,ia,Ra);ya=new Jf(L,F,ba,T,Z);Aa=new Kf(L,F,ba,T,Z);L.info.programs=ma.programs;L.context=F;L.capabilities=Z;L.extensions=ia;L.properties=U;L.renderLists=qa;L.state=ba}function c(a){a.preventDefault();console.log("THREE.WebGLRenderer: Context Lost.");Y=!0}function d(){console.log("THREE.WebGLRenderer: Context Restored.");Y=!1;b()}function e(a){a=a.target;a.removeEventListener("dispose",
16670 e);f(a);U.remove(a)}function f(a){var b=U.get(a).program;a.program=void 0;void 0!==b&&ma.releaseProgram(b)}function g(a,b,c){a.render(function(a){L.renderBufferImmediate(a,b,c)})}function h(a){null!==Ba&&Ba(a);(a=ka.getDevice())&&a.isPresenting?a.requestAnimationFrame(h):window.requestAnimationFrame(h)}function k(a,b,c){if(!1!==a.visible){if(a.layers.test(b.layers))if(a.isLight)y.push(a),a.castShadow&&C.push(a);else if(a.isSprite)a.frustumCulled&&!Td.intersectsSprite(a)||D.push(a);else if(a.isLensFlare)Va.push(a);
16671 else if(a.isImmediateRenderObject)c&&Nb.setFromMatrixPosition(a.matrixWorld).applyMatrix4(md),A.push(a,null,a.material,Nb.z,null);else if(a.isMesh||a.isLine||a.isPoints)if(a.isSkinnedMesh&&a.skeleton.update(),!a.frustumCulled||Td.intersectsObject(a)){c&&Nb.setFromMatrixPosition(a.matrixWorld).applyMatrix4(md);var d=ra.update(a),e=a.material;if(Array.isArray(e))for(var f=d.groups,g=0,h=f.length;g<h;g++){var l=f[g],n=e[l.materialIndex];n&&n.visible&&A.push(a,d,n,Nb.z,l)}else e.visible&&A.push(a,d,e,
16672 Nb.z,null)}a=a.children;g=0;for(h=a.length;g<h;g++)k(a[g],b,c)}}function l(a,b,c,d){for(var e=0,f=a.length;e<f;e++){var g=a[e],h=g.object,l=g.geometry,k=void 0===d?g.material:d,g=g.group;if(c.isArrayCamera){aa=c;for(var n=c.cameras,t=0,r=n.length;t<r;t++){var m=n[t];if(h.layers.test(m.layers)){var u=m.bounds;ba.viewport(Q.set(u.x*X,u.y*fa,u.z*X,u.w*fa).multiplyScalar(O));q(h,b,m,l,k,g)}}}else aa=null,q(h,b,c,l,k,g)}}function q(a,b,c,d,e,f){a.onBeforeRender(L,b,c,d,e,f);a.modelViewMatrix.multiplyMatrices(c.matrixWorldInverse,
16673 a.matrixWorld);a.normalMatrix.getNormalMatrix(a.modelViewMatrix);if(a.isImmediateRenderObject){ba.setMaterial(e);var h=t(c,b.fog,e,a);N="";g(a,h,e)}else L.renderBufferDirect(c,b.fog,d,e,a,f);a.onAfterRender(L,b,c,d,e,f)}function n(a,b,c){var d=U.get(a);c=ma.getParameters(a,sa.state,C,b,Fa.numPlanes,Fa.numIntersection,c);var g=ma.getProgramCode(a,c),h=d.program,l=!0;if(void 0===h)a.addEventListener("dispose",e);else if(h.code!==g)f(a);else{if(void 0!==c.shaderID)return;l=!1}l&&(c.shaderID?(h=mb[c.shaderID],
16674 d.shader={name:a.type,uniforms:Ea.clone(h.uniforms),vertexShader:h.vertexShader,fragmentShader:h.fragmentShader}):d.shader={name:a.type,uniforms:a.uniforms,vertexShader:a.vertexShader,fragmentShader:a.fragmentShader},a.onBeforeCompile(d.shader),h=ma.acquireProgram(a,d.shader,c,g),d.program=h,a.program=h);c=h.getAttributes();if(a.morphTargets)for(g=a.numSupportedMorphTargets=0;g<L.maxMorphTargets;g++)0<=c["morphTarget"+g]&&a.numSupportedMorphTargets++;if(a.morphNormals)for(g=a.numSupportedMorphNormals=
16675 0;g<L.maxMorphNormals;g++)0<=c["morphNormal"+g]&&a.numSupportedMorphNormals++;c=d.shader.uniforms;if(!a.isShaderMaterial&&!a.isRawShaderMaterial||!0===a.clipping)d.numClippingPlanes=Fa.numPlanes,d.numIntersection=Fa.numIntersection,c.clippingPlanes=Fa.uniform;d.fog=b;d.lightsHash=sa.state.hash;a.lights&&(c.ambientLightColor.value=sa.state.ambient,c.directionalLights.value=sa.state.directional,c.spotLights.value=sa.state.spot,c.rectAreaLights.value=sa.state.rectArea,c.pointLights.value=sa.state.point,
16676 c.hemisphereLights.value=sa.state.hemi,c.directionalShadowMap.value=sa.state.directionalShadowMap,c.directionalShadowMatrix.value=sa.state.directionalShadowMatrix,c.spotShadowMap.value=sa.state.spotShadowMap,c.spotShadowMatrix.value=sa.state.spotShadowMatrix,c.pointShadowMap.value=sa.state.pointShadowMap,c.pointShadowMatrix.value=sa.state.pointShadowMatrix);a=d.program.getUniforms();a=gb.seqWithValue(a.seq,c);d.uniformsList=a}function t(a,b,c,d){G=0;var e=U.get(c);ga&&(Ud||a!==P)&&Fa.setState(c.clippingPlanes,
16677 c.clipIntersection,c.clipShadows,a,e,a===P&&c.id===V);!1===c.needsUpdate&&(void 0===e.program?c.needsUpdate=!0:c.fog&&e.fog!==b?c.needsUpdate=!0:c.lights&&e.lightsHash!==sa.state.hash?c.needsUpdate=!0:void 0===e.numClippingPlanes||e.numClippingPlanes===Fa.numPlanes&&e.numIntersection===Fa.numIntersection||(c.needsUpdate=!0));c.needsUpdate&&(n(c,b,d),c.needsUpdate=!1);var f=!1,g=!1,h=!1,l=e.program,k=l.getUniforms(),q=e.shader.uniforms;ba.useProgram(l.program)&&(h=g=f=!0);c.id!==V&&(V=c.id,g=!0);if(f||
16678 a!==P){k.setValue(F,"projectionMatrix",a.projectionMatrix);Z.logarithmicDepthBuffer&&k.setValue(F,"logDepthBufFC",2/(Math.log(a.far+1)/Math.LN2));P!==(aa||a)&&(P=aa||a,h=g=!0);if(c.isShaderMaterial||c.isMeshPhongMaterial||c.isMeshStandardMaterial||c.envMap)f=k.map.cameraPosition,void 0!==f&&f.setValue(F,Nb.setFromMatrixPosition(a.matrixWorld));(c.isMeshPhongMaterial||c.isMeshLambertMaterial||c.isMeshBasicMaterial||c.isMeshStandardMaterial||c.isShaderMaterial||c.skinning)&&k.setValue(F,"viewMatrix",
16679 a.matrixWorldInverse)}if(c.skinning&&(k.setOptional(F,d,"bindMatrix"),k.setOptional(F,d,"bindMatrixInverse"),a=d.skeleton))if(f=a.bones,Z.floatVertexTextures){if(void 0===a.boneTexture){var f=Math.sqrt(4*f.length),f=R.ceilPowerOfTwo(f),f=Math.max(f,4),t=new Float32Array(f*f*4);t.set(a.boneMatrices);var u=new fb(t,f,f,1023,1015);a.boneMatrices=t;a.boneTexture=u;a.boneTextureSize=f}k.setValue(F,"boneTexture",a.boneTexture);k.setValue(F,"boneTextureSize",a.boneTextureSize)}else k.setOptional(F,a,"boneMatrices");
16680 g&&(k.setValue(F,"toneMappingExposure",L.toneMappingExposure),k.setValue(F,"toneMappingWhitePoint",L.toneMappingWhitePoint),c.lights&&(g=h,q.ambientLightColor.needsUpdate=g,q.directionalLights.needsUpdate=g,q.pointLights.needsUpdate=g,q.spotLights.needsUpdate=g,q.rectAreaLights.needsUpdate=g,q.hemisphereLights.needsUpdate=g),b&&c.fog&&(q.fogColor.value=b.color,b.isFog?(q.fogNear.value=b.near,q.fogFar.value=b.far):b.isFogExp2&&(q.fogDensity.value=b.density)),c.isMeshBasicMaterial?r(q,c):c.isMeshLambertMaterial?
16681 (r(q,c),c.emissiveMap&&(q.emissiveMap.value=c.emissiveMap)):c.isMeshPhongMaterial?(r(q,c),c.isMeshToonMaterial?(m(q,c),c.gradientMap&&(q.gradientMap.value=c.gradientMap)):m(q,c)):c.isMeshStandardMaterial?(r(q,c),c.isMeshPhysicalMaterial&&(q.clearCoat.value=c.clearCoat,q.clearCoatRoughness.value=c.clearCoatRoughness),q.roughness.value=c.roughness,q.metalness.value=c.metalness,c.roughnessMap&&(q.roughnessMap.value=c.roughnessMap),c.metalnessMap&&(q.metalnessMap.value=c.metalnessMap),c.emissiveMap&&
16682 (q.emissiveMap.value=c.emissiveMap),c.bumpMap&&(q.bumpMap.value=c.bumpMap,q.bumpScale.value=c.bumpScale),c.normalMap&&(q.normalMap.value=c.normalMap,q.normalScale.value.copy(c.normalScale)),c.displacementMap&&(q.displacementMap.value=c.displacementMap,q.displacementScale.value=c.displacementScale,q.displacementBias.value=c.displacementBias),c.envMap&&(q.envMapIntensity.value=c.envMapIntensity)):c.isMeshDepthMaterial?(r(q,c),c.displacementMap&&(q.displacementMap.value=c.displacementMap,q.displacementScale.value=
16683 c.displacementScale,q.displacementBias.value=c.displacementBias)):c.isMeshDistanceMaterial?(r(q,c),c.displacementMap&&(q.displacementMap.value=c.displacementMap,q.displacementScale.value=c.displacementScale,q.displacementBias.value=c.displacementBias),q.referencePosition.value.copy(c.referencePosition),q.nearDistance.value=c.nearDistance,q.farDistance.value=c.farDistance):c.isMeshNormalMaterial?(r(q,c),c.bumpMap&&(q.bumpMap.value=c.bumpMap,q.bumpScale.value=c.bumpScale),c.normalMap&&(q.normalMap.value=
16684 c.normalMap,q.normalScale.value.copy(c.normalScale)),c.displacementMap&&(q.displacementMap.value=c.displacementMap,q.displacementScale.value=c.displacementScale,q.displacementBias.value=c.displacementBias)):c.isLineBasicMaterial?(q.diffuse.value=c.color,q.opacity.value=c.opacity,c.isLineDashedMaterial&&(q.dashSize.value=c.dashSize,q.totalSize.value=c.dashSize+c.gapSize,q.scale.value=c.scale)):c.isPointsMaterial?(q.diffuse.value=c.color,q.opacity.value=c.opacity,q.size.value=c.size*O,q.scale.value=
16685 .5*fa,q.map.value=c.map,null!==c.map&&(!0===c.map.matrixAutoUpdate&&(b=c.map.offset,g=c.map.repeat,h=c.map.center,c.map.matrix.setUvTransform(b.x,b.y,g.x,g.y,c.map.rotation,h.x,h.y)),q.uvTransform.value.copy(c.map.matrix))):c.isShadowMaterial&&(q.color.value=c.color,q.opacity.value=c.opacity),void 0!==q.ltcMat&&(q.ltcMat.value=E.LTC_MAT_TEXTURE),void 0!==q.ltcMag&&(q.ltcMag.value=E.LTC_MAG_TEXTURE),gb.upload(F,e.uniformsList,q,L));k.setValue(F,"modelViewMatrix",d.modelViewMatrix);k.setValue(F,"normalMatrix",
16686 d.normalMatrix);k.setValue(F,"modelMatrix",d.matrixWorld);return l}function r(a,b){a.opacity.value=b.opacity;b.color&&(a.diffuse.value=b.color);b.emissive&&a.emissive.value.copy(b.emissive).multiplyScalar(b.emissiveIntensity);b.map&&(a.map.value=b.map);b.alphaMap&&(a.alphaMap.value=b.alphaMap);b.specularMap&&(a.specularMap.value=b.specularMap);b.envMap&&(a.envMap.value=b.envMap,a.flipEnvMap.value=b.envMap&&b.envMap.isCubeTexture?-1:1,a.reflectivity.value=b.reflectivity,a.refractionRatio.value=b.refractionRatio);
16687 b.lightMap&&(a.lightMap.value=b.lightMap,a.lightMapIntensity.value=b.lightMapIntensity);b.aoMap&&(a.aoMap.value=b.aoMap,a.aoMapIntensity.value=b.aoMapIntensity);if(b.map)var c=b.map;else b.specularMap?c=b.specularMap:b.displacementMap?c=b.displacementMap:b.normalMap?c=b.normalMap:b.bumpMap?c=b.bumpMap:b.roughnessMap?c=b.roughnessMap:b.metalnessMap?c=b.metalnessMap:b.alphaMap?c=b.alphaMap:b.emissiveMap&&(c=b.emissiveMap);if(void 0!==c){c.isWebGLRenderTarget&&(c=c.texture);if(!0===c.matrixAutoUpdate){b=
16688 c.offset;var d=c.repeat,e=c.center;c.matrix.setUvTransform(b.x,b.y,d.x,d.y,c.rotation,e.x,e.y)}a.uvTransform.value.copy(c.matrix)}}function m(a,b){a.specular.value=b.specular;a.shininess.value=Math.max(b.shininess,1E-4);b.emissiveMap&&(a.emissiveMap.value=b.emissiveMap);b.bumpMap&&(a.bumpMap.value=b.bumpMap,a.bumpScale.value=b.bumpScale);b.normalMap&&(a.normalMap.value=b.normalMap,a.normalScale.value.copy(b.normalScale));b.displacementMap&&(a.displacementMap.value=b.displacementMap,a.displacementScale.value=
16689 b.displacementScale,a.displacementBias.value=b.displacementBias)}console.log("THREE.WebGLRenderer","88");a=a||{};var v=void 0!==a.canvas?a.canvas:document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),w=void 0!==a.context?a.context:null,x=void 0!==a.alpha?a.alpha:!1,z=void 0!==a.depth?a.depth:!0,I=void 0!==a.stencil?a.stencil:!0,B=void 0!==a.antialias?a.antialias:!1,J=void 0!==a.premultipliedAlpha?a.premultipliedAlpha:!0,ta=void 0!==a.preserveDrawingBuffer?a.preserveDrawingBuffer:!1,y=
16690 [],C=[],A=null,D=[],Va=[];this.domElement=v;this.context=null;this.sortObjects=this.autoClearStencil=this.autoClearDepth=this.autoClearColor=this.autoClear=!0;this.clippingPlanes=[];this.localClippingEnabled=!1;this.gammaFactor=2;this.physicallyCorrectLights=this.gammaOutput=this.gammaInput=!1;this.toneMappingWhitePoint=this.toneMappingExposure=this.toneMapping=1;this.maxMorphTargets=8;this.maxMorphNormals=4;var L=this,Y=!1,H=null,M=null,V=-1,N="",P=null,aa=null,Q=new da,S=new da,W=null,G=0,X=v.width,
16691 fa=v.height,O=1,ca=new da(0,0,X,fa),ea=new da(0,0,X,fa),Oe=!1,Td=new ld,Fa=new qg,ga=!1,Ud=!1,md=new K,Nb=new p,Vd={geometries:0,textures:0},Ra={frame:0,calls:0,vertices:0,faces:0,points:0};this.info={render:Ra,memory:Vd,programs:null};try{x={alpha:x,depth:z,stencil:I,antialias:B,premultipliedAlpha:J,preserveDrawingBuffer:ta};var F=w||v.getContext("webgl",x)||v.getContext("experimental-webgl",x);if(null===F){if(null!==v.getContext("webgl"))throw"Error creating WebGL context with your selected attributes.";
16692 throw"Error creating WebGL context.";}void 0===F.getShaderPrecisionFormat&&(F.getShaderPrecisionFormat=function(){return{rangeMin:1,rangeMax:1,precision:1}});v.addEventListener("webglcontextlost",c,!1);v.addEventListener("webglcontextrestored",d,!1)}catch(rg){console.error("THREE.WebGLRenderer: "+rg)}var ia,Z,ba,U,T,na,pa,ra,sa,ma,qa,ja,va,wa,xa,ya,Aa,oa;b();var ka=new og(L);this.vr=ka;var Ca=new Ie(L,ra,Z.maxTextureSize);this.shadowMap=Ca;this.getContext=function(){return F};this.getContextAttributes=
16693 function(){return F.getContextAttributes()};this.forceContextLoss=function(){var a=ia.get("WEBGL_lose_context");a&&a.loseContext()};this.forceContextRestore=function(){var a=ia.get("WEBGL_lose_context");a&&a.restoreContext()};this.getPixelRatio=function(){return O};this.setPixelRatio=function(a){void 0!==a&&(O=a,this.setSize(X,fa,!1))};this.getSize=function(){return{width:X,height:fa}};this.setSize=function(a,b,c){var d=ka.getDevice();d&&d.isPresenting?console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting."):
16694 (X=a,fa=b,v.width=a*O,v.height=b*O,!1!==c&&(v.style.width=a+"px",v.style.height=b+"px"),this.setViewport(0,0,a,b))};this.getDrawingBufferSize=function(){return{width:X*O,height:fa*O}};this.setDrawingBufferSize=function(a,b,c){X=a;fa=b;O=c;v.width=a*c;v.height=b*c;this.setViewport(0,0,a,b)};this.setViewport=function(a,b,c,d){ca.set(a,fa-b-d,c,d);ba.viewport(Q.copy(ca).multiplyScalar(O))};this.setScissor=function(a,b,c,d){ea.set(a,fa-b-d,c,d);ba.scissor(S.copy(ea).multiplyScalar(O))};this.setScissorTest=
16695 function(a){ba.setScissorTest(Oe=a)};this.getClearColor=function(){return ja.getClearColor()};this.setClearColor=function(){ja.setClearColor.apply(ja,arguments)};this.getClearAlpha=function(){return ja.getClearAlpha()};this.setClearAlpha=function(){ja.setClearAlpha.apply(ja,arguments)};this.clear=function(a,b,c){var d=0;if(void 0===a||a)d|=F.COLOR_BUFFER_BIT;if(void 0===b||b)d|=F.DEPTH_BUFFER_BIT;if(void 0===c||c)d|=F.STENCIL_BUFFER_BIT;F.clear(d)};this.clearColor=function(){this.clear(!0,!1,!1)};
16696 this.clearDepth=function(){this.clear(!1,!0,!1)};this.clearStencil=function(){this.clear(!1,!1,!0)};this.clearTarget=function(a,b,c,d){this.setRenderTarget(a);this.clear(b,c,d)};this.dispose=function(){v.removeEventListener("webglcontextlost",c,!1);v.removeEventListener("webglcontextrestored",d,!1);qa.dispose();ka.dispose()};this.renderBufferImmediate=function(a,b,c){ba.initAttributes();var d=U.get(a);a.hasPositions&&!d.position&&(d.position=F.createBuffer());a.hasNormals&&!d.normal&&(d.normal=F.createBuffer());
16697 a.hasUvs&&!d.uv&&(d.uv=F.createBuffer());a.hasColors&&!d.color&&(d.color=F.createBuffer());b=b.getAttributes();a.hasPositions&&(F.bindBuffer(F.ARRAY_BUFFER,d.position),F.bufferData(F.ARRAY_BUFFER,a.positionArray,F.DYNAMIC_DRAW),ba.enableAttribute(b.position),F.vertexAttribPointer(b.position,3,F.FLOAT,!1,0,0));if(a.hasNormals){F.bindBuffer(F.ARRAY_BUFFER,d.normal);if(!c.isMeshPhongMaterial&&!c.isMeshStandardMaterial&&!c.isMeshNormalMaterial&&!0===c.flatShading)for(var e=0,f=3*a.count;e<f;e+=9){var g=
16698 a.normalArray,h=(g[e+0]+g[e+3]+g[e+6])/3,l=(g[e+1]+g[e+4]+g[e+7])/3,k=(g[e+2]+g[e+5]+g[e+8])/3;g[e+0]=h;g[e+1]=l;g[e+2]=k;g[e+3]=h;g[e+4]=l;g[e+5]=k;g[e+6]=h;g[e+7]=l;g[e+8]=k}F.bufferData(F.ARRAY_BUFFER,a.normalArray,F.DYNAMIC_DRAW);ba.enableAttribute(b.normal);F.vertexAttribPointer(b.normal,3,F.FLOAT,!1,0,0)}a.hasUvs&&c.map&&(F.bindBuffer(F.ARRAY_BUFFER,d.uv),F.bufferData(F.ARRAY_BUFFER,a.uvArray,F.DYNAMIC_DRAW),ba.enableAttribute(b.uv),F.vertexAttribPointer(b.uv,2,F.FLOAT,!1,0,0));a.hasColors&&
16699 0!==c.vertexColors&&(F.bindBuffer(F.ARRAY_BUFFER,d.color),F.bufferData(F.ARRAY_BUFFER,a.colorArray,F.DYNAMIC_DRAW),ba.enableAttribute(b.color),F.vertexAttribPointer(b.color,3,F.FLOAT,!1,0,0));ba.disableUnusedAttributes();F.drawArrays(F.TRIANGLES,0,a.count);a.count=0};this.renderBufferDirect=function(a,b,c,d,e,f){ba.setMaterial(d);var g=t(a,b,d,e);a=c.id+"_"+g.id+"_"+(!0===d.wireframe);var h=!1;a!==N&&(N=a,h=!0);e.morphTargetInfluences&&(va.update(e,c,d,g),h=!0);var l=c.index,k=c.attributes.position;
16700 b=1;!0===d.wireframe&&(l=pa.getWireframeAttribute(c),b=2);a=wa;if(null!==l){var n=na.get(l);a=xa;a.setIndex(n)}if(h){h=void 0;if(c&&c.isInstancedBufferGeometry&&null===ia.get("ANGLE_instanced_arrays"))console.error("THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");else{void 0===h&&(h=0);ba.initAttributes();var q=c.attributes,g=g.getAttributes(),r=d.defaultAttributeValues;for(J in g){var m=g[J];if(0<=m){var u=
16701 q[J];if(void 0!==u){var p=u.normalized,v=u.itemSize,w=na.get(u);if(void 0!==w){var z=w.buffer,x=w.type,w=w.bytesPerElement;if(u.isInterleavedBufferAttribute){var B=u.data,I=B.stride,u=u.offset;B&&B.isInstancedInterleavedBuffer?(ba.enableAttributeAndDivisor(m,B.meshPerAttribute),void 0===c.maxInstancedCount&&(c.maxInstancedCount=B.meshPerAttribute*B.count)):ba.enableAttribute(m);F.bindBuffer(F.ARRAY_BUFFER,z);F.vertexAttribPointer(m,v,x,p,I*w,(h*I+u)*w)}else u.isInstancedBufferAttribute?(ba.enableAttributeAndDivisor(m,
16702 u.meshPerAttribute),void 0===c.maxInstancedCount&&(c.maxInstancedCount=u.meshPerAttribute*u.count)):ba.enableAttribute(m),F.bindBuffer(F.ARRAY_BUFFER,z),F.vertexAttribPointer(m,v,x,p,0,h*v*w)}}else if(void 0!==r&&(p=r[J],void 0!==p))switch(p.length){case 2:F.vertexAttrib2fv(m,p);break;case 3:F.vertexAttrib3fv(m,p);break;case 4:F.vertexAttrib4fv(m,p);break;default:F.vertexAttrib1fv(m,p)}}}ba.disableUnusedAttributes()}null!==l&&F.bindBuffer(F.ELEMENT_ARRAY_BUFFER,n.buffer)}n=0;null!==l?n=l.count:void 0!==
16703 k&&(n=k.count);l=c.drawRange.start*b;k=null!==f?f.start*b:0;var J=Math.max(l,k);f=Math.max(0,Math.min(n,l+c.drawRange.count*b,k+(null!==f?f.count*b:Infinity))-1-J+1);if(0!==f){if(e.isMesh)if(!0===d.wireframe)ba.setLineWidth(d.wireframeLinewidth*(null===H?O:1)),a.setMode(F.LINES);else switch(e.drawMode){case 0:a.setMode(F.TRIANGLES);break;case 1:a.setMode(F.TRIANGLE_STRIP);break;case 2:a.setMode(F.TRIANGLE_FAN)}else e.isLine?(d=d.linewidth,void 0===d&&(d=1),ba.setLineWidth(d*(null===H?O:1)),e.isLineSegments?
16704 a.setMode(F.LINES):e.isLineLoop?a.setMode(F.LINE_LOOP):a.setMode(F.LINE_STRIP)):e.isPoints&&a.setMode(F.POINTS);c&&c.isInstancedBufferGeometry?0<c.maxInstancedCount&&a.renderInstances(c,J,f):a.render(J,f)}};this.compile=function(a,b){y.length=0;C.length=0;a.traverse(function(a){a.isLight&&(y.push(a),a.castShadow&&C.push(a))});sa.setup(y,C,b);a.traverse(function(b){if(b.material)if(Array.isArray(b.material))for(var c=0;c<b.material.length;c++)n(b.material[c],a.fog,b);else n(b.material,a.fog,b)})};
16705 var Da=!1,Ba=null;this.animate=function(a){Ba=a;Da||((a=ka.getDevice())&&a.isPresenting?a.requestAnimationFrame(h):window.requestAnimationFrame(h),Da=!0)};this.render=function(a,b,c,d){if(!b||!b.isCamera)console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");else if(!Y){N="";V=-1;P=null;!0===a.autoUpdate&&a.updateMatrixWorld();null===b.parent&&b.updateMatrixWorld();ka.enabled&&(b=ka.getCamera(b));md.multiplyMatrices(b.projectionMatrix,b.matrixWorldInverse);Td.setFromMatrix(md);
16706 y.length=0;C.length=0;D.length=0;Va.length=0;Ud=this.localClippingEnabled;ga=Fa.init(this.clippingPlanes,Ud,b);A=qa.get(a,b);A.init();k(a,b,L.sortObjects);!0===L.sortObjects&&A.sort();ga&&Fa.beginShadows();Ca.render(C,a,b);sa.setup(y,C,b);ga&&Fa.endShadows();Ra.frame++;Ra.calls=0;Ra.vertices=0;Ra.faces=0;Ra.points=0;void 0===c&&(c=null);this.setRenderTarget(c);ja.render(A,a,b,d);d=A.opaque;var e=A.transparent;if(a.overrideMaterial){var f=a.overrideMaterial;d.length&&l(d,a,b,f);e.length&&l(e,a,b,f)}else d.length&&
16707 l(d,a,b),e.length&&l(e,a,b);Aa.render(D,a,b);ya.render(Va,a,b,Q);c&&T.updateRenderTargetMipmap(c);ba.buffers.depth.setTest(!0);ba.buffers.depth.setMask(!0);ba.buffers.color.setMask(!0);ba.setPolygonOffset(!1);ka.enabled&&ka.submitFrame()}};this.setFaceCulling=function(a,b){ba.setCullFace(a);ba.setFlipSided(0===b)};this.allocTextureUnit=function(){var a=G;a>=Z.maxTextures&&console.warn("THREE.WebGLRenderer: Trying to use "+a+" texture units while this GPU supports only "+Z.maxTextures);G+=1;return a};
16708 this.setTexture2D=function(){var a=!1;return function(b,c){b&&b.isWebGLRenderTarget&&(a||(console.warn("THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead."),a=!0),b=b.texture);T.setTexture2D(b,c)}}();this.setTexture=function(){var a=!1;return function(b,c){a||(console.warn("THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead."),a=!0);T.setTexture2D(b,c)}}();this.setTextureCube=function(){var a=!1;return function(b,c){b&&
16709 b.isWebGLRenderTargetCube&&(a||(console.warn("THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead."),a=!0),b=b.texture);b&&b.isCubeTexture||Array.isArray(b.image)&&6===b.image.length?T.setTextureCube(b,c):T.setTextureCubeDynamic(b,c)}}();this.getRenderTarget=function(){return H};this.setRenderTarget=function(a){(H=a)&&void 0===U.get(a).__webglFramebuffer&&T.setupRenderTarget(a);var b=null,c=!1;a?(b=U.get(a).__webglFramebuffer,a.isWebGLRenderTargetCube&&
16710 (b=b[a.activeCubeFace],c=!0),Q.copy(a.viewport),S.copy(a.scissor),W=a.scissorTest):(Q.copy(ca).multiplyScalar(O),S.copy(ea).multiplyScalar(O),W=Oe);M!==b&&(F.bindFramebuffer(F.FRAMEBUFFER,b),M=b);ba.viewport(Q);ba.scissor(S);ba.setScissorTest(W);c&&(c=U.get(a.texture),F.framebufferTexture2D(F.FRAMEBUFFER,F.COLOR_ATTACHMENT0,F.TEXTURE_CUBE_MAP_POSITIVE_X+a.activeCubeFace,c.__webglTexture,a.activeMipMapLevel))};this.readRenderTargetPixels=function(a,b,c,d,e,f){if(a&&a.isWebGLRenderTarget){var g=U.get(a).__webglFramebuffer;
16711 if(g){var h=!1;g!==M&&(F.bindFramebuffer(F.FRAMEBUFFER,g),h=!0);try{var l=a.texture,k=l.format,n=l.type;1023!==k&&oa.convert(k)!==F.getParameter(F.IMPLEMENTATION_COLOR_READ_FORMAT)?console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format."):1009===n||oa.convert(n)===F.getParameter(F.IMPLEMENTATION_COLOR_READ_TYPE)||1015===n&&(ia.get("OES_texture_float")||ia.get("WEBGL_color_buffer_float"))||1016===n&&ia.get("EXT_color_buffer_half_float")?
16712 F.checkFramebufferStatus(F.FRAMEBUFFER)===F.FRAMEBUFFER_COMPLETE?0<=b&&b<=a.width-d&&0<=c&&c<=a.height-e&&F.readPixels(b,c,d,e,oa.convert(k),oa.convert(n),f):console.error("THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete."):console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.")}finally{h&&F.bindFramebuffer(F.FRAMEBUFFER,M)}}}else console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.")}}
16713 function Ob(a,b){this.name="";this.color=new H(a);this.density=void 0!==b?b:2.5E-4}function Pb(a,b,c){this.name="";this.color=new H(a);this.near=void 0!==b?b:1;this.far=void 0!==c?c:1E3}function od(){A.call(this);this.type="Scene";this.overrideMaterial=this.fog=this.background=null;this.autoUpdate=!0}function Xd(a,b,c,d,e){A.call(this);this.lensFlares=[];this.positionScreen=new p;this.customUpdateCallback=void 0;void 0!==a&&this.add(a,b,c,d,e)}function Za(a){Q.call(this);this.type="SpriteMaterial";
16714 this.color=new H(16777215);this.map=null;this.rotation=0;this.lights=this.fog=!1;this.setValues(a)}function Cc(a){A.call(this);this.type="Sprite";this.material=void 0!==a?a:new Za}function Dc(){A.call(this);this.type="LOD";Object.defineProperties(this,{levels:{enumerable:!0,value:[]}})}function Ec(a,b){a=a||[];this.bones=a.slice(0);this.boneMatrices=new Float32Array(16*this.bones.length);if(void 0===b)this.calculateInverses();else if(this.bones.length===b.length)this.boneInverses=b.slice(0);else for(console.warn("THREE.Skeleton boneInverses is the wrong length."),
16715 this.boneInverses=[],a=0,b=this.bones.length;a<b;a++)this.boneInverses.push(new K)}function pd(){A.call(this);this.type="Bone"}function qd(a,b){pa.call(this,a,b);this.type="SkinnedMesh";this.bindMode="attached";this.bindMatrix=new K;this.bindMatrixInverse=new K;a=this.initBones();a=new Ec(a);this.bind(a,this.matrixWorld);this.normalizeSkinWeights()}function O(a){Q.call(this);this.type="LineBasicMaterial";this.color=new H(16777215);this.linewidth=1;this.linejoin=this.linecap="round";this.lights=!1;
16716 this.setValues(a)}function ma(a,b,c){if(1===c)return console.warn("THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead."),new ca(a,b);A.call(this);this.type="Line";this.geometry=void 0!==a?a:new D;this.material=void 0!==b?b:new O({color:16777215*Math.random()})}function ca(a,b){ma.call(this,a,b);this.type="LineSegments"}function rd(a,b){ma.call(this,a,b);this.type="LineLoop"}function Ba(a){Q.call(this);this.type="PointsMaterial";this.color=new H(16777215);
16717 this.map=null;this.size=1;this.sizeAttenuation=!0;this.lights=!1;this.setValues(a)}function Qb(a,b){A.call(this);this.type="Points";this.geometry=void 0!==a?a:new D;this.material=void 0!==b?b:new Ba({color:16777215*Math.random()})}function Fc(){A.call(this);this.type="Group"}function sd(a,b,c,d,e,f,g,h,k){function l(){var a=q.image;a.readyState>=a.HAVE_CURRENT_DATA&&(q.needsUpdate=!0);requestAnimationFrame(l)}ea.call(this,a,b,c,d,e,f,g,h,k);this.generateMipmaps=!1;var q=this;requestAnimationFrame(l)}
16718 function Rb(a,b,c,d,e,f,g,h,k,l,q,n){ea.call(this,null,f,g,h,k,l,d,e,q,n);this.image={width:b,height:c};this.mipmaps=a;this.generateMipmaps=this.flipY=!1}function Gc(a,b,c,d,e,f,g,h,k,l){l=void 0!==l?l:1026;if(1026!==l&&1027!==l)throw Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");void 0===c&&1026===l&&(c=1012);void 0===c&&1027===l&&(c=1020);ea.call(this,null,d,e,f,g,h,l,c,k);this.image={width:a,height:b};this.magFilter=void 0!==g?g:1003;this.minFilter=void 0!==
16719 h?h:1003;this.generateMipmaps=this.flipY=!1}function Sb(a){D.call(this);this.type="WireframeGeometry";var b=[],c,d,e,f=[0,0],g={},h=["a","b","c"];if(a&&a.isGeometry){var k=a.faces;var l=0;for(d=k.length;l<d;l++){var q=k[l];for(c=0;3>c;c++){var n=q[h[c]];var t=q[h[(c+1)%3]];f[0]=Math.min(n,t);f[1]=Math.max(n,t);n=f[0]+","+f[1];void 0===g[n]&&(g[n]={index1:f[0],index2:f[1]})}}for(n in g)l=g[n],h=a.vertices[l.index1],b.push(h.x,h.y,h.z),h=a.vertices[l.index2],b.push(h.x,h.y,h.z)}else if(a&&a.isBufferGeometry){var h=
16720 new p;if(null!==a.index){k=a.attributes.position;q=a.index;var r=a.groups;0===r.length&&(r=[{start:0,count:q.count,materialIndex:0}]);a=0;for(e=r.length;a<e;++a)for(l=r[a],c=l.start,d=l.count,l=c,d=c+d;l<d;l+=3)for(c=0;3>c;c++)n=q.getX(l+c),t=q.getX(l+(c+1)%3),f[0]=Math.min(n,t),f[1]=Math.max(n,t),n=f[0]+","+f[1],void 0===g[n]&&(g[n]={index1:f[0],index2:f[1]});for(n in g)l=g[n],h.fromBufferAttribute(k,l.index1),b.push(h.x,h.y,h.z),h.fromBufferAttribute(k,l.index2),b.push(h.x,h.y,h.z)}else for(k=a.attributes.position,
16721 l=0,d=k.count/3;l<d;l++)for(c=0;3>c;c++)g=3*l+c,h.fromBufferAttribute(k,g),b.push(h.x,h.y,h.z),g=3*l+(c+1)%3,h.fromBufferAttribute(k,g),b.push(h.x,h.y,h.z)}this.addAttribute("position",new y(b,3))}function Hc(a,b,c){N.call(this);this.type="ParametricGeometry";this.parameters={func:a,slices:b,stacks:c};this.fromBufferGeometry(new Tb(a,b,c));this.mergeVertices()}function Tb(a,b,c){D.call(this);this.type="ParametricBufferGeometry";this.parameters={func:a,slices:b,stacks:c};var d=[],e=[],f=[],g=[],h=
16722 new p,k=new p,l=new p,q=new p,n=new p,t,r,m=b+1;for(t=0;t<=c;t++){var v=t/c;for(r=0;r<=b;r++){var w=r/b,k=a(w,v,k);e.push(k.x,k.y,k.z);0<=w-1E-5?(l=a(w-1E-5,v,l),q.subVectors(k,l)):(l=a(w+1E-5,v,l),q.subVectors(l,k));0<=v-1E-5?(l=a(w,v-1E-5,l),n.subVectors(k,l)):(l=a(w,v+1E-5,l),n.subVectors(l,k));h.crossVectors(q,n).normalize();f.push(h.x,h.y,h.z);g.push(w,v)}}for(t=0;t<c;t++)for(r=0;r<b;r++)a=t*m+r+1,h=(t+1)*m+r+1,k=(t+1)*m+r,d.push(t*m+r,a,k),d.push(a,h,k);this.setIndex(d);this.addAttribute("position",
16723 new y(e,3));this.addAttribute("normal",new y(f,3));this.addAttribute("uv",new y(g,2))}function Ic(a,b,c,d){N.call(this);this.type="PolyhedronGeometry";this.parameters={vertices:a,indices:b,radius:c,detail:d};this.fromBufferGeometry(new qa(a,b,c,d));this.mergeVertices()}function qa(a,b,c,d){function e(a){h.push(a.x,a.y,a.z)}function f(b,c){b*=3;c.x=a[b+0];c.y=a[b+1];c.z=a[b+2]}function g(a,b,c,d){0>d&&1===a.x&&(k[b]=a.x-1);0===c.x&&0===c.z&&(k[b]=d/2/Math.PI+.5)}D.call(this);this.type="PolyhedronBufferGeometry";
16724 this.parameters={vertices:a,indices:b,radius:c,detail:d};c=c||1;d=d||0;var h=[],k=[];(function(a){for(var c=new p,d=new p,g=new p,h=0;h<b.length;h+=3){f(b[h+0],c);f(b[h+1],d);f(b[h+2],g);var k,l,m=c,x=d,z=g,I=Math.pow(2,a),B=[];for(l=0;l<=I;l++){B[l]=[];var J=m.clone().lerp(z,l/I),y=x.clone().lerp(z,l/I),C=I-l;for(k=0;k<=C;k++)B[l][k]=0===k&&l===I?J:J.clone().lerp(y,k/C)}for(l=0;l<I;l++)for(k=0;k<2*(I-l)-1;k++)m=Math.floor(k/2),0===k%2?(e(B[l][m+1]),e(B[l+1][m]),e(B[l][m])):(e(B[l][m+1]),e(B[l+1][m+
16725 1]),e(B[l+1][m]))}})(d);(function(a){for(var b=new p,c=0;c<h.length;c+=3)b.x=h[c+0],b.y=h[c+1],b.z=h[c+2],b.normalize().multiplyScalar(a),h[c+0]=b.x,h[c+1]=b.y,h[c+2]=b.z})(c);(function(){for(var a=new p,b=0;b<h.length;b+=3)a.x=h[b+0],a.y=h[b+1],a.z=h[b+2],k.push(Math.atan2(a.z,-a.x)/2/Math.PI+.5,1-(Math.atan2(-a.y,Math.sqrt(a.x*a.x+a.z*a.z))/Math.PI+.5));for(var a=new p,b=new p,c=new p,d=new p,e=new C,f=new C,m=new C,w=0,x=0;w<h.length;w+=9,x+=6){a.set(h[w+0],h[w+1],h[w+2]);b.set(h[w+3],h[w+4],h[w+
16726 5]);c.set(h[w+6],h[w+7],h[w+8]);e.set(k[x+0],k[x+1]);f.set(k[x+2],k[x+3]);m.set(k[x+4],k[x+5]);d.copy(a).add(b).add(c).divideScalar(3);var z=Math.atan2(d.z,-d.x);g(e,x+0,a,z);g(f,x+2,b,z);g(m,x+4,c,z)}for(a=0;a<k.length;a+=6)b=k[a+0],c=k[a+2],d=k[a+4],e=Math.min(b,c,d),.9<Math.max(b,c,d)&&.1>e&&(.2>b&&(k[a+0]+=1),.2>c&&(k[a+2]+=1),.2>d&&(k[a+4]+=1))})();this.addAttribute("position",new y(h,3));this.addAttribute("normal",new y(h.slice(),3));this.addAttribute("uv",new y(k,2));0===d?this.computeVertexNormals():
16727 this.normalizeNormals()}function Jc(a,b){N.call(this);this.type="TetrahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Ub(a,b));this.mergeVertices()}function Ub(a,b){qa.call(this,[1,1,1,-1,-1,1,-1,1,-1,1,-1,-1],[2,1,0,0,3,2,1,3,0,2,3,1],a,b);this.type="TetrahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Kc(a,b){N.call(this);this.type="OctahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new nb(a,b));this.mergeVertices()}
16728 function nb(a,b){qa.call(this,[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2],a,b);this.type="OctahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Lc(a,b){N.call(this);this.type="IcosahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Vb(a,b));this.mergeVertices()}function Vb(a,b){var c=(1+Math.sqrt(5))/2;qa.call(this,[-1,c,0,1,c,0,-1,-c,0,1,-c,0,0,-1,c,0,1,c,0,-1,-c,0,1,-c,c,0,-1,c,0,1,-c,0,-1,-c,0,1],[0,11,
16729 5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1],a,b);this.type="IcosahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Mc(a,b){N.call(this);this.type="DodecahedronGeometry";this.parameters={radius:a,detail:b};this.fromBufferGeometry(new Wb(a,b));this.mergeVertices()}function Wb(a,b){var c=(1+Math.sqrt(5))/2,d=1/c;qa.call(this,[-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-d,-c,0,-d,c,0,
16730 d,-c,0,d,c,-d,-c,0,-d,c,0,d,-c,0,d,c,0,-c,0,-d,c,0,-d,-c,0,d,c,0,d],[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9],a,b);this.type="DodecahedronBufferGeometry";this.parameters={radius:a,detail:b}}function Nc(a,b,c,d,e,f){N.call(this);this.type="TubeGeometry";this.parameters={path:a,
16731 tubularSegments:b,radius:c,radialSegments:d,closed:e};void 0!==f&&console.warn("THREE.TubeGeometry: taper has been removed.");a=new Xb(a,b,c,d,e);this.tangents=a.tangents;this.normals=a.normals;this.binormals=a.binormals;this.fromBufferGeometry(a);this.mergeVertices()}function Xb(a,b,c,d,e){function f(e){q=a.getPointAt(e/b,q);var f=g.normals[e];e=g.binormals[e];for(t=0;t<=d;t++){var l=t/d*Math.PI*2,n=Math.sin(l),l=-Math.cos(l);k.x=l*f.x+n*e.x;k.y=l*f.y+n*e.y;k.z=l*f.z+n*e.z;k.normalize();u.push(k.x,
16732 k.y,k.z);h.x=q.x+c*k.x;h.y=q.y+c*k.y;h.z=q.z+c*k.z;m.push(h.x,h.y,h.z)}}D.call(this);this.type="TubeBufferGeometry";this.parameters={path:a,tubularSegments:b,radius:c,radialSegments:d,closed:e};b=b||64;c=c||1;d=d||8;e=e||!1;var g=a.computeFrenetFrames(b,e);this.tangents=g.tangents;this.normals=g.normals;this.binormals=g.binormals;var h=new p,k=new p,l=new C,q=new p,n,t,m=[],u=[],v=[],w=[];for(n=0;n<b;n++)f(n);f(!1===e?b:0);for(n=0;n<=b;n++)for(t=0;t<=d;t++)l.x=n/b,l.y=t/d,v.push(l.x,l.y);(function(){for(t=
16733 1;t<=b;t++)for(n=1;n<=d;n++){var a=(d+1)*t+(n-1),c=(d+1)*t+n,e=(d+1)*(t-1)+n;w.push((d+1)*(t-1)+(n-1),a,e);w.push(a,c,e)}})();this.setIndex(w);this.addAttribute("position",new y(m,3));this.addAttribute("normal",new y(u,3));this.addAttribute("uv",new y(v,2))}function Oc(a,b,c,d,e,f,g){N.call(this);this.type="TorusKnotGeometry";this.parameters={radius:a,tube:b,tubularSegments:c,radialSegments:d,p:e,q:f};void 0!==g&&console.warn("THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.");
16734 this.fromBufferGeometry(new Yb(a,b,c,d,e,f));this.mergeVertices()}function Yb(a,b,c,d,e,f){function g(a,b,c,d,e){var f=Math.sin(a);b=c/b*a;c=Math.cos(b);e.x=d*(2+c)*.5*Math.cos(a);e.y=d*(2+c)*f*.5;e.z=d*Math.sin(b)*.5}D.call(this);this.type="TorusKnotBufferGeometry";this.parameters={radius:a,tube:b,tubularSegments:c,radialSegments:d,p:e,q:f};a=a||1;b=b||.4;c=Math.floor(c)||64;d=Math.floor(d)||8;e=e||2;f=f||3;var h=[],k=[],l=[],q=[],n,t=new p,m=new p,u=new p,v=new p,w=new p,x=new p,z=new p;for(n=0;n<=
16735 c;++n){var I=n/c*e*Math.PI*2;g(I,e,f,a,u);g(I+.01,e,f,a,v);x.subVectors(v,u);z.addVectors(v,u);w.crossVectors(x,z);z.crossVectors(w,x);w.normalize();z.normalize();for(I=0;I<=d;++I){var B=I/d*Math.PI*2,J=-b*Math.cos(B),B=b*Math.sin(B);t.x=u.x+(J*z.x+B*w.x);t.y=u.y+(J*z.y+B*w.y);t.z=u.z+(J*z.z+B*w.z);k.push(t.x,t.y,t.z);m.subVectors(t,u).normalize();l.push(m.x,m.y,m.z);q.push(n/c);q.push(I/d)}}for(I=1;I<=c;I++)for(n=1;n<=d;n++)a=(d+1)*I+(n-1),b=(d+1)*I+n,e=(d+1)*(I-1)+n,h.push((d+1)*(I-1)+(n-1),a,e),
16736 h.push(a,b,e);this.setIndex(h);this.addAttribute("position",new y(k,3));this.addAttribute("normal",new y(l,3));this.addAttribute("uv",new y(q,2))}function Pc(a,b,c,d,e){N.call(this);this.type="TorusGeometry";this.parameters={radius:a,tube:b,radialSegments:c,tubularSegments:d,arc:e};this.fromBufferGeometry(new Zb(a,b,c,d,e));this.mergeVertices()}function Zb(a,b,c,d,e){D.call(this);this.type="TorusBufferGeometry";this.parameters={radius:a,tube:b,radialSegments:c,tubularSegments:d,arc:e};a=a||1;b=b||
16737 .4;c=Math.floor(c)||8;d=Math.floor(d)||6;e=e||2*Math.PI;var f=[],g=[],h=[],k=[],l=new p,q=new p,n=new p,t,m;for(t=0;t<=c;t++)for(m=0;m<=d;m++){var u=m/d*e,v=t/c*Math.PI*2;q.x=(a+b*Math.cos(v))*Math.cos(u);q.y=(a+b*Math.cos(v))*Math.sin(u);q.z=b*Math.sin(v);g.push(q.x,q.y,q.z);l.x=a*Math.cos(u);l.y=a*Math.sin(u);n.subVectors(q,l).normalize();h.push(n.x,n.y,n.z);k.push(m/d);k.push(t/c)}for(t=1;t<=c;t++)for(m=1;m<=d;m++)a=(d+1)*(t-1)+m-1,b=(d+1)*(t-1)+m,e=(d+1)*t+m,f.push((d+1)*t+m-1,a,e),f.push(a,b,
16738 e);this.setIndex(f);this.addAttribute("position",new y(g,3));this.addAttribute("normal",new y(h,3));this.addAttribute("uv",new y(k,2))}function $a(a,b){N.call(this);this.type="ExtrudeGeometry";this.parameters={shapes:a,options:b};this.fromBufferGeometry(new Ga(a,b));this.mergeVertices()}function Ga(a,b){"undefined"!==typeof a&&(D.call(this),this.type="ExtrudeBufferGeometry",a=Array.isArray(a)?a:[a],this.addShapeList(a,b),this.computeVertexNormals())}function Qc(a,b){N.call(this);this.type="TextGeometry";
16739 this.parameters={text:a,parameters:b};this.fromBufferGeometry(new $b(a,b));this.mergeVertices()}function $b(a,b){b=b||{};var c=b.font;if(!c||!c.isFont)return console.error("THREE.TextGeometry: font parameter is not an instance of THREE.Font."),new N;a=c.generateShapes(a,b.size,b.curveSegments);b.amount=void 0!==b.height?b.height:50;void 0===b.bevelThickness&&(b.bevelThickness=10);void 0===b.bevelSize&&(b.bevelSize=8);void 0===b.bevelEnabled&&(b.bevelEnabled=!1);Ga.call(this,a,b);this.type="TextBufferGeometry"}
16740 function Rc(a,b,c,d,e,f,g){N.call(this);this.type="SphereGeometry";this.parameters={radius:a,widthSegments:b,heightSegments:c,phiStart:d,phiLength:e,thetaStart:f,thetaLength:g};this.fromBufferGeometry(new ob(a,b,c,d,e,f,g));this.mergeVertices()}function ob(a,b,c,d,e,f,g){D.call(this);this.type="SphereBufferGeometry";this.parameters={radius:a,widthSegments:b,heightSegments:c,phiStart:d,phiLength:e,thetaStart:f,thetaLength:g};a=a||1;b=Math.max(3,Math.floor(b)||8);c=Math.max(2,Math.floor(c)||6);d=void 0!==
16741 d?d:0;e=void 0!==e?e:2*Math.PI;f=void 0!==f?f:0;g=void 0!==g?g:Math.PI;var h=f+g,k,l,q=0,n=[],t=new p,m=new p,u=[],v=[],w=[],x=[];for(l=0;l<=c;l++){var z=[],I=l/c;for(k=0;k<=b;k++){var B=k/b;t.x=-a*Math.cos(d+B*e)*Math.sin(f+I*g);t.y=a*Math.cos(f+I*g);t.z=a*Math.sin(d+B*e)*Math.sin(f+I*g);v.push(t.x,t.y,t.z);m.set(t.x,t.y,t.z).normalize();w.push(m.x,m.y,m.z);x.push(B,1-I);z.push(q++)}n.push(z)}for(l=0;l<c;l++)for(k=0;k<b;k++)a=n[l][k+1],d=n[l][k],e=n[l+1][k],g=n[l+1][k+1],(0!==l||0<f)&&u.push(a,d,
16742 g),(l!==c-1||h<Math.PI)&&u.push(d,e,g);this.setIndex(u);this.addAttribute("position",new y(v,3));this.addAttribute("normal",new y(w,3));this.addAttribute("uv",new y(x,2))}function Sc(a,b,c,d,e,f){N.call(this);this.type="RingGeometry";this.parameters={innerRadius:a,outerRadius:b,thetaSegments:c,phiSegments:d,thetaStart:e,thetaLength:f};this.fromBufferGeometry(new ac(a,b,c,d,e,f));this.mergeVertices()}function ac(a,b,c,d,e,f){D.call(this);this.type="RingBufferGeometry";this.parameters={innerRadius:a,
16743 outerRadius:b,thetaSegments:c,phiSegments:d,thetaStart:e,thetaLength:f};a=a||.5;b=b||1;e=void 0!==e?e:0;f=void 0!==f?f:2*Math.PI;c=void 0!==c?Math.max(3,c):8;d=void 0!==d?Math.max(1,d):1;var g=[],h=[],k=[],l=[],q=a,n=(b-a)/d,t=new p,m=new C,u,v;for(u=0;u<=d;u++){for(v=0;v<=c;v++)a=e+v/c*f,t.x=q*Math.cos(a),t.y=q*Math.sin(a),h.push(t.x,t.y,t.z),k.push(0,0,1),m.x=(t.x/b+1)/2,m.y=(t.y/b+1)/2,l.push(m.x,m.y);q+=n}for(u=0;u<d;u++)for(b=u*(c+1),v=0;v<c;v++)a=v+b,e=a+c+1,f=a+c+2,q=a+1,g.push(a,e,q),g.push(e,
16744 f,q);this.setIndex(g);this.addAttribute("position",new y(h,3));this.addAttribute("normal",new y(k,3));this.addAttribute("uv",new y(l,2))}function Tc(a,b,c,d){N.call(this);this.type="LatheGeometry";this.parameters={points:a,segments:b,phiStart:c,phiLength:d};this.fromBufferGeometry(new bc(a,b,c,d));this.mergeVertices()}function bc(a,b,c,d){D.call(this);this.type="LatheBufferGeometry";this.parameters={points:a,segments:b,phiStart:c,phiLength:d};b=Math.floor(b)||12;c=c||0;d=d||2*Math.PI;d=R.clamp(d,
16745 0,2*Math.PI);var e=[],f=[],g=[],h=1/b,k=new p,l=new C,q;for(q=0;q<=b;q++){var n=c+q*h*d;var t=Math.sin(n),m=Math.cos(n);for(n=0;n<=a.length-1;n++)k.x=a[n].x*t,k.y=a[n].y,k.z=a[n].x*m,f.push(k.x,k.y,k.z),l.x=q/b,l.y=n/(a.length-1),g.push(l.x,l.y)}for(q=0;q<b;q++)for(n=0;n<a.length-1;n++)c=n+q*a.length,h=c+a.length,k=c+a.length+1,l=c+1,e.push(c,h,l),e.push(h,k,l);this.setIndex(e);this.addAttribute("position",new y(f,3));this.addAttribute("uv",new y(g,2));this.computeVertexNormals();if(d===2*Math.PI)for(d=
16746 this.attributes.normal.array,e=new p,f=new p,g=new p,c=b*a.length*3,n=q=0;q<a.length;q++,n+=3)e.x=d[n+0],e.y=d[n+1],e.z=d[n+2],f.x=d[c+n+0],f.y=d[c+n+1],f.z=d[c+n+2],g.addVectors(e,f).normalize(),d[n+0]=d[c+n+0]=g.x,d[n+1]=d[c+n+1]=g.y,d[n+2]=d[c+n+2]=g.z}function cc(a,b){N.call(this);this.type="ShapeGeometry";"object"===typeof b&&(console.warn("THREE.ShapeGeometry: Options parameter has been removed."),b=b.curveSegments);this.parameters={shapes:a,curveSegments:b};this.fromBufferGeometry(new dc(a,
16747 b));this.mergeVertices()}function dc(a,b){function c(a){var c,h=e.length/3;a=a.extractPoints(b);var l=a.shape,q=a.holes;if(!1===Ha.isClockWise(l))for(l=l.reverse(),a=0,c=q.length;a<c;a++){var m=q[a];!0===Ha.isClockWise(m)&&(q[a]=m.reverse())}var p=Ha.triangulateShape(l,q);a=0;for(c=q.length;a<c;a++)m=q[a],l=l.concat(m);a=0;for(c=l.length;a<c;a++)m=l[a],e.push(m.x,m.y,0),f.push(0,0,1),g.push(m.x,m.y);a=0;for(c=p.length;a<c;a++)l=p[a],d.push(l[0]+h,l[1]+h,l[2]+h),k+=3}D.call(this);this.type="ShapeBufferGeometry";
16748 this.parameters={shapes:a,curveSegments:b};b=b||12;var d=[],e=[],f=[],g=[],h=0,k=0;if(!1===Array.isArray(a))c(a);else for(var l=0;l<a.length;l++)c(a[l]),this.addGroup(h,k,l),h+=k,k=0;this.setIndex(d);this.addAttribute("position",new y(e,3));this.addAttribute("normal",new y(f,3));this.addAttribute("uv",new y(g,2))}function ec(a,b){D.call(this);this.type="EdgesGeometry";this.parameters={thresholdAngle:b};var c=[];b=Math.cos(R.DEG2RAD*(void 0!==b?b:1));var d=[0,0],e={},f=["a","b","c"];if(a.isBufferGeometry){var g=
16749 new N;g.fromBufferGeometry(a)}else g=a.clone();g.mergeVertices();g.computeFaceNormals();a=g.vertices;g=g.faces;for(var h=0,k=g.length;h<k;h++)for(var l=g[h],q=0;3>q;q++){var n=l[f[q]];var t=l[f[(q+1)%3]];d[0]=Math.min(n,t);d[1]=Math.max(n,t);n=d[0]+","+d[1];void 0===e[n]?e[n]={index1:d[0],index2:d[1],face1:h,face2:void 0}:e[n].face2=h}for(n in e)if(d=e[n],void 0===d.face2||g[d.face1].normal.dot(g[d.face2].normal)<=b)f=a[d.index1],c.push(f.x,f.y,f.z),f=a[d.index2],c.push(f.x,f.y,f.z);this.addAttribute("position",
16750 new y(c,3))}function pb(a,b,c,d,e,f,g,h){N.call(this);this.type="CylinderGeometry";this.parameters={radiusTop:a,radiusBottom:b,height:c,radialSegments:d,heightSegments:e,openEnded:f,thetaStart:g,thetaLength:h};this.fromBufferGeometry(new Sa(a,b,c,d,e,f,g,h));this.mergeVertices()}function Sa(a,b,c,d,e,f,g,h){function k(c){var e,f=new C,k=new p,r=0,v=!0===c?a:b,z=!0===c?1:-1;var y=u;for(e=1;e<=d;e++)n.push(0,w*z,0),t.push(0,z,0),m.push(.5,.5),u++;var A=u;for(e=0;e<=d;e++){var D=e/d*h+g,L=Math.cos(D),
16751 D=Math.sin(D);k.x=v*D;k.y=w*z;k.z=v*L;n.push(k.x,k.y,k.z);t.push(0,z,0);f.x=.5*L+.5;f.y=.5*D*z+.5;m.push(f.x,f.y);u++}for(e=0;e<d;e++)f=y+e,k=A+e,!0===c?q.push(k,k+1,f):q.push(k+1,k,f),r+=3;l.addGroup(x,r,!0===c?1:2);x+=r}D.call(this);this.type="CylinderBufferGeometry";this.parameters={radiusTop:a,radiusBottom:b,height:c,radialSegments:d,heightSegments:e,openEnded:f,thetaStart:g,thetaLength:h};var l=this;a=void 0!==a?a:1;b=void 0!==b?b:1;c=c||1;d=Math.floor(d)||8;e=Math.floor(e)||1;f=void 0!==f?f:
16752 !1;g=void 0!==g?g:0;h=void 0!==h?h:2*Math.PI;var q=[],n=[],t=[],m=[],u=0,v=[],w=c/2,x=0;(function(){var f,k,r=new p,J=new p,y=0,C=(b-a)/c;for(k=0;k<=e;k++){var A=[],D=k/e,E=D*(b-a)+a;for(f=0;f<=d;f++){var H=f/d,L=H*h+g,Y=Math.sin(L),L=Math.cos(L);J.x=E*Y;J.y=-D*c+w;J.z=E*L;n.push(J.x,J.y,J.z);r.set(Y,C,L).normalize();t.push(r.x,r.y,r.z);m.push(H,1-D);A.push(u++)}v.push(A)}for(f=0;f<d;f++)for(k=0;k<e;k++)r=v[k+1][f],J=v[k+1][f+1],C=v[k][f+1],q.push(v[k][f],r,C),q.push(r,J,C),y+=6;l.addGroup(x,y,0);
16753 x+=y})();!1===f&&(0<a&&k(!0),0<b&&k(!1));this.setIndex(q);this.addAttribute("position",new y(n,3));this.addAttribute("normal",new y(t,3));this.addAttribute("uv",new y(m,2))}function Uc(a,b,c,d,e,f,g){pb.call(this,0,a,b,c,d,e,f,g);this.type="ConeGeometry";this.parameters={radius:a,height:b,radialSegments:c,heightSegments:d,openEnded:e,thetaStart:f,thetaLength:g}}function Vc(a,b,c,d,e,f,g){Sa.call(this,0,a,b,c,d,e,f,g);this.type="ConeBufferGeometry";this.parameters={radius:a,height:b,radialSegments:c,
16754 heightSegments:d,openEnded:e,thetaStart:f,thetaLength:g}}function Wc(a,b,c,d){N.call(this);this.type="CircleGeometry";this.parameters={radius:a,segments:b,thetaStart:c,thetaLength:d};this.fromBufferGeometry(new fc(a,b,c,d));this.mergeVertices()}function fc(a,b,c,d){D.call(this);this.type="CircleBufferGeometry";this.parameters={radius:a,segments:b,thetaStart:c,thetaLength:d};a=a||1;b=void 0!==b?Math.max(3,b):8;c=void 0!==c?c:0;d=void 0!==d?d:2*Math.PI;var e=[],f=[],g=[],h=[],k,l=new p,q=new C;f.push(0,
16755 0,0);g.push(0,0,1);h.push(.5,.5);var n=0;for(k=3;n<=b;n++,k+=3){var t=c+n/b*d;l.x=a*Math.cos(t);l.y=a*Math.sin(t);f.push(l.x,l.y,l.z);g.push(0,0,1);q.x=(f[k]/a+1)/2;q.y=(f[k+1]/a+1)/2;h.push(q.x,q.y)}for(k=1;k<=b;k++)e.push(k,k+1,0);this.setIndex(e);this.addAttribute("position",new y(f,3));this.addAttribute("normal",new y(g,3));this.addAttribute("uv",new y(h,2))}function gc(a){Q.call(this);this.type="ShadowMaterial";this.color=new H(0);this.opacity=1;this.transparent=this.lights=!0;this.setValues(a)}
16756 function hc(a){oa.call(this,a);this.type="RawShaderMaterial"}function Ma(a){Q.call(this);this.defines={STANDARD:""};this.type="MeshStandardMaterial";this.color=new H(16777215);this.metalness=this.roughness=.5;this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new H(0);this.emissiveIntensity=1;this.bumpMap=this.emissiveMap=null;this.bumpScale=1;this.normalMap=null;this.normalScale=new C(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=
16757 0;this.envMap=this.alphaMap=this.metalnessMap=this.roughnessMap=null;this.envMapIntensity=1;this.refractionRatio=.98;this.wireframe=!1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.morphNormals=this.morphTargets=this.skinning=!1;this.setValues(a)}function qb(a){Ma.call(this);this.defines={PHYSICAL:""};this.type="MeshPhysicalMaterial";this.reflectivity=.5;this.clearCoatRoughness=this.clearCoat=0;this.setValues(a)}function Ia(a){Q.call(this);this.type="MeshPhongMaterial";
16758 this.color=new H(16777215);this.specular=new H(1118481);this.shininess=30;this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new H(0);this.emissiveIntensity=1;this.bumpMap=this.emissiveMap=null;this.bumpScale=1;this.normalMap=null;this.normalScale=new C(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.envMap=this.alphaMap=this.specularMap=null;this.combine=0;this.reflectivity=1;this.refractionRatio=.98;this.wireframe=
16759 !1;this.wireframeLinewidth=1;this.wireframeLinejoin=this.wireframeLinecap="round";this.morphNormals=this.morphTargets=this.skinning=!1;this.setValues(a)}function rb(a){Ia.call(this);this.defines={TOON:""};this.type="MeshToonMaterial";this.gradientMap=null;this.setValues(a)}function sb(a){Q.call(this);this.type="MeshNormalMaterial";this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalScale=new C(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.wireframe=
16760 !1;this.wireframeLinewidth=1;this.morphNormals=this.morphTargets=this.skinning=this.lights=this.fog=!1;this.setValues(a)}function tb(a){Q.call(this);this.type="MeshLambertMaterial";this.color=new H(16777215);this.lightMap=this.map=null;this.lightMapIntensity=1;this.aoMap=null;this.aoMapIntensity=1;this.emissive=new H(0);this.emissiveIntensity=1;this.envMap=this.alphaMap=this.specularMap=this.emissiveMap=null;this.combine=0;this.reflectivity=1;this.refractionRatio=.98;this.wireframe=!1;this.wireframeLinewidth=
16761 1;this.wireframeLinejoin=this.wireframeLinecap="round";this.morphNormals=this.morphTargets=this.skinning=!1;this.setValues(a)}function ub(a){O.call(this);this.type="LineDashedMaterial";this.scale=1;this.dashSize=3;this.gapSize=1;this.setValues(a)}function Yd(a,b,c){var d=this,e=!1,f=0,g=0,h=void 0;this.onStart=void 0;this.onLoad=a;this.onProgress=b;this.onError=c;this.itemStart=function(a){g++;if(!1===e&&void 0!==d.onStart)d.onStart(a,f,g);e=!0};this.itemEnd=function(a){f++;if(void 0!==d.onProgress)d.onProgress(a,
16762 f,g);if(f===g&&(e=!1,void 0!==d.onLoad))d.onLoad()};this.itemError=function(a){if(void 0!==d.onError)d.onError(a)};this.resolveURL=function(a){return h?h(a):a};this.setURLModifier=function(a){h=a}}function Ja(a){this.manager=void 0!==a?a:wa}function Qe(a){this.manager=void 0!==a?a:wa;this._parser=null}function Zd(a){this.manager=void 0!==a?a:wa;this._parser=null}function Xc(a){this.manager=void 0!==a?a:wa}function $d(a){this.manager=void 0!==a?a:wa}function td(a){this.manager=void 0!==a?a:wa}function ga(a,
16763 b){A.call(this);this.type="Light";this.color=new H(a);this.intensity=void 0!==b?b:1;this.receiveShadow=void 0}function ud(a,b,c){ga.call(this,a,c);this.type="HemisphereLight";this.castShadow=void 0;this.position.copy(A.DefaultUp);this.updateMatrix();this.groundColor=new H(b)}function vb(a){this.camera=a;this.bias=0;this.radius=1;this.mapSize=new C(512,512);this.map=null;this.matrix=new K}function vd(){vb.call(this,new U(50,1,.5,500))}function wd(a,b,c,d,e,f){ga.call(this,a,b);this.type="SpotLight";
16764 this.position.copy(A.DefaultUp);this.updateMatrix();this.target=new A;Object.defineProperty(this,"power",{get:function(){return this.intensity*Math.PI},set:function(a){this.intensity=a/Math.PI}});this.distance=void 0!==c?c:0;this.angle=void 0!==d?d:Math.PI/3;this.penumbra=void 0!==e?e:0;this.decay=void 0!==f?f:1;this.shadow=new vd}function xd(a,b,c,d){ga.call(this,a,b);this.type="PointLight";Object.defineProperty(this,"power",{get:function(){return 4*this.intensity*Math.PI},set:function(a){this.intensity=
16765 a/(4*Math.PI)}});this.distance=void 0!==c?c:0;this.decay=void 0!==d?d:1;this.shadow=new vb(new U(90,1,.5,500))}function yd(){vb.call(this,new Kb(-5,5,5,-5,.5,500))}function zd(a,b){ga.call(this,a,b);this.type="DirectionalLight";this.position.copy(A.DefaultUp);this.updateMatrix();this.target=new A;this.shadow=new yd}function Ad(a,b){ga.call(this,a,b);this.type="AmbientLight";this.castShadow=void 0}function Bd(a,b,c,d){ga.call(this,a,b);this.type="RectAreaLight";this.position.set(0,1,0);this.updateMatrix();
16766 this.width=void 0!==c?c:10;this.height=void 0!==d?d:10}function xa(a,b,c,d){this.parameterPositions=a;this._cachedIndex=0;this.resultBuffer=void 0!==d?d:new b.constructor(c);this.sampleValues=b;this.valueSize=c}function Cd(a,b,c,d){xa.call(this,a,b,c,d);this._offsetNext=this._weightNext=this._offsetPrev=this._weightPrev=-0}function Yc(a,b,c,d){xa.call(this,a,b,c,d)}function Dd(a,b,c,d){xa.call(this,a,b,c,d)}function wb(a,b,c,d){if(void 0===a)throw Error("track name is undefined");if(void 0===b||0===
16767 b.length)throw Error("no keyframes in track named "+a);this.name=a;this.times=T.convertArray(b,this.TimeBufferType);this.values=T.convertArray(c,this.ValueBufferType);this.setInterpolation(d||this.DefaultInterpolation);this.validate();this.optimize()}function ic(a,b,c,d){wb.call(this,a,b,c,d)}function Ed(a,b,c,d){xa.call(this,a,b,c,d)}function Zc(a,b,c,d){wb.call(this,a,b,c,d)}function jc(a,b,c,d){wb.call(this,a,b,c,d)}function Fd(a,b,c,d){wb.call(this,a,b,c,d)}function Gd(a,b,c){wb.call(this,a,b,
16768 c)}function Hd(a,b,c,d){wb.call(this,a,b,c,d)}function xb(a,b,c,d){wb.apply(this,a,b,c,d)}function ka(a,b,c){this.name=a;this.tracks=c;this.duration=void 0!==b?b:-1;this.uuid=R.generateUUID();0>this.duration&&this.resetDuration();this.optimize()}function Id(a){this.manager=void 0!==a?a:wa;this.textures={}}function ae(a){this.manager=void 0!==a?a:wa}function kc(){this.onLoadStart=function(){};this.onLoadProgress=function(){};this.onLoadComplete=function(){}}function be(a){"boolean"===typeof a&&(console.warn("THREE.JSONLoader: showStatus parameter has been removed from constructor."),
16769 a=void 0);this.manager=void 0!==a?a:wa;this.withCredentials=!1}function Re(a){this.manager=void 0!==a?a:wa;this.texturePath=""}function Se(a,b,c,d,e){b=.5*(d-b);e=.5*(e-c);var f=a*a;return(2*c-2*d+b+e)*a*f+(-3*c+3*d-2*b-e)*f+b*a+c}function yb(a,b,c,d){var e=1-a;return e*e*b+2*(1-a)*a*c+a*a*d}function zb(a,b,c,d,e){var f=1-a,g=1-a;return f*f*f*b+3*g*g*a*c+3*(1-a)*a*a*d+a*a*a*e}function S(){this.type="Curve";this.arcLengthDivisions=200}function Ka(a,b){S.call(this);this.type="LineCurve";this.v1=a||
16770 new C;this.v2=b||new C}function Ab(){S.call(this);this.type="CurvePath";this.curves=[];this.autoClose=!1}function Na(a,b,c,d,e,f,g,h){S.call(this);this.type="EllipseCurve";this.aX=a||0;this.aY=b||0;this.xRadius=c||1;this.yRadius=d||1;this.aStartAngle=e||0;this.aEndAngle=f||2*Math.PI;this.aClockwise=g||!1;this.aRotation=h||0}function ab(a){S.call(this);this.type="SplineCurve";this.points=a||[]}function bb(a,b,c,d){S.call(this);this.type="CubicBezierCurve";this.v0=a||new C;this.v1=b||new C;this.v2=
16771 c||new C;this.v3=d||new C}function cb(a,b,c){S.call(this);this.type="QuadraticBezierCurve";this.v0=a||new C;this.v1=b||new C;this.v2=c||new C}function Bb(a){Ab.call(this);this.type="Path";this.currentPoint=new C;a&&this.setFromPoints(a)}function Cb(a){Bb.call(this,a);this.type="Shape";this.holes=[]}function ce(){this.type="ShapePath";this.subPaths=[];this.currentPath=null}function de(a){this.type="Font";this.data=a}function Te(a){this.manager=void 0!==a?a:wa}function ee(a){this.manager=void 0!==a?
16772 a:wa}function Ue(){this.type="StereoCamera";this.aspect=1;this.eyeSep=.064;this.cameraL=new U;this.cameraL.layers.enable(1);this.cameraL.matrixAutoUpdate=!1;this.cameraR=new U;this.cameraR.layers.enable(2);this.cameraR.matrixAutoUpdate=!1}function $c(a,b,c){A.call(this);this.type="CubeCamera";var d=new U(90,1,a,b);d.up.set(0,-1,0);d.lookAt(new p(1,0,0));this.add(d);var e=new U(90,1,a,b);e.up.set(0,-1,0);e.lookAt(new p(-1,0,0));this.add(e);var f=new U(90,1,a,b);f.up.set(0,0,1);f.lookAt(new p(0,1,0));
16773 this.add(f);var g=new U(90,1,a,b);g.up.set(0,0,-1);g.lookAt(new p(0,-1,0));this.add(g);var h=new U(90,1,a,b);h.up.set(0,-1,0);h.lookAt(new p(0,0,1));this.add(h);var k=new U(90,1,a,b);k.up.set(0,-1,0);k.lookAt(new p(0,0,-1));this.add(k);this.renderTarget=new Ib(c,c,{format:1022,magFilter:1006,minFilter:1006});this.renderTarget.texture.name="CubeCamera";this.update=function(a,b){null===this.parent&&this.updateMatrixWorld();var c=this.renderTarget,l=c.texture.generateMipmaps;c.texture.generateMipmaps=
16774 !1;c.activeCubeFace=0;a.render(b,d,c);c.activeCubeFace=1;a.render(b,e,c);c.activeCubeFace=2;a.render(b,f,c);c.activeCubeFace=3;a.render(b,g,c);c.activeCubeFace=4;a.render(b,h,c);c.texture.generateMipmaps=l;c.activeCubeFace=5;a.render(b,k,c);a.setRenderTarget(null)};this.clear=function(a,b,c,d){for(var e=this.renderTarget,f=0;6>f;f++)e.activeCubeFace=f,a.setRenderTarget(e),a.clear(b,c,d);a.setRenderTarget(null)}}function fe(){A.call(this);this.type="AudioListener";this.context=ge.getContext();this.gain=
16775 this.context.createGain();this.gain.connect(this.context.destination);this.filter=null}function lc(a){A.call(this);this.type="Audio";this.context=a.context;this.gain=this.context.createGain();this.gain.connect(a.getInput());this.autoplay=!1;this.buffer=null;this.loop=!1;this.offset=this.startTime=0;this.playbackRate=1;this.isPlaying=!1;this.hasPlaybackControl=!0;this.sourceType="empty";this.filters=[]}function he(a){lc.call(this,a);this.panner=this.context.createPanner();this.panner.connect(this.gain)}
16776 function ie(a,b){this.analyser=a.context.createAnalyser();this.analyser.fftSize=void 0!==b?b:2048;this.data=new Uint8Array(this.analyser.frequencyBinCount);a.getOutput().connect(this.analyser)}function je(a,b,c){this.binding=a;this.valueSize=c;a=Float64Array;switch(b){case "quaternion":b=this._slerp;break;case "string":case "bool":a=Array;b=this._select;break;default:b=this._lerp}this.buffer=new a(4*c);this._mixBufferRegion=b;this.referenceCount=this.useCount=this.cumulativeWeight=0}function Ve(a,
16777 b,c){c=c||na.parseTrackName(b);this._targetGroup=a;this._bindings=a.subscribe_(b,c)}function na(a,b,c){this.path=b;this.parsedPath=c||na.parseTrackName(b);this.node=na.findNode(a,this.parsedPath.nodeName)||a;this.rootNode=a}function We(){this.uuid=R.generateUUID();this._objects=Array.prototype.slice.call(arguments);this.nCachedObjects_=0;var a={};this._indicesByUUID=a;for(var b=0,c=arguments.length;b!==c;++b)a[arguments[b].uuid]=b;this._paths=[];this._parsedPaths=[];this._bindings=[];this._bindingsIndicesByPath=
16778 {};var d=this;this.stats={objects:{get total(){return d._objects.length},get inUse(){return this.total-d.nCachedObjects_}},get bindingsPerObject(){return d._bindings.length}}}function Xe(a,b,c){this._mixer=a;this._clip=b;this._localRoot=c||null;a=b.tracks;b=a.length;c=Array(b);for(var d={endingStart:2400,endingEnd:2400},e=0;e!==b;++e){var f=a[e].createInterpolant(null);c[e]=f;f.settings=d}this._interpolantSettings=d;this._interpolants=c;this._propertyBindings=Array(b);this._weightInterpolant=this._timeScaleInterpolant=
16779 this._byClipCacheIndex=this._cacheIndex=null;this.loop=2201;this._loopCount=-1;this._startTime=null;this.time=0;this._effectiveWeight=this.weight=this._effectiveTimeScale=this.timeScale=1;this.repetitions=Infinity;this.paused=!1;this.enabled=!0;this.clampWhenFinished=!1;this.zeroSlopeAtEnd=this.zeroSlopeAtStart=!0}function Ye(a){this._root=a;this._initMemoryManager();this.time=this._accuIndex=0;this.timeScale=1}function Jd(a,b){"string"===typeof a&&(console.warn("THREE.Uniform: Type parameter is no longer needed."),
16780 a=b);this.value=a}function ke(){D.call(this);this.type="InstancedBufferGeometry";this.maxInstancedCount=void 0}function le(a,b,c,d){this.uuid=R.generateUUID();this.data=a;this.itemSize=b;this.offset=c;this.normalized=!0===d}function mc(a,b){this.uuid=R.generateUUID();this.array=a;this.stride=b;this.count=void 0!==a?a.length/b:0;this.dynamic=!1;this.updateRange={offset:0,count:-1};this.onUploadCallback=function(){};this.version=0}function me(a,b,c){mc.call(this,a,b);this.meshPerAttribute=c||1}function ne(a,
16781 b,c){P.call(this,a,b);this.meshPerAttribute=c||1}function Ze(a,b,c,d){this.ray=new lb(a,b);this.near=c||0;this.far=d||Infinity;this.params={Mesh:{},Line:{},LOD:{},Points:{threshold:1},Sprite:{}};Object.defineProperties(this.params,{PointCloud:{get:function(){console.warn("THREE.Raycaster: params.PointCloud has been renamed to params.Points.");return this.Points}}})}function $e(a,b){return a.distance-b.distance}function oe(a,b,c,d){if(!1!==a.visible&&(a.raycast(b,c),!0===d)){a=a.children;d=0;for(var e=
16782 a.length;d<e;d++)oe(a[d],b,c,!0)}}function af(a){this.autoStart=void 0!==a?a:!0;this.elapsedTime=this.oldTime=this.startTime=0;this.running=!1}function bf(a,b,c){this.radius=void 0!==a?a:1;this.phi=void 0!==b?b:0;this.theta=void 0!==c?c:0;return this}function cf(a,b,c){this.radius=void 0!==a?a:1;this.theta=void 0!==b?b:0;this.y=void 0!==c?c:0;return this}function ad(a){A.call(this);this.material=a;this.render=function(){}}function bd(a,b,c,d){this.object=a;this.size=void 0!==b?b:1;a=void 0!==c?c:
16783 16711680;d=void 0!==d?d:1;b=0;(c=this.object.geometry)&&c.isGeometry?b=3*c.faces.length:c&&c.isBufferGeometry&&(b=c.attributes.normal.count);c=new D;b=new y(6*b,3);c.addAttribute("position",b);ca.call(this,c,new O({color:a,linewidth:d}));this.matrixAutoUpdate=!1;this.update()}function nc(a,b){A.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.color=b;a=new D;b=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(var c=0,
16784 d=1;32>c;c++,d++){var e=c/32*Math.PI*2,f=d/32*Math.PI*2;b.push(Math.cos(e),Math.sin(e),1,Math.cos(f),Math.sin(f),1)}a.addAttribute("position",new y(b,3));b=new O({fog:!1});this.cone=new ca(a,b);this.add(this.cone);this.update()}function df(a){var b=[];a&&a.isBone&&b.push(a);for(var c=0;c<a.children.length;c++)b.push.apply(b,df(a.children[c]));return b}function oc(a){for(var b=df(a),c=new D,d=[],e=[],f=new H(0,0,1),g=new H(0,1,0),h=0;h<b.length;h++){var k=b[h];k.parent&&k.parent.isBone&&(d.push(0,
16785 0,0),d.push(0,0,0),e.push(f.r,f.g,f.b),e.push(g.r,g.g,g.b))}c.addAttribute("position",new y(d,3));c.addAttribute("color",new y(e,3));d=new O({vertexColors:2,depthTest:!1,depthWrite:!1,transparent:!0});ca.call(this,c,d);this.root=a;this.bones=b;this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1}function pc(a,b,c){this.light=a;this.light.updateMatrixWorld();this.color=c;a=new ob(b,4,2);b=new va({wireframe:!0,fog:!1});pa.call(this,a,b);this.matrix=this.light.matrixWorld;this.matrixAutoUpdate=!1;this.update()}
16786 function qc(a,b){A.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.color=b;a=new O({fog:!1});b=new D;b.addAttribute("position",new P(new Float32Array(15),3));this.line=new ma(b,a);this.add(this.line);this.update()}function rc(a,b,c){A.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.color=c;a=new nb(b);a.rotateY(.5*Math.PI);this.material=new va({wireframe:!0,fog:!1});void 0===
16787 this.color&&(this.material.vertexColors=2);b=a.getAttribute("position");b=new Float32Array(3*b.count);a.addAttribute("color",new P(b,3));this.add(new pa(a,this.material));this.update()}function cd(a,b,c,d){a=a||10;b=b||10;c=new H(void 0!==c?c:4473924);d=new H(void 0!==d?d:8947848);var e=b/2,f=a/b,g=a/2;a=[];for(var h=[],k=0,l=0,q=-g;k<=b;k++,q+=f){a.push(-g,0,q,g,0,q);a.push(q,0,-g,q,0,g);var n=k===e?c:d;n.toArray(h,l);l+=3;n.toArray(h,l);l+=3;n.toArray(h,l);l+=3;n.toArray(h,l);l+=3}b=new D;b.addAttribute("position",
16788 new y(a,3));b.addAttribute("color",new y(h,3));c=new O({vertexColors:2});ca.call(this,b,c)}function Kd(a,b,c,d,e,f){a=a||10;b=b||16;c=c||8;d=d||64;e=new H(void 0!==e?e:4473924);f=new H(void 0!==f?f:8947848);var g=[],h=[],k;for(k=0;k<=b;k++){var l=k/b*2*Math.PI;var q=Math.sin(l)*a;l=Math.cos(l)*a;g.push(0,0,0);g.push(q,0,l);var n=k&1?e:f;h.push(n.r,n.g,n.b);h.push(n.r,n.g,n.b)}for(k=0;k<=c;k++){n=k&1?e:f;var t=a-a/c*k;for(b=0;b<d;b++)l=b/d*2*Math.PI,q=Math.sin(l)*t,l=Math.cos(l)*t,g.push(q,0,l),h.push(n.r,
16789 n.g,n.b),l=(b+1)/d*2*Math.PI,q=Math.sin(l)*t,l=Math.cos(l)*t,g.push(q,0,l),h.push(n.r,n.g,n.b)}a=new D;a.addAttribute("position",new y(g,3));a.addAttribute("color",new y(h,3));g=new O({vertexColors:2});ca.call(this,a,g)}function dd(a,b,c,d){this.object=a;this.size=void 0!==b?b:1;a=void 0!==c?c:16776960;d=void 0!==d?d:1;b=0;(c=this.object.geometry)&&c.isGeometry?b=c.faces.length:console.warn("THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.");c=new D;
16790 b=new y(6*b,3);c.addAttribute("position",b);ca.call(this,c,new O({color:a,linewidth:d}));this.matrixAutoUpdate=!1;this.update()}function sc(a,b,c){A.call(this);this.light=a;this.light.updateMatrixWorld();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.color=c;void 0===b&&(b=1);a=new D;a.addAttribute("position",new y([-b,b,0,b,b,0,b,-b,0,-b,-b,0,-b,b,0],3));b=new O({fog:!1});this.lightPlane=new ma(a,b);this.add(this.lightPlane);a=new D;a.addAttribute("position",new y([0,0,0,0,0,1],3));this.targetLine=
16791 new ma(a,b);this.add(this.targetLine);this.update()}function ed(a){function b(a,b,d){c(a,d);c(b,d)}function c(a,b){f.push(0,0,0);g.push(b.r,b.g,b.b);void 0===h[a]&&(h[a]=[]);h[a].push(f.length/3-1)}var d=new D,e=new O({color:16777215,vertexColors:1}),f=[],g=[],h={},k=new H(16755200),l=new H(16711680),q=new H(43775),n=new H(16777215),t=new H(3355443);b("n1","n2",k);b("n2","n4",k);b("n4","n3",k);b("n3","n1",k);b("f1","f2",k);b("f2","f4",k);b("f4","f3",k);b("f3","f1",k);b("n1","f1",k);b("n2","f2",k);
16792 b("n3","f3",k);b("n4","f4",k);b("p","n1",l);b("p","n2",l);b("p","n3",l);b("p","n4",l);b("u1","u2",q);b("u2","u3",q);b("u3","u1",q);b("c","t",n);b("p","c",t);b("cn1","cn2",t);b("cn3","cn4",t);b("cf1","cf2",t);b("cf3","cf4",t);d.addAttribute("position",new y(f,3));d.addAttribute("color",new y(g,3));ca.call(this,d,e);this.camera=a;this.camera.updateProjectionMatrix&&this.camera.updateProjectionMatrix();this.matrix=a.matrixWorld;this.matrixAutoUpdate=!1;this.pointMap=h;this.update()}function Db(a,b){this.object=
16793 a;void 0===b&&(b=16776960);a=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]);var c=new Float32Array(24),d=new D;d.setIndex(new P(a,1));d.addAttribute("position",new P(c,3));ca.call(this,d,new O({color:b}));this.matrixAutoUpdate=!1;this.update()}function fd(a,b){this.type="Box3Helper";this.box=a;a=void 0!==b?b:16776960;b=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]);var c=new D;c.setIndex(new P(b,1));c.addAttribute("position",new y([1,1,1,-1,1,1,-1,-1,1,1,-1,
16794 1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1],3));ca.call(this,c,new O({color:a}));this.geometry.computeBoundingSphere()}function gd(a,b,c){this.type="PlaneHelper";this.plane=a;this.size=void 0===b?1:b;a=void 0!==c?c:16776960;b=new D;b.addAttribute("position",new y([1,-1,1,-1,1,1,-1,-1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,0,0,1,0,0,0],3));b.computeBoundingSphere();ma.call(this,b,new O({color:a}));b=new D;b.addAttribute("position",new y([1,1,1,-1,1,1,-1,-1,1,1,1,1,-1,-1,1,1,-1,1],3));b.computeBoundingSphere();
16795 this.add(new pa(b,new va({color:a,opacity:.2,transparent:!0,depthWrite:!1})))}function Eb(a,b,c,d,e,f){A.call(this);void 0===d&&(d=16776960);void 0===c&&(c=1);void 0===e&&(e=.2*c);void 0===f&&(f=.2*e);void 0===Ld&&(Ld=new D,Ld.addAttribute("position",new y([0,0,0,0,1,0],3)),pe=new Sa(0,.5,1,5,1),pe.translate(0,-.5,0));this.position.copy(b);this.line=new ma(Ld,new O({color:d}));this.line.matrixAutoUpdate=!1;this.add(this.line);this.cone=new pa(pe,new va({color:d}));this.cone.matrixAutoUpdate=!1;this.add(this.cone);
16796 this.setDirection(a);this.setLength(c,e,f)}function hd(a){a=a||1;var b=[0,0,0,a,0,0,0,0,0,0,a,0,0,0,0,0,0,a];a=new D;a.addAttribute("position",new y(b,3));a.addAttribute("color",new y([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],3));b=new O({vertexColors:2});ca.call(this,a,b)}function qe(){var a=0,b=0,c=0,d=0;return{initCatmullRom:function(e,f,g,h,k){e=k*(g-e);h=k*(h-f);a=f;b=e;c=-3*f+3*g-2*e-h;d=2*f-2*g+e+h},initNonuniformCatmullRom:function(e,f,g,h,k,l,q){e=((f-e)/k-(g-e)/(k+l)+(g-f)/l)*l;h=((g-f)/
16797 l-(h-f)/(l+q)+(h-g)/q)*l;a=f;b=e;c=-3*f+3*g-2*e-h;d=2*f-2*g+e+h},calc:function(e){var f=e*e;return a+b*e+c*f+d*f*e}}}function ya(a,b,c,d){S.call(this);this.type="CatmullRomCurve3";this.points=a||[];this.closed=b||!1;this.curveType=c||"centripetal";this.tension=d||.5}function Fb(a,b,c,d){S.call(this);this.type="CubicBezierCurve3";this.v0=a||new p;this.v1=b||new p;this.v2=c||new p;this.v3=d||new p}function Gb(a,b,c){S.call(this);this.type="QuadraticBezierCurve3";this.v0=a||new p;this.v1=b||new p;this.v2=
16798 c||new p}function db(a,b){S.call(this);this.type="LineCurve3";this.v1=a||new p;this.v2=b||new p}function id(a,b,c,d,e,f){Na.call(this,a,b,c,c,d,e,f);this.type="ArcCurve"}function ef(a){console.warn("THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.");ya.call(this,a);this.type="catmullrom";this.closed=!0}function ff(a){console.warn("THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.");ya.call(this,a);this.type="catmullrom"}function re(a){console.warn("THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.");
16799 ya.call(this,a);this.type="catmullrom"}void 0===Number.EPSILON&&(Number.EPSILON=Math.pow(2,-52));void 0===Number.isInteger&&(Number.isInteger=function(a){return"number"===typeof a&&isFinite(a)&&Math.floor(a)===a});void 0===Math.sign&&(Math.sign=function(a){return 0>a?-1:0<a?1:+a});!1==="name"in Function.prototype&&Object.defineProperty(Function.prototype,"name",{get:function(){return this.toString().match(/^\s*function\s*([^\(\s]*)/)[1]}});void 0===Object.assign&&function(){Object.assign=function(a){if(void 0===
16800 a||null===a)throw new TypeError("Cannot convert undefined or null to object");for(var b=Object(a),c=1;c<arguments.length;c++){var d=arguments[c];if(void 0!==d&&null!==d)for(var e in d)Object.prototype.hasOwnProperty.call(d,e)&&(b[e]=d[e])}return b}}();Object.assign(ja.prototype,{addEventListener:function(a,b){void 0===this._listeners&&(this._listeners={});var c=this._listeners;void 0===c[a]&&(c[a]=[]);-1===c[a].indexOf(b)&&c[a].push(b)},hasEventListener:function(a,b){if(void 0===this._listeners)return!1;
16801 var c=this._listeners;return void 0!==c[a]&&-1!==c[a].indexOf(b)},removeEventListener:function(a,b){void 0!==this._listeners&&(a=this._listeners[a],void 0!==a&&(b=a.indexOf(b),-1!==b&&a.splice(b,1)))},dispatchEvent:function(a){if(void 0!==this._listeners){var b=this._listeners[a.type];if(void 0!==b){a.target=this;for(var b=b.slice(0),c=0,d=b.length;c<d;c++)b[c].call(this,a)}}}});var R={DEG2RAD:Math.PI/180,RAD2DEG:180/Math.PI,generateUUID:function(){var a="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),
16802 b=0,c;return function(){for(var d="",e=0;36>e;e++)8===e||13===e||18===e||23===e?d+="-":14===e?d+="4":(2>=b&&(b=33554432+16777216*Math.random()|0),c=b&15,b>>=4,d+=a[19===e?c&3|8:c]);return d}}(),clamp:function(a,b,c){return Math.max(b,Math.min(c,a))},euclideanModulo:function(a,b){return(a%b+b)%b},mapLinear:function(a,b,c,d,e){return d+(a-b)*(e-d)/(c-b)},lerp:function(a,b,c){return(1-c)*a+c*b},smoothstep:function(a,b,c){if(a<=b)return 0;if(a>=c)return 1;a=(a-b)/(c-b);return a*a*(3-2*a)},smootherstep:function(a,
16803 b,c){if(a<=b)return 0;if(a>=c)return 1;a=(a-b)/(c-b);return a*a*a*(a*(6*a-15)+10)},randInt:function(a,b){return a+Math.floor(Math.random()*(b-a+1))},randFloat:function(a,b){return a+Math.random()*(b-a)},randFloatSpread:function(a){return a*(.5-Math.random())},degToRad:function(a){return a*R.DEG2RAD},radToDeg:function(a){return a*R.RAD2DEG},isPowerOfTwo:function(a){return 0===(a&a-1)&&0!==a},ceilPowerOfTwo:function(a){return Math.pow(2,Math.ceil(Math.log(a)/Math.LN2))},floorPowerOfTwo:function(a){return Math.pow(2,
16804 Math.floor(Math.log(a)/Math.LN2))}};Object.defineProperties(C.prototype,{width:{get:function(){return this.x},set:function(a){this.x=a}},height:{get:function(){return this.y},set:function(a){this.y=a}}});Object.assign(C.prototype,{isVector2:!0,set:function(a,b){this.x=a;this.y=b;return this},setScalar:function(a){this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;
16805 default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y)},copy:function(a){this.x=a.x;this.y=a.y;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b);this.x+=a.x;this.y+=a.y;return this},
16806 addScalar:function(a){this.x+=a;this.y+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;return this},subScalar:function(a){this.x-=a;this.y-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;
16807 return this},multiply:function(a){this.x*=a.x;this.y*=a.y;return this},multiplyScalar:function(a){this.x*=a;this.y*=a;return this},divide:function(a){this.x/=a.x;this.y/=a.y;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},applyMatrix3:function(a){var b=this.x,c=this.y;a=a.elements;this.x=a[0]*b+a[3]*c+a[6];this.y=a[1]*b+a[4]*c+a[7];return this},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=
16808 Math.max(this.y,a.y);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));return this},clampScalar:function(){var a=new C,b=new C;return function(c,d){a.set(c,c);b.set(d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.divideScalar(c||1).multiplyScalar(Math.max(a,Math.min(b,c)))},floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);return this},ceil:function(){this.x=Math.ceil(this.x);
16809 this.y=Math.ceil(this.y);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);return this},negate:function(){this.x=-this.x;this.y=-this.y;return this},dot:function(a){return this.x*a.x+this.y*a.y},lengthSq:function(){return this.x*this.x+this.y*this.y},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},manhattanLength:function(){return Math.abs(this.x)+
16810 Math.abs(this.y)},normalize:function(){return this.divideScalar(this.length()||1)},angle:function(){var a=Math.atan2(this.y,this.x);0>a&&(a+=2*Math.PI);return a},distanceTo:function(a){return Math.sqrt(this.distanceToSquared(a))},distanceToSquared:function(a){var b=this.x-a.x;a=this.y-a.y;return b*b+a*a},manhattanDistanceTo:function(a){return Math.abs(this.x-a.x)+Math.abs(this.y-a.y)},setLength:function(a){return this.normalize().multiplyScalar(a)},lerp:function(a,b){this.x+=(a.x-this.x)*b;this.y+=
16811 (a.y-this.y)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},equals:function(a){return a.x===this.x&&a.y===this.y},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;return a},fromBufferAttribute:function(a,b,c){void 0!==c&&console.warn("THREE.Vector2: offset has been removed from .fromBufferAttribute().");this.x=a.getX(b);this.y=a.getY(b);
16812 return this},rotateAround:function(a,b){var c=Math.cos(b);b=Math.sin(b);var d=this.x-a.x,e=this.y-a.y;this.x=d*c-e*b+a.x;this.y=d*b+e*c+a.y;return this}});Object.assign(K.prototype,{isMatrix4:!0,set:function(a,b,c,d,e,f,g,h,k,l,q,n,t,m,p,v){var r=this.elements;r[0]=a;r[4]=b;r[8]=c;r[12]=d;r[1]=e;r[5]=f;r[9]=g;r[13]=h;r[2]=k;r[6]=l;r[10]=q;r[14]=n;r[3]=t;r[7]=m;r[11]=p;r[15]=v;return this},identity:function(){this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return this},clone:function(){return(new K).fromArray(this.elements)},
16813 copy:function(a){var b=this.elements;a=a.elements;b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];b[5]=a[5];b[6]=a[6];b[7]=a[7];b[8]=a[8];b[9]=a[9];b[10]=a[10];b[11]=a[11];b[12]=a[12];b[13]=a[13];b[14]=a[14];b[15]=a[15];return this},copyPosition:function(a){var b=this.elements;a=a.elements;b[12]=a[12];b[13]=a[13];b[14]=a[14];return this},extractBasis:function(a,b,c){a.setFromMatrixColumn(this,0);b.setFromMatrixColumn(this,1);c.setFromMatrixColumn(this,2);return this},makeBasis:function(a,b,c){this.set(a.x,
16814 b.x,c.x,0,a.y,b.y,c.y,0,a.z,b.z,c.z,0,0,0,0,1);return this},extractRotation:function(){var a=new p;return function(b){var c=this.elements,d=b.elements,e=1/a.setFromMatrixColumn(b,0).length(),f=1/a.setFromMatrixColumn(b,1).length();b=1/a.setFromMatrixColumn(b,2).length();c[0]=d[0]*e;c[1]=d[1]*e;c[2]=d[2]*e;c[4]=d[4]*f;c[5]=d[5]*f;c[6]=d[6]*f;c[8]=d[8]*b;c[9]=d[9]*b;c[10]=d[10]*b;return this}}(),makeRotationFromEuler:function(a){a&&a.isEuler||console.error("THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");
16815 var b=this.elements,c=a.x,d=a.y,e=a.z,f=Math.cos(c),c=Math.sin(c),g=Math.cos(d),d=Math.sin(d),h=Math.cos(e),e=Math.sin(e);if("XYZ"===a.order){var k=f*h;var l=f*e;var q=c*h;a=c*e;b[0]=g*h;b[4]=-g*e;b[8]=d;b[1]=l+q*d;b[5]=k-a*d;b[9]=-c*g;b[2]=a-k*d;b[6]=q+l*d;b[10]=f*g}else"YXZ"===a.order?(k=g*h,l=g*e,q=d*h,a=d*e,b[0]=k+a*c,b[4]=q*c-l,b[8]=f*d,b[1]=f*e,b[5]=f*h,b[9]=-c,b[2]=l*c-q,b[6]=a+k*c,b[10]=f*g):"ZXY"===a.order?(k=g*h,l=g*e,q=d*h,a=d*e,b[0]=k-a*c,b[4]=-f*e,b[8]=q+l*c,b[1]=l+q*c,b[5]=f*h,b[9]=
16816 a-k*c,b[2]=-f*d,b[6]=c,b[10]=f*g):"ZYX"===a.order?(k=f*h,l=f*e,q=c*h,a=c*e,b[0]=g*h,b[4]=q*d-l,b[8]=k*d+a,b[1]=g*e,b[5]=a*d+k,b[9]=l*d-q,b[2]=-d,b[6]=c*g,b[10]=f*g):"YZX"===a.order?(k=f*g,l=f*d,q=c*g,a=c*d,b[0]=g*h,b[4]=a-k*e,b[8]=q*e+l,b[1]=e,b[5]=f*h,b[9]=-c*h,b[2]=-d*h,b[6]=l*e+q,b[10]=k-a*e):"XZY"===a.order&&(k=f*g,l=f*d,q=c*g,a=c*d,b[0]=g*h,b[4]=-e,b[8]=d*h,b[1]=k*e+a,b[5]=f*h,b[9]=l*e-q,b[2]=q*e-l,b[6]=c*h,b[10]=a*e+k);b[3]=0;b[7]=0;b[11]=0;b[12]=0;b[13]=0;b[14]=0;b[15]=1;return this},makeRotationFromQuaternion:function(a){var b=
16817 this.elements,c=a._x,d=a._y,e=a._z,f=a._w,g=c+c,h=d+d,k=e+e;a=c*g;var l=c*h,c=c*k,q=d*h,d=d*k,e=e*k,g=f*g,h=f*h,f=f*k;b[0]=1-(q+e);b[4]=l-f;b[8]=c+h;b[1]=l+f;b[5]=1-(a+e);b[9]=d-g;b[2]=c-h;b[6]=d+g;b[10]=1-(a+q);b[3]=0;b[7]=0;b[11]=0;b[12]=0;b[13]=0;b[14]=0;b[15]=1;return this},lookAt:function(){var a=new p,b=new p,c=new p;return function(d,e,f){var g=this.elements;c.subVectors(d,e);0===c.lengthSq()&&(c.z=1);c.normalize();a.crossVectors(f,c);0===a.lengthSq()&&(1===Math.abs(f.z)?c.x+=1E-4:c.z+=1E-4,
16818 c.normalize(),a.crossVectors(f,c));a.normalize();b.crossVectors(c,a);g[0]=a.x;g[4]=b.x;g[8]=c.x;g[1]=a.y;g[5]=b.y;g[9]=c.y;g[2]=a.z;g[6]=b.z;g[10]=c.z;return this}}(),multiply:function(a,b){return void 0!==b?(console.warn("THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead."),this.multiplyMatrices(a,b)):this.multiplyMatrices(this,a)},premultiply:function(a){return this.multiplyMatrices(a,this)},multiplyMatrices:function(a,b){var c=a.elements,d=b.elements;
16819 b=this.elements;a=c[0];var e=c[4],f=c[8],g=c[12],h=c[1],k=c[5],l=c[9],q=c[13],n=c[2],m=c[6],r=c[10],p=c[14],v=c[3],w=c[7],x=c[11],c=c[15],z=d[0],I=d[4],B=d[8],J=d[12],y=d[1],C=d[5],A=d[9],D=d[13],E=d[2],H=d[6],L=d[10],Y=d[14],N=d[3],M=d[7],V=d[11],d=d[15];b[0]=a*z+e*y+f*E+g*N;b[4]=a*I+e*C+f*H+g*M;b[8]=a*B+e*A+f*L+g*V;b[12]=a*J+e*D+f*Y+g*d;b[1]=h*z+k*y+l*E+q*N;b[5]=h*I+k*C+l*H+q*M;b[9]=h*B+k*A+l*L+q*V;b[13]=h*J+k*D+l*Y+q*d;b[2]=n*z+m*y+r*E+p*N;b[6]=n*I+m*C+r*H+p*M;b[10]=n*B+m*A+r*L+p*V;b[14]=n*J+m*
16820 D+r*Y+p*d;b[3]=v*z+w*y+x*E+c*N;b[7]=v*I+w*C+x*H+c*M;b[11]=v*B+w*A+x*L+c*V;b[15]=v*J+w*D+x*Y+c*d;return this},multiplyScalar:function(a){var b=this.elements;b[0]*=a;b[4]*=a;b[8]*=a;b[12]*=a;b[1]*=a;b[5]*=a;b[9]*=a;b[13]*=a;b[2]*=a;b[6]*=a;b[10]*=a;b[14]*=a;b[3]*=a;b[7]*=a;b[11]*=a;b[15]*=a;return this},applyToBufferAttribute:function(){var a=new p;return function(b){for(var c=0,d=b.count;c<d;c++)a.x=b.getX(c),a.y=b.getY(c),a.z=b.getZ(c),a.applyMatrix4(this),b.setXYZ(c,a.x,a.y,a.z);return b}}(),determinant:function(){var a=
16821 this.elements,b=a[0],c=a[4],d=a[8],e=a[12],f=a[1],g=a[5],h=a[9],k=a[13],l=a[2],q=a[6],n=a[10],m=a[14];return a[3]*(+e*h*q-d*k*q-e*g*n+c*k*n+d*g*m-c*h*m)+a[7]*(+b*h*m-b*k*n+e*f*n-d*f*m+d*k*l-e*h*l)+a[11]*(+b*k*q-b*g*m-e*f*q+c*f*m+e*g*l-c*k*l)+a[15]*(-d*g*l-b*h*q+b*g*n+d*f*q-c*f*n+c*h*l)},transpose:function(){var a=this.elements;var b=a[1];a[1]=a[4];a[4]=b;b=a[2];a[2]=a[8];a[8]=b;b=a[6];a[6]=a[9];a[9]=b;b=a[3];a[3]=a[12];a[12]=b;b=a[7];a[7]=a[13];a[13]=b;b=a[11];a[11]=a[14];a[14]=b;return this},setPosition:function(a){var b=
16822 this.elements;b[12]=a.x;b[13]=a.y;b[14]=a.z;return this},getInverse:function(a,b){var c=this.elements,d=a.elements;a=d[0];var e=d[1],f=d[2],g=d[3],h=d[4],k=d[5],l=d[6],q=d[7],n=d[8],m=d[9],r=d[10],p=d[11],v=d[12],w=d[13],x=d[14],d=d[15],z=m*x*q-w*r*q+w*l*p-k*x*p-m*l*d+k*r*d,I=v*r*q-n*x*q-v*l*p+h*x*p+n*l*d-h*r*d,B=n*w*q-v*m*q+v*k*p-h*w*p-n*k*d+h*m*d,J=v*m*l-n*w*l-v*k*r+h*w*r+n*k*x-h*m*x,y=a*z+e*I+f*B+g*J;if(0===y){if(!0===b)throw Error("THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0");
16823 console.warn("THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0");return this.identity()}b=1/y;c[0]=z*b;c[1]=(w*r*g-m*x*g-w*f*p+e*x*p+m*f*d-e*r*d)*b;c[2]=(k*x*g-w*l*g+w*f*q-e*x*q-k*f*d+e*l*d)*b;c[3]=(m*l*g-k*r*g-m*f*q+e*r*q+k*f*p-e*l*p)*b;c[4]=I*b;c[5]=(n*x*g-v*r*g+v*f*p-a*x*p-n*f*d+a*r*d)*b;c[6]=(v*l*g-h*x*g-v*f*q+a*x*q+h*f*d-a*l*d)*b;c[7]=(h*r*g-n*l*g+n*f*q-a*r*q-h*f*p+a*l*p)*b;c[8]=B*b;c[9]=(v*m*g-n*w*g-v*e*p+a*w*p+n*e*d-a*m*d)*b;c[10]=(h*w*g-v*k*g+v*e*q-a*w*q-h*e*d+a*k*d)*b;c[11]=
16824 (n*k*g-h*m*g-n*e*q+a*m*q+h*e*p-a*k*p)*b;c[12]=J*b;c[13]=(n*w*f-v*m*f+v*e*r-a*w*r-n*e*x+a*m*x)*b;c[14]=(v*k*f-h*w*f-v*e*l+a*w*l+h*e*x-a*k*x)*b;c[15]=(h*m*f-n*k*f+n*e*l-a*m*l-h*e*r+a*k*r)*b;return this},scale:function(a){var b=this.elements,c=a.x,d=a.y;a=a.z;b[0]*=c;b[4]*=d;b[8]*=a;b[1]*=c;b[5]*=d;b[9]*=a;b[2]*=c;b[6]*=d;b[10]*=a;b[3]*=c;b[7]*=d;b[11]*=a;return this},getMaxScaleOnAxis:function(){var a=this.elements;return Math.sqrt(Math.max(a[0]*a[0]+a[1]*a[1]+a[2]*a[2],a[4]*a[4]+a[5]*a[5]+a[6]*a[6],
16825 a[8]*a[8]+a[9]*a[9]+a[10]*a[10]))},makeTranslation:function(a,b,c){this.set(1,0,0,a,0,1,0,b,0,0,1,c,0,0,0,1);return this},makeRotationX:function(a){var b=Math.cos(a);a=Math.sin(a);this.set(1,0,0,0,0,b,-a,0,0,a,b,0,0,0,0,1);return this},makeRotationY:function(a){var b=Math.cos(a);a=Math.sin(a);this.set(b,0,a,0,0,1,0,0,-a,0,b,0,0,0,0,1);return this},makeRotationZ:function(a){var b=Math.cos(a);a=Math.sin(a);this.set(b,-a,0,0,a,b,0,0,0,0,1,0,0,0,0,1);return this},makeRotationAxis:function(a,b){var c=
16826 Math.cos(b);b=Math.sin(b);var d=1-c,e=a.x,f=a.y;a=a.z;var g=d*e,h=d*f;this.set(g*e+c,g*f-b*a,g*a+b*f,0,g*f+b*a,h*f+c,h*a-b*e,0,g*a-b*f,h*a+b*e,d*a*a+c,0,0,0,0,1);return this},makeScale:function(a,b,c){this.set(a,0,0,0,0,b,0,0,0,0,c,0,0,0,0,1);return this},makeShear:function(a,b,c){this.set(1,b,c,0,a,1,c,0,a,b,1,0,0,0,0,1);return this},compose:function(a,b,c){this.makeRotationFromQuaternion(b);this.scale(c);this.setPosition(a);return this},decompose:function(){var a=new p,b=new K;return function(c,
16827 d,e){var f=this.elements,g=a.set(f[0],f[1],f[2]).length(),h=a.set(f[4],f[5],f[6]).length(),k=a.set(f[8],f[9],f[10]).length();0>this.determinant()&&(g=-g);c.x=f[12];c.y=f[13];c.z=f[14];b.copy(this);c=1/g;var f=1/h,l=1/k;b.elements[0]*=c;b.elements[1]*=c;b.elements[2]*=c;b.elements[4]*=f;b.elements[5]*=f;b.elements[6]*=f;b.elements[8]*=l;b.elements[9]*=l;b.elements[10]*=l;d.setFromRotationMatrix(b);e.x=g;e.y=h;e.z=k;return this}}(),makePerspective:function(a,b,c,d,e,f){void 0===f&&console.warn("THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.");
16828 var g=this.elements;g[0]=2*e/(b-a);g[4]=0;g[8]=(b+a)/(b-a);g[12]=0;g[1]=0;g[5]=2*e/(c-d);g[9]=(c+d)/(c-d);g[13]=0;g[2]=0;g[6]=0;g[10]=-(f+e)/(f-e);g[14]=-2*f*e/(f-e);g[3]=0;g[7]=0;g[11]=-1;g[15]=0;return this},makeOrthographic:function(a,b,c,d,e,f){var g=this.elements,h=1/(b-a),k=1/(c-d),l=1/(f-e);g[0]=2*h;g[4]=0;g[8]=0;g[12]=-((b+a)*h);g[1]=0;g[5]=2*k;g[9]=0;g[13]=-((c+d)*k);g[2]=0;g[6]=0;g[10]=-2*l;g[14]=-((f+e)*l);g[3]=0;g[7]=0;g[11]=0;g[15]=1;return this},equals:function(a){var b=this.elements;
16829 a=a.elements;for(var c=0;16>c;c++)if(b[c]!==a[c])return!1;return!0},fromArray:function(a,b){void 0===b&&(b=0);for(var c=0;16>c;c++)this.elements[c]=a[c+b];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);var c=this.elements;a[b]=c[0];a[b+1]=c[1];a[b+2]=c[2];a[b+3]=c[3];a[b+4]=c[4];a[b+5]=c[5];a[b+6]=c[6];a[b+7]=c[7];a[b+8]=c[8];a[b+9]=c[9];a[b+10]=c[10];a[b+11]=c[11];a[b+12]=c[12];a[b+13]=c[13];a[b+14]=c[14];a[b+15]=c[15];return a}});Object.assign(Z,{slerp:function(a,b,c,d){return c.copy(a).slerp(b,
16830 d)},slerpFlat:function(a,b,c,d,e,f,g){var h=c[d+0],k=c[d+1],l=c[d+2];c=c[d+3];d=e[f+0];var q=e[f+1],n=e[f+2];e=e[f+3];if(c!==e||h!==d||k!==q||l!==n){f=1-g;var m=h*d+k*q+l*n+c*e,r=0<=m?1:-1,p=1-m*m;p>Number.EPSILON&&(p=Math.sqrt(p),m=Math.atan2(p,m*r),f=Math.sin(f*m)/p,g=Math.sin(g*m)/p);r*=g;h=h*f+d*r;k=k*f+q*r;l=l*f+n*r;c=c*f+e*r;f===1-g&&(g=1/Math.sqrt(h*h+k*k+l*l+c*c),h*=g,k*=g,l*=g,c*=g)}a[b]=h;a[b+1]=k;a[b+2]=l;a[b+3]=c}});Object.defineProperties(Z.prototype,{x:{get:function(){return this._x},
16831 set:function(a){this._x=a;this.onChangeCallback()}},y:{get:function(){return this._y},set:function(a){this._y=a;this.onChangeCallback()}},z:{get:function(){return this._z},set:function(a){this._z=a;this.onChangeCallback()}},w:{get:function(){return this._w},set:function(a){this._w=a;this.onChangeCallback()}}});Object.assign(Z.prototype,{set:function(a,b,c,d){this._x=a;this._y=b;this._z=c;this._w=d;this.onChangeCallback();return this},clone:function(){return new this.constructor(this._x,this._y,this._z,
16832 this._w)},copy:function(a){this._x=a.x;this._y=a.y;this._z=a.z;this._w=a.w;this.onChangeCallback();return this},setFromEuler:function(a,b){if(!a||!a.isEuler)throw Error("THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.");var c=a._x,d=a._y,e=a._z;a=a.order;var f=Math.cos,g=Math.sin,h=f(c/2),k=f(d/2),f=f(e/2),c=g(c/2),d=g(d/2),e=g(e/2);"XYZ"===a?(this._x=c*k*f+h*d*e,this._y=h*d*f-c*k*e,this._z=h*k*e+c*d*f,this._w=h*k*f-c*d*e):"YXZ"===a?(this._x=c*k*f+
16833 h*d*e,this._y=h*d*f-c*k*e,this._z=h*k*e-c*d*f,this._w=h*k*f+c*d*e):"ZXY"===a?(this._x=c*k*f-h*d*e,this._y=h*d*f+c*k*e,this._z=h*k*e+c*d*f,this._w=h*k*f-c*d*e):"ZYX"===a?(this._x=c*k*f-h*d*e,this._y=h*d*f+c*k*e,this._z=h*k*e-c*d*f,this._w=h*k*f+c*d*e):"YZX"===a?(this._x=c*k*f+h*d*e,this._y=h*d*f+c*k*e,this._z=h*k*e-c*d*f,this._w=h*k*f-c*d*e):"XZY"===a&&(this._x=c*k*f-h*d*e,this._y=h*d*f-c*k*e,this._z=h*k*e+c*d*f,this._w=h*k*f+c*d*e);if(!1!==b)this.onChangeCallback();return this},setFromAxisAngle:function(a,
16834 b){b/=2;var c=Math.sin(b);this._x=a.x*c;this._y=a.y*c;this._z=a.z*c;this._w=Math.cos(b);this.onChangeCallback();return this},setFromRotationMatrix:function(a){var b=a.elements,c=b[0];a=b[4];var d=b[8],e=b[1],f=b[5],g=b[9],h=b[2],k=b[6],b=b[10],l=c+f+b;0<l?(c=.5/Math.sqrt(l+1),this._w=.25/c,this._x=(k-g)*c,this._y=(d-h)*c,this._z=(e-a)*c):c>f&&c>b?(c=2*Math.sqrt(1+c-f-b),this._w=(k-g)/c,this._x=.25*c,this._y=(a+e)/c,this._z=(d+h)/c):f>b?(c=2*Math.sqrt(1+f-c-b),this._w=(d-h)/c,this._x=(a+e)/c,this._y=
16835 .25*c,this._z=(g+k)/c):(c=2*Math.sqrt(1+b-c-f),this._w=(e-a)/c,this._x=(d+h)/c,this._y=(g+k)/c,this._z=.25*c);this.onChangeCallback();return this},setFromUnitVectors:function(){var a=new p,b;return function(c,d){void 0===a&&(a=new p);b=c.dot(d)+1;1E-6>b?(b=0,Math.abs(c.x)>Math.abs(c.z)?a.set(-c.y,c.x,0):a.set(0,-c.z,c.y)):a.crossVectors(c,d);this._x=a.x;this._y=a.y;this._z=a.z;this._w=b;return this.normalize()}}(),inverse:function(){return this.conjugate().normalize()},conjugate:function(){this._x*=
16836 -1;this._y*=-1;this._z*=-1;this.onChangeCallback();return this},dot:function(a){return this._x*a._x+this._y*a._y+this._z*a._z+this._w*a._w},lengthSq:function(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w},length:function(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)},normalize:function(){var a=this.length();0===a?(this._z=this._y=this._x=0,this._w=1):(a=1/a,this._x*=a,this._y*=a,this._z*=a,this._w*=a);this.onChangeCallback();return this},
16837 multiply:function(a,b){return void 0!==b?(console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),this.multiplyQuaternions(a,b)):this.multiplyQuaternions(this,a)},premultiply:function(a){return this.multiplyQuaternions(a,this)},multiplyQuaternions:function(a,b){var c=a._x,d=a._y,e=a._z;a=a._w;var f=b._x,g=b._y,h=b._z;b=b._w;this._x=c*b+a*f+d*h-e*g;this._y=d*b+a*g+e*f-c*h;this._z=e*b+a*h+c*g-d*f;this._w=a*b-c*f-d*g-e*h;this.onChangeCallback();
16838 return this},slerp:function(a,b){if(0===b)return this;if(1===b)return this.copy(a);var c=this._x,d=this._y,e=this._z,f=this._w,g=f*a._w+c*a._x+d*a._y+e*a._z;0>g?(this._w=-a._w,this._x=-a._x,this._y=-a._y,this._z=-a._z,g=-g):this.copy(a);if(1<=g)return this._w=f,this._x=c,this._y=d,this._z=e,this;a=Math.sqrt(1-g*g);if(.001>Math.abs(a))return this._w=.5*(f+this._w),this._x=.5*(c+this._x),this._y=.5*(d+this._y),this._z=.5*(e+this._z),this;var h=Math.atan2(a,g),g=Math.sin((1-b)*h)/a;b=Math.sin(b*h)/a;
16839 this._w=f*g+this._w*b;this._x=c*g+this._x*b;this._y=d*g+this._y*b;this._z=e*g+this._z*b;this.onChangeCallback();return this},equals:function(a){return a._x===this._x&&a._y===this._y&&a._z===this._z&&a._w===this._w},fromArray:function(a,b){void 0===b&&(b=0);this._x=a[b];this._y=a[b+1];this._z=a[b+2];this._w=a[b+3];this.onChangeCallback();return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this._x;a[b+1]=this._y;a[b+2]=this._z;a[b+3]=this._w;return a},onChange:function(a){this.onChangeCallback=
16840 a;return this},onChangeCallback:function(){}});Object.assign(p.prototype,{isVector3:!0,set:function(a,b,c){this.x=a;this.y=b;this.z=c;return this},setScalar:function(a){this.z=this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setZ:function(a){this.z=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;case 2:this.z=b;break;default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;
16841 case 1:return this.y;case 2:return this.z;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y,this.z)},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b);this.x+=a.x;this.y+=a.y;this.z+=a.z;return this},addScalar:function(a){this.x+=a;this.y+=a;this.z+=a;return this},
16842 addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;this.z+=a.z*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b);this.x-=a.x;this.y-=a.y;this.z-=a.z;return this},subScalar:function(a){this.x-=a;this.y-=a;this.z-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=
16843 a.z-b.z;return this},multiply:function(a,b){if(void 0!==b)return console.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."),this.multiplyVectors(a,b);this.x*=a.x;this.y*=a.y;this.z*=a.z;return this},multiplyScalar:function(a){this.x*=a;this.y*=a;this.z*=a;return this},multiplyVectors:function(a,b){this.x=a.x*b.x;this.y=a.y*b.y;this.z=a.z*b.z;return this},applyEuler:function(){var a=new Z;return function(b){b&&b.isEuler||console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.");
16844 return this.applyQuaternion(a.setFromEuler(b))}}(),applyAxisAngle:function(){var a=new Z;return function(b,c){return this.applyQuaternion(a.setFromAxisAngle(b,c))}}(),applyMatrix3:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;this.x=a[0]*b+a[3]*c+a[6]*d;this.y=a[1]*b+a[4]*c+a[7]*d;this.z=a[2]*b+a[5]*c+a[8]*d;return this},applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;var e=1/(a[3]*b+a[7]*c+a[11]*d+a[15]);this.x=(a[0]*b+a[4]*c+a[8]*d+a[12])*e;this.y=(a[1]*b+a[5]*c+a[9]*
16845 d+a[13])*e;this.z=(a[2]*b+a[6]*c+a[10]*d+a[14])*e;return this},applyQuaternion:function(a){var b=this.x,c=this.y,d=this.z,e=a.x,f=a.y,g=a.z;a=a.w;var h=a*b+f*d-g*c,k=a*c+g*b-e*d,l=a*d+e*c-f*b,b=-e*b-f*c-g*d;this.x=h*a+b*-e+k*-g-l*-f;this.y=k*a+b*-f+l*-e-h*-g;this.z=l*a+b*-g+h*-f-k*-e;return this},project:function(){var a=new K;return function(b){a.multiplyMatrices(b.projectionMatrix,a.getInverse(b.matrixWorld));return this.applyMatrix4(a)}}(),unproject:function(){var a=new K;return function(b){a.multiplyMatrices(b.matrixWorld,
16846 a.getInverse(b.projectionMatrix));return this.applyMatrix4(a)}}(),transformDirection:function(a){var b=this.x,c=this.y,d=this.z;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d;this.y=a[1]*b+a[5]*c+a[9]*d;this.z=a[2]*b+a[6]*c+a[10]*d;return this.normalize()},divide:function(a){this.x/=a.x;this.y/=a.y;this.z/=a.z;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);this.z=Math.min(this.z,a.z);return this},max:function(a){this.x=
16847 Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);this.z=Math.max(this.z,a.z);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));this.z=Math.max(a.z,Math.min(b.z,this.z));return this},clampScalar:function(){var a=new p,b=new p;return function(c,d){a.set(c,c,c);b.set(d,d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.divideScalar(c||1).multiplyScalar(Math.max(a,Math.min(b,c)))},floor:function(){this.x=
16848 Math.floor(this.x);this.y=Math.floor(this.y);this.z=Math.floor(this.z);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);this.z=Math.round(this.z);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);this.z=0>this.z?Math.ceil(this.z):Math.floor(this.z);return this},negate:function(){this.x=
16849 -this.x;this.y=-this.y;this.z=-this.z;return this},dot:function(a){return this.x*a.x+this.y*a.y+this.z*a.z},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},manhattanLength:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)},normalize:function(){return this.divideScalar(this.length()||1)},setLength:function(a){return this.normalize().multiplyScalar(a)},lerp:function(a,b){this.x+=(a.x-
16850 this.x)*b;this.y+=(a.y-this.y)*b;this.z+=(a.z-this.z)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},cross:function(a,b){return void 0!==b?(console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),this.crossVectors(a,b)):this.crossVectors(this,a)},crossVectors:function(a,b){var c=a.x,d=a.y;a=a.z;var e=b.x,f=b.y;b=b.z;this.x=d*b-a*f;this.y=a*e-c*b;this.z=c*f-d*e;return this},projectOnVector:function(a){var b=
16851 a.dot(this)/a.lengthSq();return this.copy(a).multiplyScalar(b)},projectOnPlane:function(){var a=new p;return function(b){a.copy(this).projectOnVector(b);return this.sub(a)}}(),reflect:function(){var a=new p;return function(b){return this.sub(a.copy(b).multiplyScalar(2*this.dot(b)))}}(),angleTo:function(a){a=this.dot(a)/Math.sqrt(this.lengthSq()*a.lengthSq());return Math.acos(R.clamp(a,-1,1))},distanceTo:function(a){return Math.sqrt(this.distanceToSquared(a))},distanceToSquared:function(a){var b=this.x-
16852 a.x,c=this.y-a.y;a=this.z-a.z;return b*b+c*c+a*a},manhattanDistanceTo:function(a){return Math.abs(this.x-a.x)+Math.abs(this.y-a.y)+Math.abs(this.z-a.z)},setFromSpherical:function(a){var b=Math.sin(a.phi)*a.radius;this.x=b*Math.sin(a.theta);this.y=Math.cos(a.phi)*a.radius;this.z=b*Math.cos(a.theta);return this},setFromCylindrical:function(a){this.x=a.radius*Math.sin(a.theta);this.y=a.y;this.z=a.radius*Math.cos(a.theta);return this},setFromMatrixPosition:function(a){a=a.elements;this.x=a[12];this.y=
16853 a[13];this.z=a[14];return this},setFromMatrixScale:function(a){var b=this.setFromMatrixColumn(a,0).length(),c=this.setFromMatrixColumn(a,1).length();a=this.setFromMatrixColumn(a,2).length();this.x=b;this.y=c;this.z=a;return this},setFromMatrixColumn:function(a,b){return this.fromArray(a.elements,4*b)},equals:function(a){return a.x===this.x&&a.y===this.y&&a.z===this.z},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];this.z=a[b+2];return this},toArray:function(a,b){void 0===a&&(a=
16854 []);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;a[b+2]=this.z;return a},fromBufferAttribute:function(a,b,c){void 0!==c&&console.warn("THREE.Vector3: offset has been removed from .fromBufferAttribute().");this.x=a.getX(b);this.y=a.getY(b);this.z=a.getZ(b);return this}});Object.assign(ra.prototype,{isMatrix3:!0,set:function(a,b,c,d,e,f,g,h,k){var l=this.elements;l[0]=a;l[1]=d;l[2]=g;l[3]=b;l[4]=e;l[5]=h;l[6]=c;l[7]=f;l[8]=k;return this},identity:function(){this.set(1,0,0,0,1,0,0,0,1);return this},clone:function(){return(new this.constructor).fromArray(this.elements)},
16855 copy:function(a){var b=this.elements;a=a.elements;b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];b[5]=a[5];b[6]=a[6];b[7]=a[7];b[8]=a[8];return this},setFromMatrix4:function(a){a=a.elements;this.set(a[0],a[4],a[8],a[1],a[5],a[9],a[2],a[6],a[10]);return this},applyToBufferAttribute:function(){var a=new p;return function(b){for(var c=0,d=b.count;c<d;c++)a.x=b.getX(c),a.y=b.getY(c),a.z=b.getZ(c),a.applyMatrix3(this),b.setXYZ(c,a.x,a.y,a.z);return b}}(),multiply:function(a){return this.multiplyMatrices(this,
16856 a)},premultiply:function(a){return this.multiplyMatrices(a,this)},multiplyMatrices:function(a,b){var c=a.elements,d=b.elements;b=this.elements;a=c[0];var e=c[3],f=c[6],g=c[1],h=c[4],k=c[7],l=c[2],q=c[5],c=c[8],n=d[0],m=d[3],r=d[6],p=d[1],v=d[4],w=d[7],x=d[2],z=d[5],d=d[8];b[0]=a*n+e*p+f*x;b[3]=a*m+e*v+f*z;b[6]=a*r+e*w+f*d;b[1]=g*n+h*p+k*x;b[4]=g*m+h*v+k*z;b[7]=g*r+h*w+k*d;b[2]=l*n+q*p+c*x;b[5]=l*m+q*v+c*z;b[8]=l*r+q*w+c*d;return this},multiplyScalar:function(a){var b=this.elements;b[0]*=a;b[3]*=a;
16857 b[6]*=a;b[1]*=a;b[4]*=a;b[7]*=a;b[2]*=a;b[5]*=a;b[8]*=a;return this},determinant:function(){var a=this.elements,b=a[0],c=a[1],d=a[2],e=a[3],f=a[4],g=a[5],h=a[6],k=a[7],a=a[8];return b*f*a-b*g*k-c*e*a+c*g*h+d*e*k-d*f*h},getInverse:function(a,b){a&&a.isMatrix4&&console.error("THREE.Matrix3: .getInverse() no longer takes a Matrix4 argument.");var c=a.elements;a=this.elements;var d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],k=c[5],l=c[6],q=c[7],c=c[8],n=c*h-k*q,m=k*l-c*g,r=q*g-h*l,p=d*n+e*m+f*r;if(0===p){if(!0===
16858 b)throw Error("THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0");console.warn("THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0");return this.identity()}b=1/p;a[0]=n*b;a[1]=(f*q-c*e)*b;a[2]=(k*e-f*h)*b;a[3]=m*b;a[4]=(c*d-f*l)*b;a[5]=(f*g-k*d)*b;a[6]=r*b;a[7]=(e*l-q*d)*b;a[8]=(h*d-e*g)*b;return this},transpose:function(){var a=this.elements;var b=a[1];a[1]=a[3];a[3]=b;b=a[2];a[2]=a[6];a[6]=b;b=a[5];a[5]=a[7];a[7]=b;return this},getNormalMatrix:function(a){return this.setFromMatrix4(a).getInverse(this).transpose()},
16859 transposeIntoArray:function(a){var b=this.elements;a[0]=b[0];a[1]=b[3];a[2]=b[6];a[3]=b[1];a[4]=b[4];a[5]=b[7];a[6]=b[2];a[7]=b[5];a[8]=b[8];return this},setUvTransform:function(a,b,c,d,e,f,g){var h=Math.cos(e);e=Math.sin(e);this.set(c*h,c*e,-c*(h*f+e*g)+f+a,-d*e,d*h,-d*(-e*f+h*g)+g+b,0,0,1)},scale:function(a,b){var c=this.elements;c[0]*=a;c[3]*=a;c[6]*=a;c[1]*=b;c[4]*=b;c[7]*=b;return this},rotate:function(a){var b=Math.cos(a);a=Math.sin(a);var c=this.elements,d=c[0],e=c[3],f=c[6],g=c[1],h=c[4],
16860 k=c[7];c[0]=b*d+a*g;c[3]=b*e+a*h;c[6]=b*f+a*k;c[1]=-a*d+b*g;c[4]=-a*e+b*h;c[7]=-a*f+b*k;return this},translate:function(a,b){var c=this.elements;c[0]+=a*c[2];c[3]+=a*c[5];c[6]+=a*c[8];c[1]+=b*c[2];c[4]+=b*c[5];c[7]+=b*c[8];return this},equals:function(a){var b=this.elements;a=a.elements;for(var c=0;9>c;c++)if(b[c]!==a[c])return!1;return!0},fromArray:function(a,b){void 0===b&&(b=0);for(var c=0;9>c;c++)this.elements[c]=a[c+b];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);var c=
16861 this.elements;a[b]=c[0];a[b+1]=c[1];a[b+2]=c[2];a[b+3]=c[3];a[b+4]=c[4];a[b+5]=c[5];a[b+6]=c[6];a[b+7]=c[7];a[b+8]=c[8];return a}});var kf=0;ea.DEFAULT_IMAGE=void 0;ea.DEFAULT_MAPPING=300;Object.defineProperty(ea.prototype,"needsUpdate",{set:function(a){!0===a&&this.version++}});Object.assign(ea.prototype,ja.prototype,{constructor:ea,isTexture:!0,clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.name=a.name;this.image=a.image;this.mipmaps=a.mipmaps.slice(0);this.mapping=
16862 a.mapping;this.wrapS=a.wrapS;this.wrapT=a.wrapT;this.magFilter=a.magFilter;this.minFilter=a.minFilter;this.anisotropy=a.anisotropy;this.format=a.format;this.type=a.type;this.offset.copy(a.offset);this.repeat.copy(a.repeat);this.center.copy(a.center);this.rotation=a.rotation;this.matrixAutoUpdate=a.matrixAutoUpdate;this.matrix.copy(a.matrix);this.generateMipmaps=a.generateMipmaps;this.premultiplyAlpha=a.premultiplyAlpha;this.flipY=a.flipY;this.unpackAlignment=a.unpackAlignment;this.encoding=a.encoding;
16863 return this},toJSON:function(a){var b=void 0===a||"string"===typeof a;if(!b&&void 0!==a.textures[this.uuid])return a.textures[this.uuid];var c={metadata:{version:4.5,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,mapping:this.mapping,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY};
16864 if(void 0!==this.image){var d=this.image;void 0===d.uuid&&(d.uuid=R.generateUUID());if(!b&&void 0===a.images[d.uuid]){var e=a.images,f=d.uuid,g=d.uuid;if(d instanceof HTMLCanvasElement)var h=d;else{h=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");h.width=d.width;h.height=d.height;var k=h.getContext("2d");d instanceof ImageData?k.putImageData(d,0,0):k.drawImage(d,0,0,d.width,d.height)}h=2048<h.width||2048<h.height?h.toDataURL("image/jpeg",.6):h.toDataURL("image/png");e[f]={uuid:g,
16865 url:h}}c.image=d.uuid}b||(a.textures[this.uuid]=c);return c},dispose:function(){this.dispatchEvent({type:"dispose"})},transformUv:function(a){if(300===this.mapping){a.applyMatrix3(this.matrix);if(0>a.x||1<a.x)switch(this.wrapS){case 1E3:a.x-=Math.floor(a.x);break;case 1001:a.x=0>a.x?0:1;break;case 1002:a.x=1===Math.abs(Math.floor(a.x)%2)?Math.ceil(a.x)-a.x:a.x-Math.floor(a.x)}if(0>a.y||1<a.y)switch(this.wrapT){case 1E3:a.y-=Math.floor(a.y);break;case 1001:a.y=0>a.y?0:1;break;case 1002:a.y=1===Math.abs(Math.floor(a.y)%
16866 2)?Math.ceil(a.y)-a.y:a.y-Math.floor(a.y)}this.flipY&&(a.y=1-a.y)}}});Object.assign(da.prototype,{isVector4:!0,set:function(a,b,c,d){this.x=a;this.y=b;this.z=c;this.w=d;return this},setScalar:function(a){this.w=this.z=this.y=this.x=a;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setZ:function(a){this.z=a;return this},setW:function(a){this.w=a;return this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;case 2:this.z=b;break;
16867 case 3:this.w=b;break;default:throw Error("index is out of range: "+a);}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw Error("index is out of range: "+a);}},clone:function(){return new this.constructor(this.x,this.y,this.z,this.w)},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;this.w=void 0!==a.w?a.w:1;return this},add:function(a,b){if(void 0!==b)return console.warn("THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),
16868 this.addVectors(a,b);this.x+=a.x;this.y+=a.y;this.z+=a.z;this.w+=a.w;return this},addScalar:function(a){this.x+=a;this.y+=a;this.z+=a;this.w+=a;return this},addVectors:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;this.w=a.w+b.w;return this},addScaledVector:function(a,b){this.x+=a.x*b;this.y+=a.y*b;this.z+=a.z*b;this.w+=a.w*b;return this},sub:function(a,b){if(void 0!==b)return console.warn("THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,
16869 b);this.x-=a.x;this.y-=a.y;this.z-=a.z;this.w-=a.w;return this},subScalar:function(a){this.x-=a;this.y-=a;this.z-=a;this.w-=a;return this},subVectors:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;this.w=a.w-b.w;return this},multiplyScalar:function(a){this.x*=a;this.y*=a;this.z*=a;this.w*=a;return this},applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z,e=this.w;a=a.elements;this.x=a[0]*b+a[4]*c+a[8]*d+a[12]*e;this.y=a[1]*b+a[5]*c+a[9]*d+a[13]*e;this.z=a[2]*b+a[6]*c+a[10]*d+a[14]*
16870 e;this.w=a[3]*b+a[7]*c+a[11]*d+a[15]*e;return this},divideScalar:function(a){return this.multiplyScalar(1/a)},setAxisAngleFromQuaternion:function(a){this.w=2*Math.acos(a.w);var b=Math.sqrt(1-a.w*a.w);1E-4>b?(this.x=1,this.z=this.y=0):(this.x=a.x/b,this.y=a.y/b,this.z=a.z/b);return this},setAxisAngleFromRotationMatrix:function(a){a=a.elements;var b=a[0];var c=a[4];var d=a[8],e=a[1],f=a[5],g=a[9];var h=a[2];var k=a[6];var l=a[10];if(.01>Math.abs(c-e)&&.01>Math.abs(d-h)&&.01>Math.abs(g-k)){if(.1>Math.abs(c+
16871 e)&&.1>Math.abs(d+h)&&.1>Math.abs(g+k)&&.1>Math.abs(b+f+l-3))return this.set(1,0,0,0),this;a=Math.PI;b=(b+1)/2;f=(f+1)/2;l=(l+1)/2;c=(c+e)/4;d=(d+h)/4;g=(g+k)/4;b>f&&b>l?.01>b?(k=0,c=h=.707106781):(k=Math.sqrt(b),h=c/k,c=d/k):f>l?.01>f?(k=.707106781,h=0,c=.707106781):(h=Math.sqrt(f),k=c/h,c=g/h):.01>l?(h=k=.707106781,c=0):(c=Math.sqrt(l),k=d/c,h=g/c);this.set(k,h,c,a);return this}a=Math.sqrt((k-g)*(k-g)+(d-h)*(d-h)+(e-c)*(e-c));.001>Math.abs(a)&&(a=1);this.x=(k-g)/a;this.y=(d-h)/a;this.z=(e-c)/a;
16872 this.w=Math.acos((b+f+l-1)/2);return this},min:function(a){this.x=Math.min(this.x,a.x);this.y=Math.min(this.y,a.y);this.z=Math.min(this.z,a.z);this.w=Math.min(this.w,a.w);return this},max:function(a){this.x=Math.max(this.x,a.x);this.y=Math.max(this.y,a.y);this.z=Math.max(this.z,a.z);this.w=Math.max(this.w,a.w);return this},clamp:function(a,b){this.x=Math.max(a.x,Math.min(b.x,this.x));this.y=Math.max(a.y,Math.min(b.y,this.y));this.z=Math.max(a.z,Math.min(b.z,this.z));this.w=Math.max(a.w,Math.min(b.w,
16873 this.w));return this},clampScalar:function(){var a,b;return function(c,d){void 0===a&&(a=new da,b=new da);a.set(c,c,c,c);b.set(d,d,d,d);return this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.divideScalar(c||1).multiplyScalar(Math.max(a,Math.min(b,c)))},floor:function(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);this.z=Math.floor(this.z);this.w=Math.floor(this.w);return this},ceil:function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);
16874 this.w=Math.ceil(this.w);return this},round:function(){this.x=Math.round(this.x);this.y=Math.round(this.y);this.z=Math.round(this.z);this.w=Math.round(this.w);return this},roundToZero:function(){this.x=0>this.x?Math.ceil(this.x):Math.floor(this.x);this.y=0>this.y?Math.ceil(this.y):Math.floor(this.y);this.z=0>this.z?Math.ceil(this.z):Math.floor(this.z);this.w=0>this.w?Math.ceil(this.w):Math.floor(this.w);return this},negate:function(){this.x=-this.x;this.y=-this.y;this.z=-this.z;this.w=-this.w;return this},
16875 dot:function(a){return this.x*a.x+this.y*a.y+this.z*a.z+this.w*a.w},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},manhattanLength:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)},normalize:function(){return this.divideScalar(this.length()||1)},setLength:function(a){return this.normalize().multiplyScalar(a)},lerp:function(a,b){this.x+=
16876 (a.x-this.x)*b;this.y+=(a.y-this.y)*b;this.z+=(a.z-this.z)*b;this.w+=(a.w-this.w)*b;return this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},equals:function(a){return a.x===this.x&&a.y===this.y&&a.z===this.z&&a.w===this.w},fromArray:function(a,b){void 0===b&&(b=0);this.x=a[b];this.y=a[b+1];this.z=a[b+2];this.w=a[b+3];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.x;a[b+1]=this.y;a[b+2]=this.z;a[b+3]=this.w;return a},fromBufferAttribute:function(a,
16877 b,c){void 0!==c&&console.warn("THREE.Vector4: offset has been removed from .fromBufferAttribute().");this.x=a.getX(b);this.y=a.getY(b);this.z=a.getZ(b);this.w=a.getW(b);return this}});Object.assign(Hb.prototype,ja.prototype,{isWebGLRenderTarget:!0,setSize:function(a,b){if(this.width!==a||this.height!==b)this.width=a,this.height=b,this.dispose();this.viewport.set(0,0,a,b);this.scissor.set(0,0,a,b)},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.width=a.width;this.height=
16878 a.height;this.viewport.copy(a.viewport);this.texture=a.texture.clone();this.depthBuffer=a.depthBuffer;this.stencilBuffer=a.stencilBuffer;this.depthTexture=a.depthTexture;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Ib.prototype=Object.create(Hb.prototype);Ib.prototype.constructor=Ib;Ib.prototype.isWebGLRenderTargetCube=!0;fb.prototype=Object.create(ea.prototype);fb.prototype.constructor=fb;fb.prototype.isDataTexture=!0;Ua.prototype=Object.create(ea.prototype);Ua.prototype.constructor=
16879 Ua;Ua.prototype.isCubeTexture=!0;Object.defineProperty(Ua.prototype,"images",{get:function(){return this.image},set:function(a){this.image=a}});var Be=new ea,Ce=new Ua,we=[],ye=[],Ae=new Float32Array(16),ze=new Float32Array(9);Ge.prototype.setValue=function(a,b){for(var c=this.seq,d=0,e=c.length;d!==e;++d){var f=c[d];f.setValue(a,b[f.id])}};var Od=/([\w\d_]+)(\])?(\[|\.)?/g;gb.prototype.setValue=function(a,b,c){b=this.map[b];void 0!==b&&b.setValue(a,c,this.renderer)};gb.prototype.setOptional=function(a,
16880 b,c){b=b[c];void 0!==b&&this.setValue(a,c,b)};gb.upload=function(a,b,c,d){for(var e=0,f=b.length;e!==f;++e){var g=b[e],h=c[g.id];!1!==h.needsUpdate&&g.setValue(a,h.value,d)}};gb.seqWithValue=function(a,b){for(var c=[],d=0,e=a.length;d!==e;++d){var f=a[d];f.id in b&&c.push(f)}return c};var sg={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,
16881 cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,
16882 deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,
16883 lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,
16884 mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,
16885 royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};Object.assign(H.prototype,{isColor:!0,r:1,g:1,b:1,set:function(a){a&&
16886 a.isColor?this.copy(a):"number"===typeof a?this.setHex(a):"string"===typeof a&&this.setStyle(a);return this},setScalar:function(a){this.b=this.g=this.r=a;return this},setHex:function(a){a=Math.floor(a);this.r=(a>>16&255)/255;this.g=(a>>8&255)/255;this.b=(a&255)/255;return this},setRGB:function(a,b,c){this.r=a;this.g=b;this.b=c;return this},setHSL:function(){function a(a,c,d){0>d&&(d+=1);1<d&&--d;return d<1/6?a+6*(c-a)*d:.5>d?c:d<2/3?a+6*(c-a)*(2/3-d):a}return function(b,c,d){b=R.euclideanModulo(b,
16887 1);c=R.clamp(c,0,1);d=R.clamp(d,0,1);0===c?this.r=this.g=this.b=d:(c=.5>=d?d*(1+c):d+c-d*c,d=2*d-c,this.r=a(d,c,b+1/3),this.g=a(d,c,b),this.b=a(d,c,b-1/3));return this}}(),setStyle:function(a){function b(b){void 0!==b&&1>parseFloat(b)&&console.warn("THREE.Color: Alpha component of "+a+" will be ignored.")}var c;if(c=/^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(a)){var d=c[2];switch(c[1]){case "rgb":case "rgba":if(c=/^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d))return this.r=Math.min(255,
16888 parseInt(c[1],10))/255,this.g=Math.min(255,parseInt(c[2],10))/255,this.b=Math.min(255,parseInt(c[3],10))/255,b(c[5]),this;if(c=/^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d))return this.r=Math.min(100,parseInt(c[1],10))/100,this.g=Math.min(100,parseInt(c[2],10))/100,this.b=Math.min(100,parseInt(c[3],10))/100,b(c[5]),this;break;case "hsl":case "hsla":if(c=/^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(d)){var d=parseFloat(c[1])/360,
16889 e=parseInt(c[2],10)/100,f=parseInt(c[3],10)/100;b(c[5]);return this.setHSL(d,e,f)}}}else if(c=/^\#([A-Fa-f0-9]+)$/.exec(a)){c=c[1];d=c.length;if(3===d)return this.r=parseInt(c.charAt(0)+c.charAt(0),16)/255,this.g=parseInt(c.charAt(1)+c.charAt(1),16)/255,this.b=parseInt(c.charAt(2)+c.charAt(2),16)/255,this;if(6===d)return this.r=parseInt(c.charAt(0)+c.charAt(1),16)/255,this.g=parseInt(c.charAt(2)+c.charAt(3),16)/255,this.b=parseInt(c.charAt(4)+c.charAt(5),16)/255,this}a&&0<a.length&&(c=sg[a],void 0!==
16890 c?this.setHex(c):console.warn("THREE.Color: Unknown color "+a));return this},clone:function(){return new this.constructor(this.r,this.g,this.b)},copy:function(a){this.r=a.r;this.g=a.g;this.b=a.b;return this},copyGammaToLinear:function(a,b){void 0===b&&(b=2);this.r=Math.pow(a.r,b);this.g=Math.pow(a.g,b);this.b=Math.pow(a.b,b);return this},copyLinearToGamma:function(a,b){void 0===b&&(b=2);b=0<b?1/b:1;this.r=Math.pow(a.r,b);this.g=Math.pow(a.g,b);this.b=Math.pow(a.b,b);return this},convertGammaToLinear:function(){var a=
16891 this.r,b=this.g,c=this.b;this.r=a*a;this.g=b*b;this.b=c*c;return this},convertLinearToGamma:function(){this.r=Math.sqrt(this.r);this.g=Math.sqrt(this.g);this.b=Math.sqrt(this.b);return this},getHex:function(){return 255*this.r<<16^255*this.g<<8^255*this.b<<0},getHexString:function(){return("000000"+this.getHex().toString(16)).slice(-6)},getHSL:function(a){a=a||{h:0,s:0,l:0};var b=this.r,c=this.g,d=this.b,e=Math.max(b,c,d),f=Math.min(b,c,d),g,h=(f+e)/2;if(f===e)f=g=0;else{var k=e-f,f=.5>=h?k/(e+f):
16892 k/(2-e-f);switch(e){case b:g=(c-d)/k+(c<d?6:0);break;case c:g=(d-b)/k+2;break;case d:g=(b-c)/k+4}g/=6}a.h=g;a.s=f;a.l=h;return a},getStyle:function(){return"rgb("+(255*this.r|0)+","+(255*this.g|0)+","+(255*this.b|0)+")"},offsetHSL:function(a,b,c){var d=this.getHSL();d.h+=a;d.s+=b;d.l+=c;this.setHSL(d.h,d.s,d.l);return this},add:function(a){this.r+=a.r;this.g+=a.g;this.b+=a.b;return this},addColors:function(a,b){this.r=a.r+b.r;this.g=a.g+b.g;this.b=a.b+b.b;return this},addScalar:function(a){this.r+=
16893 a;this.g+=a;this.b+=a;return this},sub:function(a){this.r=Math.max(0,this.r-a.r);this.g=Math.max(0,this.g-a.g);this.b=Math.max(0,this.b-a.b);return this},multiply:function(a){this.r*=a.r;this.g*=a.g;this.b*=a.b;return this},multiplyScalar:function(a){this.r*=a;this.g*=a;this.b*=a;return this},lerp:function(a,b){this.r+=(a.r-this.r)*b;this.g+=(a.g-this.g)*b;this.b+=(a.b-this.b)*b;return this},equals:function(a){return a.r===this.r&&a.g===this.g&&a.b===this.b},fromArray:function(a,b){void 0===b&&(b=
16894 0);this.r=a[b];this.g=a[b+1];this.b=a[b+2];return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===b&&(b=0);a[b]=this.r;a[b+1]=this.g;a[b+2]=this.b;return a},toJSON:function(){return this.getHex()}});var E={common:{diffuse:{value:new H(15658734)},opacity:{value:1},map:{value:null},uvTransform:{value:new ra},alphaMap:{value:null}},specularmap:{specularMap:{value:null}},envmap:{envMap:{value:null},flipEnvMap:{value:-1},reflectivity:{value:1},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},
16895 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},
16896 fogFar:{value:2E3},fogColor:{value:new H(16777215)}},lights:{ambientLightColor:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{}}},spotShadowMap:{value:[]},spotShadowMatrix:{value:[]},
16897 pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}}},points:{diffuse:{value:new H(15658734)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},uvTransform:{value:new ra}}},
16898 Ea={merge:function(a){for(var b={},c=0;c<a.length;c++){var d=this.clone(a[c]),e;for(e in d)b[e]=d[e]}return b},clone:function(a){var b={},c;for(c in a){b[c]={};for(var d in a[c]){var e=a[c][d];e&&(e.isColor||e.isMatrix3||e.isMatrix4||e.isVector2||e.isVector3||e.isVector4||e.isTexture)?b[c][d]=e.clone():Array.isArray(e)?b[c][d]=e.slice():b[c][d]=e}}return b}},W={alphamap_fragment:"#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n",alphamap_pars_fragment:"#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n",
16899 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",
16900 aomap_pars_fragment:"#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif",begin_vertex:"\nvec3 transformed = vec3( position );\n",beginnormal_vertex:"\nvec3 objectNormal = vec3( normal );\n",bsdfs:"float punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tif( decayExponent > 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n#else\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n\t}\n\treturn 1.0;\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE  = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS  = 0.5 / LUT_SIZE;\n\tfloat theta = acos( dot( N, V ) );\n\tvec2 uv = vec2(\n\t\tsqrt( saturate( roughness ) ),\n\t\tsaturate( theta / ( 0.5 * PI ) ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.86267 + (0.49788 + 0.01436 * y ) * y;\n\tfloat b = 3.45068 + (4.18814 + y) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = (x > 0.0) ? v : 0.5 * inversesqrt( 1.0 - x * x ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tvec3 result = vec3( LTC_ClippedSphereFormFactor( vectorFormFactor ) );\n\treturn result;\n}\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n\treturn specularColor * AB.x + AB.y;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n",
16901 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",
16902 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",
16903 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",
16904 color_fragment:"#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif",color_pars_fragment:"#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n",color_pars_vertex:"#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif",color_vertex:"#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif",common:"#define PI 3.14159265359\n#define PI2 6.28318530718\n#define PI_HALF 1.5707963267949\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\n",
16905 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",
16906 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",
16907 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",
16908 envmap_fragment:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\treflectVec = normalize( reflectVec );\n\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\treflectVec = normalize( reflectVec );\n\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\tenvColor = envMapTexelToLinear( envColor );\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif\n",
16909 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",
16910 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",
16911 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",
16912 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",
16913 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",
16914 lights_pars:"uniform vec3 ambientLightColor;\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t\tfloat shadowCameraNear;\n\t\tfloat shadowCameraFar;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight  ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltcMat;\tuniform sampler2D ltcMag;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( queryVec, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif\n",
16915 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",
16916 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",
16917 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",
16918 lights_template:"\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#ifdef USE_LIGHTMAP\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tirradiance += getLightProbeIndirectIrradiance( geometry, 8 );\n\t#endif\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tvec3 radiance = getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), 8 );\n\t#ifndef STANDARD\n\t\tvec3 clearCoatRadiance = getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\n\t#else\n\t\tvec3 clearCoatRadiance = vec3( 0.0 );\n\t#endif\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n",
16919 logdepthbuf_fragment:"#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#ifdef USE_LOGDEPTHBUF\n\tuniform float logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n#endif\n",logdepthbuf_pars_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n\tuniform float logDepthBufFC;\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t#else\n\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\tgl_Position.z *= gl_Position.w;\n\t#endif\n#endif\n",
16920 map_fragment:"#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n",map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n",map_particle_fragment:"#ifdef USE_MAP\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n",map_particle_pars_fragment:"#ifdef USE_MAP\n\tuniform mat3 uvTransform;\n\tuniform sampler2D map;\n#endif\n",
16921 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",
16922 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",
16923 normal_fragment:"#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n#endif\n#ifdef USE_NORMALMAP\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n",
16924 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",
16925 packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256.,  256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n",
16926 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",
16927 roughnessmap_fragment:"float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif\n",roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tshadow = (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif\n",
16928 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",
16929 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",
16930 shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}\n",
16931 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",
16932 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",
16933 specularmap_fragment:"float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif",specularmap_pars_fragment:"#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",tonemapping_fragment:"#if defined( TONE_MAPPING )\n  gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n",tonemapping_pars_fragment:"#ifndef saturate\n\t#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n",
16934 uv_pars_fragment:"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n#endif",uv_pars_vertex:"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\n",
16935 uv_vertex:"#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif",uv2_pars_fragment:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif",uv2_pars_vertex:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif",
16936 uv2_vertex:"#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n#endif\n",cube_frag:"uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldPosition;\nvoid main() {\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n}\n",
16937 cube_vert:"varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}\n",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}\n",
16938 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",
16939 distanceRGBA_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}\n",
16940 distanceRGBA_vert:"#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}\n",
16941 equirect_frag:"uniform sampler2D tEquirect;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n}\n",equirect_vert:"varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}\n",
16942 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",
16943 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",
16944 meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\treflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n",
16945 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",
16946 meshlambert_frag:"uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n",
16947 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",
16948 meshphong_frag:"#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n",
16949 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",
16950 meshphysical_frag:"#define PHYSICAL\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <lights_pars>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n",
16951 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",
16952 normal_frag:"#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\nvoid main() {\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}\n",
16953 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",
16954 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",
16955 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",
16956 shadow_frag:"uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <fog_fragment>\n}\n",shadow_vert:"#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n"},
16957 mb={basic:{uniforms:Ea.merge([E.common,E.specularmap,E.envmap,E.aomap,E.lightmap,E.fog]),vertexShader:W.meshbasic_vert,fragmentShader:W.meshbasic_frag},lambert:{uniforms:Ea.merge([E.common,E.specularmap,E.envmap,E.aomap,E.lightmap,E.emissivemap,E.fog,E.lights,{emissive:{value:new H(0)}}]),vertexShader:W.meshlambert_vert,fragmentShader:W.meshlambert_frag},phong:{uniforms:Ea.merge([E.common,E.specularmap,E.envmap,E.aomap,E.lightmap,E.emissivemap,E.bumpmap,E.normalmap,E.displacementmap,E.gradientmap,
16958 E.fog,E.lights,{emissive:{value:new H(0)},specular:{value:new H(1118481)},shininess:{value:30}}]),vertexShader:W.meshphong_vert,fragmentShader:W.meshphong_frag},standard:{uniforms:Ea.merge([E.common,E.envmap,E.aomap,E.lightmap,E.emissivemap,E.bumpmap,E.normalmap,E.displacementmap,E.roughnessmap,E.metalnessmap,E.fog,E.lights,{emissive:{value:new H(0)},roughness:{value:.5},metalness:{value:.5},envMapIntensity:{value:1}}]),vertexShader:W.meshphysical_vert,fragmentShader:W.meshphysical_frag},points:{uniforms:Ea.merge([E.points,
16959 E.fog]),vertexShader:W.points_vert,fragmentShader:W.points_frag},dashed:{uniforms:Ea.merge([E.common,E.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:W.linedashed_vert,fragmentShader:W.linedashed_frag},depth:{uniforms:Ea.merge([E.common,E.displacementmap]),vertexShader:W.depth_vert,fragmentShader:W.depth_frag},normal:{uniforms:Ea.merge([E.common,E.bumpmap,E.normalmap,E.displacementmap,{opacity:{value:1}}]),vertexShader:W.normal_vert,fragmentShader:W.normal_frag},cube:{uniforms:{tCube:{value:null},
16960 tFlip:{value:-1},opacity:{value:1}},vertexShader:W.cube_vert,fragmentShader:W.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:W.equirect_vert,fragmentShader:W.equirect_frag},distanceRGBA:{uniforms:Ea.merge([E.common,E.displacementmap,{referencePosition:{value:new p},nearDistance:{value:1},farDistance:{value:1E3}}]),vertexShader:W.distanceRGBA_vert,fragmentShader:W.distanceRGBA_frag},shadow:{uniforms:Ea.merge([E.lights,E.fog,{color:{value:new H(0)},opacity:{value:1}}]),vertexShader:W.shadow_vert,
16961 fragmentShader:W.shadow_frag}};mb.physical={uniforms:Ea.merge([mb.standard.uniforms,{clearCoat:{value:0},clearCoatRoughness:{value:0}}]),vertexShader:W.meshphysical_vert,fragmentShader:W.meshphysical_frag};Object.assign(kd.prototype,{set:function(a,b){this.min.copy(a);this.max.copy(b);return this},setFromPoints:function(a){this.makeEmpty();for(var b=0,c=a.length;b<c;b++)this.expandByPoint(a[b]);return this},setFromCenterAndSize:function(){var a=new C;return function(b,c){c=a.copy(c).multiplyScalar(.5);
16962 this.min.copy(b).sub(c);this.max.copy(b).add(c);return this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.min.copy(a.min);this.max.copy(a.max);return this},makeEmpty:function(){this.min.x=this.min.y=Infinity;this.max.x=this.max.y=-Infinity;return this},isEmpty:function(){return this.max.x<this.min.x||this.max.y<this.min.y},getCenter:function(a){a=a||new C;return this.isEmpty()?a.set(0,0):a.addVectors(this.min,this.max).multiplyScalar(.5)},getSize:function(a){a=
16963 a||new C;return this.isEmpty()?a.set(0,0):a.subVectors(this.max,this.min)},expandByPoint:function(a){this.min.min(a);this.max.max(a);return this},expandByVector:function(a){this.min.sub(a);this.max.add(a);return this},expandByScalar:function(a){this.min.addScalar(-a);this.max.addScalar(a);return this},containsPoint:function(a){return a.x<this.min.x||a.x>this.max.x||a.y<this.min.y||a.y>this.max.y?!1:!0},containsBox:function(a){return this.min.x<=a.min.x&&a.max.x<=this.max.x&&this.min.y<=a.min.y&&a.max.y<=
16964 this.max.y},getParameter:function(a,b){return(b||new C).set((a.x-this.min.x)/(this.max.x-this.min.x),(a.y-this.min.y)/(this.max.y-this.min.y))},intersectsBox:function(a){return a.max.x<this.min.x||a.min.x>this.max.x||a.max.y<this.min.y||a.min.y>this.max.y?!1:!0},clampPoint:function(a,b){return(b||new C).copy(a).clamp(this.min,this.max)},distanceToPoint:function(){var a=new C;return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),intersect:function(a){this.min.max(a.min);
16965 this.max.min(a.max);return this},union:function(a){this.min.min(a.min);this.max.max(a.max);return this},translate:function(a){this.min.add(a);this.max.add(a);return this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)}});tc.prototype=Object.create(ea.prototype);tc.prototype.constructor=tc;var Lf=0;Object.assign(Q.prototype,ja.prototype,{isMaterial:!0,onBeforeCompile:function(){},setValues:function(a){if(void 0!==a)for(var b in a){var c=a[b];if(void 0===c)console.warn("THREE.Material: '"+
16966 b+"' parameter is undefined.");else if("shading"===b)console.warn("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead."),this.flatShading=1===c?!0:!1;else{var d=this[b];void 0===d?console.warn("THREE."+this.type+": '"+b+"' is not a property of this material."):d&&d.isColor?d.set(c):d&&d.isVector3&&c&&c.isVector3?d.copy(c):this[b]="overdraw"===b?Number(c):c}}},toJSON:function(a){function b(a){var b=[],c;for(c in a){var d=a[c];delete d.metadata;b.push(d)}return b}var c=
16967 void 0===a||"string"===typeof a;c&&(a={textures:{},images:{}});var d={metadata:{version:4.5,type:"Material",generator:"Material.toJSON"}};d.uuid=this.uuid;d.type=this.type;""!==this.name&&(d.name=this.name);this.color&&this.color.isColor&&(d.color=this.color.getHex());void 0!==this.roughness&&(d.roughness=this.roughness);void 0!==this.metalness&&(d.metalness=this.metalness);this.emissive&&this.emissive.isColor&&(d.emissive=this.emissive.getHex());1!==this.emissiveIntensity&&(d.emissiveIntensity=this.emissiveIntensity);
16968 this.specular&&this.specular.isColor&&(d.specular=this.specular.getHex());void 0!==this.shininess&&(d.shininess=this.shininess);void 0!==this.clearCoat&&(d.clearCoat=this.clearCoat);void 0!==this.clearCoatRoughness&&(d.clearCoatRoughness=this.clearCoatRoughness);this.map&&this.map.isTexture&&(d.map=this.map.toJSON(a).uuid);this.alphaMap&&this.alphaMap.isTexture&&(d.alphaMap=this.alphaMap.toJSON(a).uuid);this.lightMap&&this.lightMap.isTexture&&(d.lightMap=this.lightMap.toJSON(a).uuid);this.bumpMap&&
16969 this.bumpMap.isTexture&&(d.bumpMap=this.bumpMap.toJSON(a).uuid,d.bumpScale=this.bumpScale);this.normalMap&&this.normalMap.isTexture&&(d.normalMap=this.normalMap.toJSON(a).uuid,d.normalScale=this.normalScale.toArray());this.displacementMap&&this.displacementMap.isTexture&&(d.displacementMap=this.displacementMap.toJSON(a).uuid,d.displacementScale=this.displacementScale,d.displacementBias=this.displacementBias);this.roughnessMap&&this.roughnessMap.isTexture&&(d.roughnessMap=this.roughnessMap.toJSON(a).uuid);
16970 this.metalnessMap&&this.metalnessMap.isTexture&&(d.metalnessMap=this.metalnessMap.toJSON(a).uuid);this.emissiveMap&&this.emissiveMap.isTexture&&(d.emissiveMap=this.emissiveMap.toJSON(a).uuid);this.specularMap&&this.specularMap.isTexture&&(d.specularMap=this.specularMap.toJSON(a).uuid);this.envMap&&this.envMap.isTexture&&(d.envMap=this.envMap.toJSON(a).uuid,d.reflectivity=this.reflectivity);this.gradientMap&&this.gradientMap.isTexture&&(d.gradientMap=this.gradientMap.toJSON(a).uuid);void 0!==this.size&&
16971 (d.size=this.size);void 0!==this.sizeAttenuation&&(d.sizeAttenuation=this.sizeAttenuation);1!==this.blending&&(d.blending=this.blending);!0===this.flatShading&&(d.flatShading=this.flatShading);0!==this.side&&(d.side=this.side);0!==this.vertexColors&&(d.vertexColors=this.vertexColors);1>this.opacity&&(d.opacity=this.opacity);!0===this.transparent&&(d.transparent=this.transparent);d.depthFunc=this.depthFunc;d.depthTest=this.depthTest;d.depthWrite=this.depthWrite;0!==this.rotation&&(d.rotation=this.rotation);
16972 1!==this.linewidth&&(d.linewidth=this.linewidth);void 0!==this.dashSize&&(d.dashSize=this.dashSize);void 0!==this.gapSize&&(d.gapSize=this.gapSize);void 0!==this.scale&&(d.scale=this.scale);!0===this.dithering&&(d.dithering=!0);0<this.alphaTest&&(d.alphaTest=this.alphaTest);!0===this.premultipliedAlpha&&(d.premultipliedAlpha=this.premultipliedAlpha);!0===this.wireframe&&(d.wireframe=this.wireframe);1<this.wireframeLinewidth&&(d.wireframeLinewidth=this.wireframeLinewidth);"round"!==this.wireframeLinecap&&
16973 (d.wireframeLinecap=this.wireframeLinecap);"round"!==this.wireframeLinejoin&&(d.wireframeLinejoin=this.wireframeLinejoin);!0===this.morphTargets&&(d.morphTargets=!0);!0===this.skinning&&(d.skinning=!0);!1===this.visible&&(d.visible=!1);"{}"!==JSON.stringify(this.userData)&&(d.userData=this.userData);c&&(c=b(a.textures),a=b(a.images),0<c.length&&(d.textures=c),0<a.length&&(d.images=a));return d},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.name=a.name;this.fog=a.fog;
16974 this.lights=a.lights;this.blending=a.blending;this.side=a.side;this.flatShading=a.flatShading;this.vertexColors=a.vertexColors;this.opacity=a.opacity;this.transparent=a.transparent;this.blendSrc=a.blendSrc;this.blendDst=a.blendDst;this.blendEquation=a.blendEquation;this.blendSrcAlpha=a.blendSrcAlpha;this.blendDstAlpha=a.blendDstAlpha;this.blendEquationAlpha=a.blendEquationAlpha;this.depthFunc=a.depthFunc;this.depthTest=a.depthTest;this.depthWrite=a.depthWrite;this.colorWrite=a.colorWrite;this.precision=
16975 a.precision;this.polygonOffset=a.polygonOffset;this.polygonOffsetFactor=a.polygonOffsetFactor;this.polygonOffsetUnits=a.polygonOffsetUnits;this.dithering=a.dithering;this.alphaTest=a.alphaTest;this.premultipliedAlpha=a.premultipliedAlpha;this.overdraw=a.overdraw;this.visible=a.visible;this.userData=JSON.parse(JSON.stringify(a.userData));this.clipShadows=a.clipShadows;this.clipIntersection=a.clipIntersection;a=a.clippingPlanes;var b=null;if(null!==a)for(var c=a.length,b=Array(c),d=0;d!==c;++d)b[d]=
16976 a[d].clone();this.clippingPlanes=b;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Wa.prototype=Object.create(Q.prototype);Wa.prototype.constructor=Wa;Wa.prototype.isMeshDepthMaterial=!0;Wa.prototype.copy=function(a){Q.prototype.copy.call(this,a);this.depthPacking=a.depthPacking;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.map=a.map;this.alphaMap=a.alphaMap;this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=
16977 a.displacementBias;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;return this};Xa.prototype=Object.create(Q.prototype);Xa.prototype.constructor=Xa;Xa.prototype.isMeshDistanceMaterial=!0;Xa.prototype.copy=function(a){Q.prototype.copy.call(this,a);this.referencePosition.copy(a.referencePosition);this.nearDistance=a.nearDistance;this.farDistance=a.farDistance;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.map=a.map;this.alphaMap=a.alphaMap;this.displacementMap=
16978 a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;return this};Object.assign(Oa.prototype,{isBox3:!0,set:function(a,b){this.min.copy(a);this.max.copy(b);return this},setFromArray:function(a){for(var b=Infinity,c=Infinity,d=Infinity,e=-Infinity,f=-Infinity,g=-Infinity,h=0,k=a.length;h<k;h+=3){var l=a[h],q=a[h+1],n=a[h+2];l<b&&(b=l);q<c&&(c=q);n<d&&(d=n);l>e&&(e=l);q>f&&(f=q);n>g&&(g=n)}this.min.set(b,c,d);this.max.set(e,f,g);return this},setFromBufferAttribute:function(a){for(var b=
16979 Infinity,c=Infinity,d=Infinity,e=-Infinity,f=-Infinity,g=-Infinity,h=0,k=a.count;h<k;h++){var l=a.getX(h),q=a.getY(h),n=a.getZ(h);l<b&&(b=l);q<c&&(c=q);n<d&&(d=n);l>e&&(e=l);q>f&&(f=q);n>g&&(g=n)}this.min.set(b,c,d);this.max.set(e,f,g);return this},setFromPoints:function(a){this.makeEmpty();for(var b=0,c=a.length;b<c;b++)this.expandByPoint(a[b]);return this},setFromCenterAndSize:function(){var a=new p;return function(b,c){c=a.copy(c).multiplyScalar(.5);this.min.copy(b).sub(c);this.max.copy(b).add(c);
16980 return this}}(),setFromObject:function(a){this.makeEmpty();return this.expandByObject(a)},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.min.copy(a.min);this.max.copy(a.max);return this},makeEmpty:function(){this.min.x=this.min.y=this.min.z=Infinity;this.max.x=this.max.y=this.max.z=-Infinity;return this},isEmpty:function(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z},getCenter:function(a){a=a||new p;return this.isEmpty()?a.set(0,0,0):
16981 a.addVectors(this.min,this.max).multiplyScalar(.5)},getSize:function(a){a=a||new p;return this.isEmpty()?a.set(0,0,0):a.subVectors(this.max,this.min)},expandByPoint:function(a){this.min.min(a);this.max.max(a);return this},expandByVector:function(a){this.min.sub(a);this.max.add(a);return this},expandByScalar:function(a){this.min.addScalar(-a);this.max.addScalar(a);return this},expandByObject:function(){function a(a){var f=a.geometry;if(void 0!==f)if(f.isGeometry)for(f=f.vertices,c=0,d=f.length;c<d;c++)e.copy(f[c]),
16982 e.applyMatrix4(a.matrixWorld),b.expandByPoint(e);else if(f.isBufferGeometry&&(f=f.attributes.position,void 0!==f))for(c=0,d=f.count;c<d;c++)e.fromBufferAttribute(f,c).applyMatrix4(a.matrixWorld),b.expandByPoint(e)}var b,c,d,e=new p;return function(c){b=this;c.updateMatrixWorld(!0);c.traverse(a);return this}}(),containsPoint:function(a){return a.x<this.min.x||a.x>this.max.x||a.y<this.min.y||a.y>this.max.y||a.z<this.min.z||a.z>this.max.z?!1:!0},containsBox:function(a){return this.min.x<=a.min.x&&a.max.x<=
16983 this.max.x&&this.min.y<=a.min.y&&a.max.y<=this.max.y&&this.min.z<=a.min.z&&a.max.z<=this.max.z},getParameter:function(a,b){return(b||new p).set((a.x-this.min.x)/(this.max.x-this.min.x),(a.y-this.min.y)/(this.max.y-this.min.y),(a.z-this.min.z)/(this.max.z-this.min.z))},intersectsBox:function(a){return a.max.x<this.min.x||a.min.x>this.max.x||a.max.y<this.min.y||a.min.y>this.max.y||a.max.z<this.min.z||a.min.z>this.max.z?!1:!0},intersectsSphere:function(){var a=new p;return function(b){this.clampPoint(b.center,
16984 a);return a.distanceToSquared(b.center)<=b.radius*b.radius}}(),intersectsPlane:function(a){if(0<a.normal.x){var b=a.normal.x*this.min.x;var c=a.normal.x*this.max.x}else b=a.normal.x*this.max.x,c=a.normal.x*this.min.x;0<a.normal.y?(b+=a.normal.y*this.min.y,c+=a.normal.y*this.max.y):(b+=a.normal.y*this.max.y,c+=a.normal.y*this.min.y);0<a.normal.z?(b+=a.normal.z*this.min.z,c+=a.normal.z*this.max.z):(b+=a.normal.z*this.max.z,c+=a.normal.z*this.min.z);return b<=a.constant&&c>=a.constant},clampPoint:function(a,
16985 b){return(b||new p).copy(a).clamp(this.min,this.max)},distanceToPoint:function(){var a=new p;return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),getBoundingSphere:function(){var a=new p;return function(b){b=b||new Da;this.getCenter(b.center);b.radius=.5*this.getSize(a).length();return b}}(),intersect:function(a){this.min.max(a.min);this.max.min(a.max);this.isEmpty()&&this.makeEmpty();return this},union:function(a){this.min.min(a.min);this.max.max(a.max);return this},applyMatrix4:function(){var a=
16986 [new p,new p,new p,new p,new p,new p,new p,new p];return function(b){if(this.isEmpty())return this;a[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(b);a[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(b);a[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(b);a[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(b);a[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(b);a[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(b);a[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(b);
16987 a[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(b);this.setFromPoints(a);return this}}(),translate:function(a){this.min.add(a);this.max.add(a);return this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)}});Object.assign(Da.prototype,{set:function(a,b){this.center.copy(a);this.radius=b;return this},setFromPoints:function(){var a=new Oa;return function(b,c){var d=this.center;void 0!==c?d.copy(c):a.setFromPoints(b).getCenter(d);for(var e=c=0,f=b.length;e<f;e++)c=Math.max(c,
16988 d.distanceToSquared(b[e]));this.radius=Math.sqrt(c);return this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.center.copy(a.center);this.radius=a.radius;return this},empty:function(){return 0>=this.radius},containsPoint:function(a){return a.distanceToSquared(this.center)<=this.radius*this.radius},distanceToPoint:function(a){return a.distanceTo(this.center)-this.radius},intersectsSphere:function(a){var b=this.radius+a.radius;return a.center.distanceToSquared(this.center)<=
16989 b*b},intersectsBox:function(a){return a.intersectsSphere(this)},intersectsPlane:function(a){return Math.abs(a.distanceToPoint(this.center))<=this.radius},clampPoint:function(a,b){var c=this.center.distanceToSquared(a);b=b||new p;b.copy(a);c>this.radius*this.radius&&(b.sub(this.center).normalize(),b.multiplyScalar(this.radius).add(this.center));return b},getBoundingBox:function(a){a=a||new Oa;a.set(this.center,this.center);a.expandByScalar(this.radius);return a},applyMatrix4:function(a){this.center.applyMatrix4(a);
16990 this.radius*=a.getMaxScaleOnAxis();return this},translate:function(a){this.center.add(a);return this},equals:function(a){return a.center.equals(this.center)&&a.radius===this.radius}});Object.assign(Aa.prototype,{set:function(a,b){this.normal.copy(a);this.constant=b;return this},setComponents:function(a,b,c,d){this.normal.set(a,b,c);this.constant=d;return this},setFromNormalAndCoplanarPoint:function(a,b){this.normal.copy(a);this.constant=-b.dot(this.normal);return this},setFromCoplanarPoints:function(){var a=
16991 new p,b=new p;return function(c,d,e){d=a.subVectors(e,d).cross(b.subVectors(c,d)).normalize();this.setFromNormalAndCoplanarPoint(d,c);return this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.normal.copy(a.normal);this.constant=a.constant;return this},normalize:function(){var a=1/this.normal.length();this.normal.multiplyScalar(a);this.constant*=a;return this},negate:function(){this.constant*=-1;this.normal.negate();return this},distanceToPoint:function(a){return this.normal.dot(a)+
16992 this.constant},distanceToSphere:function(a){return this.distanceToPoint(a.center)-a.radius},projectPoint:function(a,b){return(b||new p).copy(this.normal).multiplyScalar(-this.distanceToPoint(a)).add(a)},intersectLine:function(){var a=new p;return function(b,c){c=c||new p;var d=b.delta(a),e=this.normal.dot(d);if(0===e){if(0===this.distanceToPoint(b.start))return c.copy(b.start)}else if(e=-(b.start.dot(this.normal)+this.constant)/e,!(0>e||1<e))return c.copy(d).multiplyScalar(e).add(b.start)}}(),intersectsLine:function(a){var b=
16993 this.distanceToPoint(a.start);a=this.distanceToPoint(a.end);return 0>b&&0<a||0>a&&0<b},intersectsBox:function(a){return a.intersectsPlane(this)},intersectsSphere:function(a){return a.intersectsPlane(this)},coplanarPoint:function(a){return(a||new p).copy(this.normal).multiplyScalar(-this.constant)},applyMatrix4:function(){var a=new p,b=new ra;return function(c,d){d=d||b.getNormalMatrix(c);c=this.coplanarPoint(a).applyMatrix4(c);d=this.normal.applyMatrix3(d).normalize();this.constant=-c.dot(d);return this}}(),
16994 translate:function(a){this.constant-=a.dot(this.normal);return this},equals:function(a){return a.normal.equals(this.normal)&&a.constant===this.constant}});Object.assign(ld.prototype,{set:function(a,b,c,d,e,f){var g=this.planes;g[0].copy(a);g[1].copy(b);g[2].copy(c);g[3].copy(d);g[4].copy(e);g[5].copy(f);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){for(var b=this.planes,c=0;6>c;c++)b[c].copy(a.planes[c]);return this},setFromMatrix:function(a){var b=this.planes,
16995 c=a.elements;a=c[0];var d=c[1],e=c[2],f=c[3],g=c[4],h=c[5],k=c[6],l=c[7],q=c[8],n=c[9],m=c[10],r=c[11],p=c[12],v=c[13],w=c[14],c=c[15];b[0].setComponents(f-a,l-g,r-q,c-p).normalize();b[1].setComponents(f+a,l+g,r+q,c+p).normalize();b[2].setComponents(f+d,l+h,r+n,c+v).normalize();b[3].setComponents(f-d,l-h,r-n,c-v).normalize();b[4].setComponents(f-e,l-k,r-m,c-w).normalize();b[5].setComponents(f+e,l+k,r+m,c+w).normalize();return this},intersectsObject:function(){var a=new Da;return function(b){var c=
16996 b.geometry;null===c.boundingSphere&&c.computeBoundingSphere();a.copy(c.boundingSphere).applyMatrix4(b.matrixWorld);return this.intersectsSphere(a)}}(),intersectsSprite:function(){var a=new Da;return function(b){a.center.set(0,0,0);a.radius=.7071067811865476;a.applyMatrix4(b.matrixWorld);return this.intersectsSphere(a)}}(),intersectsSphere:function(a){var b=this.planes,c=a.center;a=-a.radius;for(var d=0;6>d;d++)if(b[d].distanceToPoint(c)<a)return!1;return!0},intersectsBox:function(){var a=new p,b=
16997 new p;return function(c){for(var d=this.planes,e=0;6>e;e++){var f=d[e];a.x=0<f.normal.x?c.min.x:c.max.x;b.x=0<f.normal.x?c.max.x:c.min.x;a.y=0<f.normal.y?c.min.y:c.max.y;b.y=0<f.normal.y?c.max.y:c.min.y;a.z=0<f.normal.z?c.min.z:c.max.z;b.z=0<f.normal.z?c.max.z:c.min.z;var g=f.distanceToPoint(a),f=f.distanceToPoint(b);if(0>g&&0>f)return!1}return!0}}(),containsPoint:function(a){for(var b=this.planes,c=0;6>c;c++)if(0>b[c].distanceToPoint(a))return!1;return!0}});Ya.RotationOrders="XYZ YZX ZXY XZY YXZ ZYX".split(" ");
16998 Ya.DefaultOrder="XYZ";Object.defineProperties(Ya.prototype,{x:{get:function(){return this._x},set:function(a){this._x=a;this.onChangeCallback()}},y:{get:function(){return this._y},set:function(a){this._y=a;this.onChangeCallback()}},z:{get:function(){return this._z},set:function(a){this._z=a;this.onChangeCallback()}},order:{get:function(){return this._order},set:function(a){this._order=a;this.onChangeCallback()}}});Object.assign(Ya.prototype,{isEuler:!0,set:function(a,b,c,d){this._x=a;this._y=b;this._z=
16999 c;this._order=d||this._order;this.onChangeCallback();return this},clone:function(){return new this.constructor(this._x,this._y,this._z,this._order)},copy:function(a){this._x=a._x;this._y=a._y;this._z=a._z;this._order=a._order;this.onChangeCallback();return this},setFromRotationMatrix:function(a,b,c){var d=R.clamp,e=a.elements;a=e[0];var f=e[4],g=e[8],h=e[1],k=e[5],l=e[9],q=e[2],n=e[6],e=e[10];b=b||this._order;"XYZ"===b?(this._y=Math.asin(d(g,-1,1)),.99999>Math.abs(g)?(this._x=Math.atan2(-l,e),this._z=
17000 Math.atan2(-f,a)):(this._x=Math.atan2(n,k),this._z=0)):"YXZ"===b?(this._x=Math.asin(-d(l,-1,1)),.99999>Math.abs(l)?(this._y=Math.atan2(g,e),this._z=Math.atan2(h,k)):(this._y=Math.atan2(-q,a),this._z=0)):"ZXY"===b?(this._x=Math.asin(d(n,-1,1)),.99999>Math.abs(n)?(this._y=Math.atan2(-q,e),this._z=Math.atan2(-f,k)):(this._y=0,this._z=Math.atan2(h,a))):"ZYX"===b?(this._y=Math.asin(-d(q,-1,1)),.99999>Math.abs(q)?(this._x=Math.atan2(n,e),this._z=Math.atan2(h,a)):(this._x=0,this._z=Math.atan2(-f,k))):"YZX"===
17001 b?(this._z=Math.asin(d(h,-1,1)),.99999>Math.abs(h)?(this._x=Math.atan2(-l,k),this._y=Math.atan2(-q,a)):(this._x=0,this._y=Math.atan2(g,e))):"XZY"===b?(this._z=Math.asin(-d(f,-1,1)),.99999>Math.abs(f)?(this._x=Math.atan2(n,k),this._y=Math.atan2(g,a)):(this._x=Math.atan2(-l,e),this._y=0)):console.warn("THREE.Euler: .setFromRotationMatrix() given unsupported order: "+b);this._order=b;if(!1!==c)this.onChangeCallback();return this},setFromQuaternion:function(){var a=new K;return function(b,c,d){a.makeRotationFromQuaternion(b);
17002 return this.setFromRotationMatrix(a,c,d)}}(),setFromVector3:function(a,b){return this.set(a.x,a.y,a.z,b||this._order)},reorder:function(){var a=new Z;return function(b){a.setFromEuler(this);return this.setFromQuaternion(a,b)}}(),equals:function(a){return a._x===this._x&&a._y===this._y&&a._z===this._z&&a._order===this._order},fromArray:function(a){this._x=a[0];this._y=a[1];this._z=a[2];void 0!==a[3]&&(this._order=a[3]);this.onChangeCallback();return this},toArray:function(a,b){void 0===a&&(a=[]);void 0===
17003 b&&(b=0);a[b]=this._x;a[b+1]=this._y;a[b+2]=this._z;a[b+3]=this._order;return a},toVector3:function(a){return a?a.set(this._x,this._y,this._z):new p(this._x,this._y,this._z)},onChange:function(a){this.onChangeCallback=a;return this},onChangeCallback:function(){}});Object.assign(Pd.prototype,{set:function(a){this.mask=1<<a|0},enable:function(a){this.mask=this.mask|1<<a|0},toggle:function(a){this.mask^=1<<a|0},disable:function(a){this.mask&=~(1<<a|0)},test:function(a){return 0!==(this.mask&a.mask)}});
17004 var Nf=0;A.DefaultUp=new p(0,1,0);A.DefaultMatrixAutoUpdate=!0;Object.assign(A.prototype,ja.prototype,{isObject3D:!0,onBeforeRender:function(){},onAfterRender:function(){},applyMatrix:function(a){this.matrix.multiplyMatrices(a,this.matrix);this.matrix.decompose(this.position,this.quaternion,this.scale)},applyQuaternion:function(a){this.quaternion.premultiply(a);return this},setRotationFromAxisAngle:function(a,b){this.quaternion.setFromAxisAngle(a,b)},setRotationFromEuler:function(a){this.quaternion.setFromEuler(a,
17005 !0)},setRotationFromMatrix:function(a){this.quaternion.setFromRotationMatrix(a)},setRotationFromQuaternion:function(a){this.quaternion.copy(a)},rotateOnAxis:function(){var a=new Z;return function(b,c){a.setFromAxisAngle(b,c);this.quaternion.multiply(a);return this}}(),rotateOnWorldAxis:function(){var a=new Z;return function(b,c){a.setFromAxisAngle(b,c);this.quaternion.premultiply(a);return this}}(),rotateX:function(){var a=new p(1,0,0);return function(b){return this.rotateOnAxis(a,b)}}(),rotateY:function(){var a=
17006 new p(0,1,0);return function(b){return this.rotateOnAxis(a,b)}}(),rotateZ:function(){var a=new p(0,0,1);return function(b){return this.rotateOnAxis(a,b)}}(),translateOnAxis:function(){var a=new p;return function(b,c){a.copy(b).applyQuaternion(this.quaternion);this.position.add(a.multiplyScalar(c));return this}}(),translateX:function(){var a=new p(1,0,0);return function(b){return this.translateOnAxis(a,b)}}(),translateY:function(){var a=new p(0,1,0);return function(b){return this.translateOnAxis(a,
17007 b)}}(),translateZ:function(){var a=new p(0,0,1);return function(b){return this.translateOnAxis(a,b)}}(),localToWorld:function(a){return a.applyMatrix4(this.matrixWorld)},worldToLocal:function(){var a=new K;return function(b){return b.applyMatrix4(a.getInverse(this.matrixWorld))}}(),lookAt:function(){var a=new K,b=new p;return function(c,d,e){c.isVector3?b.copy(c):b.set(c,d,e);this.isCamera?a.lookAt(this.position,b,this.up):a.lookAt(b,this.position,this.up);this.quaternion.setFromRotationMatrix(a)}}(),
17008 add:function(a){if(1<arguments.length){for(var b=0;b<arguments.length;b++)this.add(arguments[b]);return this}if(a===this)return console.error("THREE.Object3D.add: object can't be added as a child of itself.",a),this;a&&a.isObject3D?(null!==a.parent&&a.parent.remove(a),a.parent=this,a.dispatchEvent({type:"added"}),this.children.push(a)):console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.",a);return this},remove:function(a){if(1<arguments.length){for(var b=0;b<arguments.length;b++)this.remove(arguments[b]);
17009 return this}b=this.children.indexOf(a);-1!==b&&(a.parent=null,a.dispatchEvent({type:"removed"}),this.children.splice(b,1));return this},getObjectById:function(a){return this.getObjectByProperty("id",a)},getObjectByName:function(a){return this.getObjectByProperty("name",a)},getObjectByProperty:function(a,b){if(this[a]===b)return this;for(var c=0,d=this.children.length;c<d;c++){var e=this.children[c].getObjectByProperty(a,b);if(void 0!==e)return e}},getWorldPosition:function(a){a=a||new p;this.updateMatrixWorld(!0);
17010 return a.setFromMatrixPosition(this.matrixWorld)},getWorldQuaternion:function(){var a=new p,b=new p;return function(c){c=c||new Z;this.updateMatrixWorld(!0);this.matrixWorld.decompose(a,c,b);return c}}(),getWorldRotation:function(){var a=new Z;return function(b){b=b||new Ya;this.getWorldQuaternion(a);return b.setFromQuaternion(a,this.rotation.order,!1)}}(),getWorldScale:function(){var a=new p,b=new Z;return function(c){c=c||new p;this.updateMatrixWorld(!0);this.matrixWorld.decompose(a,b,c);return c}}(),
17011 getWorldDirection:function(){var a=new Z;return function(b){b=b||new p;this.getWorldQuaternion(a);return b.set(0,0,1).applyQuaternion(a)}}(),raycast:function(){},traverse:function(a){a(this);for(var b=this.children,c=0,d=b.length;c<d;c++)b[c].traverse(a)},traverseVisible:function(a){if(!1!==this.visible){a(this);for(var b=this.children,c=0,d=b.length;c<d;c++)b[c].traverseVisible(a)}},traverseAncestors:function(a){var b=this.parent;null!==b&&(a(b),b.traverseAncestors(a))},updateMatrix:function(){this.matrix.compose(this.position,
17012 this.quaternion,this.scale);this.matrixWorldNeedsUpdate=!0},updateMatrixWorld:function(a){this.matrixAutoUpdate&&this.updateMatrix();if(this.matrixWorldNeedsUpdate||a)null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix),this.matrixWorldNeedsUpdate=!1,a=!0;for(var b=this.children,c=0,d=b.length;c<d;c++)b[c].updateMatrixWorld(a)},toJSON:function(a){function b(b,c){void 0===b[c.uuid]&&(b[c.uuid]=c.toJSON(a));return c.uuid}function c(a){var b=
17013 [],c;for(c in a){var d=a[c];delete d.metadata;b.push(d)}return b}var d=void 0===a||"string"===typeof a,e={};d&&(a={geometries:{},materials:{},textures:{},images:{}},e.metadata={version:4.5,type:"Object",generator:"Object3D.toJSON"});var f={};f.uuid=this.uuid;f.type=this.type;""!==this.name&&(f.name=this.name);!0===this.castShadow&&(f.castShadow=!0);!0===this.receiveShadow&&(f.receiveShadow=!0);!1===this.visible&&(f.visible=!1);"{}"!==JSON.stringify(this.userData)&&(f.userData=this.userData);f.matrix=
17014 this.matrix.toArray();void 0!==this.geometry&&(f.geometry=b(a.geometries,this.geometry));if(void 0!==this.material)if(Array.isArray(this.material)){for(var g=[],h=0,k=this.material.length;h<k;h++)g.push(b(a.materials,this.material[h]));f.material=g}else f.material=b(a.materials,this.material);if(0<this.children.length)for(f.children=[],h=0;h<this.children.length;h++)f.children.push(this.children[h].toJSON(a).object);d&&(d=c(a.geometries),g=c(a.materials),h=c(a.textures),k=c(a.images),0<d.length&&
17015 (e.geometries=d),0<g.length&&(e.materials=g),0<h.length&&(e.textures=h),0<k.length&&(e.images=k));e.object=f;return e},clone:function(a){return(new this.constructor).copy(this,a)},copy:function(a,b){void 0===b&&(b=!0);this.name=a.name;this.up.copy(a.up);this.position.copy(a.position);this.quaternion.copy(a.quaternion);this.scale.copy(a.scale);this.matrix.copy(a.matrix);this.matrixWorld.copy(a.matrixWorld);this.matrixAutoUpdate=a.matrixAutoUpdate;this.matrixWorldNeedsUpdate=a.matrixWorldNeedsUpdate;
17016 this.layers.mask=a.layers.mask;this.visible=a.visible;this.castShadow=a.castShadow;this.receiveShadow=a.receiveShadow;this.frustumCulled=a.frustumCulled;this.renderOrder=a.renderOrder;this.userData=JSON.parse(JSON.stringify(a.userData));if(!0===b)for(b=0;b<a.children.length;b++)this.add(a.children[b].clone());return this}});La.prototype=Object.assign(Object.create(A.prototype),{constructor:La,isCamera:!0,copy:function(a,b){A.prototype.copy.call(this,a,b);this.matrixWorldInverse.copy(a.matrixWorldInverse);
17017 this.projectionMatrix.copy(a.projectionMatrix);return this},getWorldDirection:function(){var a=new Z;return function(b){b=b||new p;this.getWorldQuaternion(a);return b.set(0,0,-1).applyQuaternion(a)}}(),updateMatrixWorld:function(a){A.prototype.updateMatrixWorld.call(this,a);this.matrixWorldInverse.getInverse(this.matrixWorld)},clone:function(){return(new this.constructor).copy(this)}});Kb.prototype=Object.assign(Object.create(La.prototype),{constructor:Kb,isOrthographicCamera:!0,copy:function(a,b){La.prototype.copy.call(this,
17018 a,b);this.left=a.left;this.right=a.right;this.top=a.top;this.bottom=a.bottom;this.near=a.near;this.far=a.far;this.zoom=a.zoom;this.view=null===a.view?null:Object.assign({},a.view);return this},setViewOffset:function(a,b,c,d,e,f){null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1});this.view.enabled=!0;this.view.fullWidth=a;this.view.fullHeight=b;this.view.offsetX=c;this.view.offsetY=d;this.view.width=e;this.view.height=f;this.updateProjectionMatrix()},
17019 clearViewOffset:function(){null!==this.view&&(this.view.enabled=!1);this.updateProjectionMatrix()},updateProjectionMatrix:function(){var a=(this.right-this.left)/(2*this.zoom),b=(this.top-this.bottom)/(2*this.zoom),c=(this.right+this.left)/2,d=(this.top+this.bottom)/2,e=c-a,c=c+a,a=d+b,b=d-b;if(null!==this.view&&this.view.enabled)var c=this.zoom/(this.view.width/this.view.fullWidth),b=this.zoom/(this.view.height/this.view.fullHeight),f=(this.right-this.left)/this.view.width,d=(this.top-this.bottom)/
17020 this.view.height,e=e+this.view.offsetX/c*f,c=e+this.view.width/c*f,a=a-this.view.offsetY/b*d,b=a-this.view.height/b*d;this.projectionMatrix.makeOrthographic(e,c,a,b,this.near,this.far)},toJSON:function(a){a=A.prototype.toJSON.call(this,a);a.object.zoom=this.zoom;a.object.left=this.left;a.object.right=this.right;a.object.top=this.top;a.object.bottom=this.bottom;a.object.near=this.near;a.object.far=this.far;null!==this.view&&(a.object.view=Object.assign({},this.view));return a}});Object.assign(Pa.prototype,
17021 {clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.a=a.a;this.b=a.b;this.c=a.c;this.normal.copy(a.normal);this.color.copy(a.color);this.materialIndex=a.materialIndex;for(var b=0,c=a.vertexNormals.length;b<c;b++)this.vertexNormals[b]=a.vertexNormals[b].clone();b=0;for(c=a.vertexColors.length;b<c;b++)this.vertexColors[b]=a.vertexColors[b].clone();return this}});var Of=0;Object.assign(N.prototype,ja.prototype,{isGeometry:!0,applyMatrix:function(a){for(var b=(new ra).getNormalMatrix(a),
17022 c=0,d=this.vertices.length;c<d;c++)this.vertices[c].applyMatrix4(a);c=0;for(d=this.faces.length;c<d;c++){a=this.faces[c];a.normal.applyMatrix3(b).normalize();for(var e=0,f=a.vertexNormals.length;e<f;e++)a.vertexNormals[e].applyMatrix3(b).normalize()}null!==this.boundingBox&&this.computeBoundingBox();null!==this.boundingSphere&&this.computeBoundingSphere();this.normalsNeedUpdate=this.verticesNeedUpdate=!0;return this},rotateX:function(){var a=new K;return function(b){a.makeRotationX(b);this.applyMatrix(a);
17023 return this}}(),rotateY:function(){var a=new K;return function(b){a.makeRotationY(b);this.applyMatrix(a);return this}}(),rotateZ:function(){var a=new K;return function(b){a.makeRotationZ(b);this.applyMatrix(a);return this}}(),translate:function(){var a=new K;return function(b,c,d){a.makeTranslation(b,c,d);this.applyMatrix(a);return this}}(),scale:function(){var a=new K;return function(b,c,d){a.makeScale(b,c,d);this.applyMatrix(a);return this}}(),lookAt:function(){var a=new A;return function(b){a.lookAt(b);
17024 a.updateMatrix();this.applyMatrix(a.matrix)}}(),fromBufferGeometry:function(a){function b(a,b,d,e){var f=void 0!==g?[q[a].clone(),q[b].clone(),q[d].clone()]:[],t=void 0!==h?[c.colors[a].clone(),c.colors[b].clone(),c.colors[d].clone()]:[];e=new Pa(a,b,d,f,t,e);c.faces.push(e);void 0!==k&&c.faceVertexUvs[0].push([n[a].clone(),n[b].clone(),n[d].clone()]);void 0!==l&&c.faceVertexUvs[1].push([m[a].clone(),m[b].clone(),m[d].clone()])}var c=this,d=null!==a.index?a.index.array:void 0,e=a.attributes,f=e.position.array,
17025 g=void 0!==e.normal?e.normal.array:void 0,h=void 0!==e.color?e.color.array:void 0,k=void 0!==e.uv?e.uv.array:void 0,l=void 0!==e.uv2?e.uv2.array:void 0;void 0!==l&&(this.faceVertexUvs[1]=[]);for(var q=[],n=[],m=[],r=e=0;e<f.length;e+=3,r+=2)c.vertices.push(new p(f[e],f[e+1],f[e+2])),void 0!==g&&q.push(new p(g[e],g[e+1],g[e+2])),void 0!==h&&c.colors.push(new H(h[e],h[e+1],h[e+2])),void 0!==k&&n.push(new C(k[r],k[r+1])),void 0!==l&&m.push(new C(l[r],l[r+1]));var u=a.groups;if(0<u.length)for(e=0;e<u.length;e++)for(var f=
17026 u[e],v=f.start,w=f.count,r=v,v=v+w;r<v;r+=3)void 0!==d?b(d[r],d[r+1],d[r+2],f.materialIndex):b(r,r+1,r+2,f.materialIndex);else if(void 0!==d)for(e=0;e<d.length;e+=3)b(d[e],d[e+1],d[e+2]);else for(e=0;e<f.length/3;e+=3)b(e,e+1,e+2);this.computeFaceNormals();null!==a.boundingBox&&(this.boundingBox=a.boundingBox.clone());null!==a.boundingSphere&&(this.boundingSphere=a.boundingSphere.clone());return this},center:function(){this.computeBoundingBox();var a=this.boundingBox.getCenter().negate();this.translate(a.x,
17027 a.y,a.z);return a},normalize:function(){this.computeBoundingSphere();var a=this.boundingSphere.center,b=this.boundingSphere.radius,b=0===b?1:1/b,c=new K;c.set(b,0,0,-b*a.x,0,b,0,-b*a.y,0,0,b,-b*a.z,0,0,0,1);this.applyMatrix(c);return this},computeFaceNormals:function(){for(var a=new p,b=new p,c=0,d=this.faces.length;c<d;c++){var e=this.faces[c],f=this.vertices[e.a],g=this.vertices[e.b];a.subVectors(this.vertices[e.c],g);b.subVectors(f,g);a.cross(b);a.normalize();e.normal.copy(a)}},computeVertexNormals:function(a){void 0===
17028 a&&(a=!0);var b;var c=Array(this.vertices.length);var d=0;for(b=this.vertices.length;d<b;d++)c[d]=new p;if(a){var e=new p,f=new p;a=0;for(d=this.faces.length;a<d;a++){b=this.faces[a];var g=this.vertices[b.a];var h=this.vertices[b.b];var k=this.vertices[b.c];e.subVectors(k,h);f.subVectors(g,h);e.cross(f);c[b.a].add(e);c[b.b].add(e);c[b.c].add(e)}}else for(this.computeFaceNormals(),a=0,d=this.faces.length;a<d;a++)b=this.faces[a],c[b.a].add(b.normal),c[b.b].add(b.normal),c[b.c].add(b.normal);d=0;for(b=
17029 this.vertices.length;d<b;d++)c[d].normalize();a=0;for(d=this.faces.length;a<d;a++)b=this.faces[a],g=b.vertexNormals,3===g.length?(g[0].copy(c[b.a]),g[1].copy(c[b.b]),g[2].copy(c[b.c])):(g[0]=c[b.a].clone(),g[1]=c[b.b].clone(),g[2]=c[b.c].clone());0<this.faces.length&&(this.normalsNeedUpdate=!0)},computeFlatVertexNormals:function(){var a;this.computeFaceNormals();var b=0;for(a=this.faces.length;b<a;b++){var c=this.faces[b];var d=c.vertexNormals;3===d.length?(d[0].copy(c.normal),d[1].copy(c.normal),
17030 d[2].copy(c.normal)):(d[0]=c.normal.clone(),d[1]=c.normal.clone(),d[2]=c.normal.clone())}0<this.faces.length&&(this.normalsNeedUpdate=!0)},computeMorphNormals:function(){var a,b;var c=0;for(b=this.faces.length;c<b;c++){var d=this.faces[c];d.__originalFaceNormal?d.__originalFaceNormal.copy(d.normal):d.__originalFaceNormal=d.normal.clone();d.__originalVertexNormals||(d.__originalVertexNormals=[]);var e=0;for(a=d.vertexNormals.length;e<a;e++)d.__originalVertexNormals[e]?d.__originalVertexNormals[e].copy(d.vertexNormals[e]):
17031 d.__originalVertexNormals[e]=d.vertexNormals[e].clone()}var f=new N;f.faces=this.faces;e=0;for(a=this.morphTargets.length;e<a;e++){if(!this.morphNormals[e]){this.morphNormals[e]={};this.morphNormals[e].faceNormals=[];this.morphNormals[e].vertexNormals=[];d=this.morphNormals[e].faceNormals;var g=this.morphNormals[e].vertexNormals;c=0;for(b=this.faces.length;c<b;c++){var h=new p;var k={a:new p,b:new p,c:new p};d.push(h);g.push(k)}}g=this.morphNormals[e];f.vertices=this.morphTargets[e].vertices;f.computeFaceNormals();
17032 f.computeVertexNormals();c=0;for(b=this.faces.length;c<b;c++)d=this.faces[c],h=g.faceNormals[c],k=g.vertexNormals[c],h.copy(d.normal),k.a.copy(d.vertexNormals[0]),k.b.copy(d.vertexNormals[1]),k.c.copy(d.vertexNormals[2])}c=0;for(b=this.faces.length;c<b;c++)d=this.faces[c],d.normal=d.__originalFaceNormal,d.vertexNormals=d.__originalVertexNormals},computeLineDistances:function(){for(var a=0,b=this.vertices,c=0,d=b.length;c<d;c++)0<c&&(a+=b[c].distanceTo(b[c-1])),this.lineDistances[c]=a},computeBoundingBox:function(){null===
17033 this.boundingBox&&(this.boundingBox=new Oa);this.boundingBox.setFromPoints(this.vertices)},computeBoundingSphere:function(){null===this.boundingSphere&&(this.boundingSphere=new Da);this.boundingSphere.setFromPoints(this.vertices)},merge:function(a,b,c){if(a&&a.isGeometry){var d,e=this.vertices.length,f=this.vertices,g=a.vertices,h=this.faces,k=a.faces,l=this.faceVertexUvs[0],q=a.faceVertexUvs[0],n=this.colors,m=a.colors;void 0===c&&(c=0);void 0!==b&&(d=(new ra).getNormalMatrix(b));a=0;for(var r=g.length;a<
17034 r;a++){var p=g[a].clone();void 0!==b&&p.applyMatrix4(b);f.push(p)}a=0;for(r=m.length;a<r;a++)n.push(m[a].clone());a=0;for(r=k.length;a<r;a++){var g=k[a],v=g.vertexNormals,m=g.vertexColors,n=new Pa(g.a+e,g.b+e,g.c+e);n.normal.copy(g.normal);void 0!==d&&n.normal.applyMatrix3(d).normalize();b=0;for(f=v.length;b<f;b++)p=v[b].clone(),void 0!==d&&p.applyMatrix3(d).normalize(),n.vertexNormals.push(p);n.color.copy(g.color);b=0;for(f=m.length;b<f;b++)p=m[b],n.vertexColors.push(p.clone());n.materialIndex=g.materialIndex+
17035 c;h.push(n)}a=0;for(r=q.length;a<r;a++)if(c=q[a],d=[],void 0!==c){b=0;for(f=c.length;b<f;b++)d.push(c[b].clone());l.push(d)}}else console.error("THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.",a)},mergeMesh:function(a){a&&a.isMesh?(a.matrixAutoUpdate&&a.updateMatrix(),this.merge(a.geometry,a.matrix)):console.error("THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.",a)},mergeVertices:function(){var a={},b=[],c=[],d=Math.pow(10,4),e;var f=0;for(e=this.vertices.length;f<
17036 e;f++){var g=this.vertices[f];g=Math.round(g.x*d)+"_"+Math.round(g.y*d)+"_"+Math.round(g.z*d);void 0===a[g]?(a[g]=f,b.push(this.vertices[f]),c[f]=b.length-1):c[f]=c[a[g]]}a=[];f=0;for(e=this.faces.length;f<e;f++)for(d=this.faces[f],d.a=c[d.a],d.b=c[d.b],d.c=c[d.c],d=[d.a,d.b,d.c],g=0;3>g;g++)if(d[g]===d[(g+1)%3]){a.push(f);break}for(f=a.length-1;0<=f;f--)for(d=a[f],this.faces.splice(d,1),c=0,e=this.faceVertexUvs.length;c<e;c++)this.faceVertexUvs[c].splice(d,1);f=this.vertices.length-b.length;this.vertices=
17037 b;return f},setFromPoints:function(a){this.vertices=[];for(var b=0,c=a.length;b<c;b++){var d=a[b];this.vertices.push(new p(d.x,d.y,d.z||0))}return this},sortFacesByMaterialIndex:function(){for(var a=this.faces,b=a.length,c=0;c<b;c++)a[c]._id=c;a.sort(function(a,b){return a.materialIndex-b.materialIndex});var d=this.faceVertexUvs[0],e=this.faceVertexUvs[1],f,g;d&&d.length===b&&(f=[]);e&&e.length===b&&(g=[]);for(c=0;c<b;c++){var h=a[c]._id;f&&f.push(d[h]);g&&g.push(e[h])}f&&(this.faceVertexUvs[0]=f);
17038 g&&(this.faceVertexUvs[1]=g)},toJSON:function(){function a(a,b,c){return c?a|1<<b:a&~(1<<b)}function b(a){var b=a.x.toString()+a.y.toString()+a.z.toString();if(void 0!==l[b])return l[b];l[b]=k.length/3;k.push(a.x,a.y,a.z);return l[b]}function c(a){var b=a.r.toString()+a.g.toString()+a.b.toString();if(void 0!==n[b])return n[b];n[b]=q.length;q.push(a.getHex());return n[b]}function d(a){var b=a.x.toString()+a.y.toString();if(void 0!==p[b])return p[b];p[b]=m.length/2;m.push(a.x,a.y);return p[b]}var e=
17039 {metadata:{version:4.5,type:"Geometry",generator:"Geometry.toJSON"}};e.uuid=this.uuid;e.type=this.type;""!==this.name&&(e.name=this.name);if(void 0!==this.parameters){var f=this.parameters,g;for(g in f)void 0!==f[g]&&(e[g]=f[g]);return e}f=[];for(g=0;g<this.vertices.length;g++){var h=this.vertices[g];f.push(h.x,h.y,h.z)}var h=[],k=[],l={},q=[],n={},m=[],p={};for(g=0;g<this.faces.length;g++){var u=this.faces[g],v=void 0!==this.faceVertexUvs[0][g],w=0<u.normal.length(),x=0<u.vertexNormals.length,z=
17040 1!==u.color.r||1!==u.color.g||1!==u.color.b,I=0<u.vertexColors.length,B=0,B=a(B,0,0),B=a(B,1,!0),B=a(B,2,!1),B=a(B,3,v),B=a(B,4,w),B=a(B,5,x),B=a(B,6,z),B=a(B,7,I);h.push(B);h.push(u.a,u.b,u.c);h.push(u.materialIndex);v&&(v=this.faceVertexUvs[0][g],h.push(d(v[0]),d(v[1]),d(v[2])));w&&h.push(b(u.normal));x&&(w=u.vertexNormals,h.push(b(w[0]),b(w[1]),b(w[2])));z&&h.push(c(u.color));I&&(u=u.vertexColors,h.push(c(u[0]),c(u[1]),c(u[2])))}e.data={};e.data.vertices=f;e.data.normals=k;0<q.length&&(e.data.colors=
17041 q);0<m.length&&(e.data.uvs=[m]);e.data.faces=h;return e},clone:function(){return(new N).copy(this)},copy:function(a){var b,c,d;this.vertices=[];this.colors=[];this.faces=[];this.faceVertexUvs=[[]];this.morphTargets=[];this.morphNormals=[];this.skinWeights=[];this.skinIndices=[];this.lineDistances=[];this.boundingSphere=this.boundingBox=null;this.name=a.name;var e=a.vertices;var f=0;for(b=e.length;f<b;f++)this.vertices.push(e[f].clone());e=a.colors;f=0;for(b=e.length;f<b;f++)this.colors.push(e[f].clone());
17042 e=a.faces;f=0;for(b=e.length;f<b;f++)this.faces.push(e[f].clone());f=0;for(b=a.faceVertexUvs.length;f<b;f++){var g=a.faceVertexUvs[f];void 0===this.faceVertexUvs[f]&&(this.faceVertexUvs[f]=[]);e=0;for(c=g.length;e<c;e++){var h=g[e],k=[];var l=0;for(d=h.length;l<d;l++)k.push(h[l].clone());this.faceVertexUvs[f].push(k)}}l=a.morphTargets;f=0;for(b=l.length;f<b;f++){d={};d.name=l[f].name;if(void 0!==l[f].vertices)for(d.vertices=[],e=0,c=l[f].vertices.length;e<c;e++)d.vertices.push(l[f].vertices[e].clone());
17043 if(void 0!==l[f].normals)for(d.normals=[],e=0,c=l[f].normals.length;e<c;e++)d.normals.push(l[f].normals[e].clone());this.morphTargets.push(d)}l=a.morphNormals;f=0;for(b=l.length;f<b;f++){d={};if(void 0!==l[f].vertexNormals)for(d.vertexNormals=[],e=0,c=l[f].vertexNormals.length;e<c;e++)g=l[f].vertexNormals[e],h={},h.a=g.a.clone(),h.b=g.b.clone(),h.c=g.c.clone(),d.vertexNormals.push(h);if(void 0!==l[f].faceNormals)for(d.faceNormals=[],e=0,c=l[f].faceNormals.length;e<c;e++)d.faceNormals.push(l[f].faceNormals[e].clone());
17044 this.morphNormals.push(d)}e=a.skinWeights;f=0;for(b=e.length;f<b;f++)this.skinWeights.push(e[f].clone());e=a.skinIndices;f=0;for(b=e.length;f<b;f++)this.skinIndices.push(e[f].clone());e=a.lineDistances;f=0;for(b=e.length;f<b;f++)this.lineDistances.push(e[f]);f=a.boundingBox;null!==f&&(this.boundingBox=f.clone());f=a.boundingSphere;null!==f&&(this.boundingSphere=f.clone());this.elementsNeedUpdate=a.elementsNeedUpdate;this.verticesNeedUpdate=a.verticesNeedUpdate;this.uvsNeedUpdate=a.uvsNeedUpdate;this.normalsNeedUpdate=
17045 a.normalsNeedUpdate;this.colorsNeedUpdate=a.colorsNeedUpdate;this.lineDistancesNeedUpdate=a.lineDistancesNeedUpdate;this.groupsNeedUpdate=a.groupsNeedUpdate;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Object.defineProperty(P.prototype,"needsUpdate",{set:function(a){!0===a&&this.version++}});Object.assign(P.prototype,{isBufferAttribute:!0,setArray:function(a){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.count=void 0!==
17046 a?a.length/this.itemSize:0;this.array=a},setDynamic:function(a){this.dynamic=a;return this},copy:function(a){this.array=new a.array.constructor(a.array);this.itemSize=a.itemSize;this.count=a.count;this.normalized=a.normalized;this.dynamic=a.dynamic;return this},copyAt:function(a,b,c){a*=this.itemSize;c*=b.itemSize;for(var d=0,e=this.itemSize;d<e;d++)this.array[a+d]=b.array[c+d];return this},copyArray:function(a){this.array.set(a);return this},copyColorsArray:function(a){for(var b=this.array,c=0,d=
17047 0,e=a.length;d<e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyColorsArray(): color is undefined",d),f=new H);b[c++]=f.r;b[c++]=f.g;b[c++]=f.b}return this},copyIndicesArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];b[c++]=f.a;b[c++]=f.b;b[c++]=f.c}return this},copyVector2sArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyVector2sArray(): vector is undefined",d),f=new C);
17048 b[c++]=f.x;b[c++]=f.y}return this},copyVector3sArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyVector3sArray(): vector is undefined",d),f=new p);b[c++]=f.x;b[c++]=f.y;b[c++]=f.z}return this},copyVector4sArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyVector4sArray(): vector is undefined",d),f=new da);b[c++]=f.x;b[c++]=f.y;b[c++]=f.z;
17049 b[c++]=f.w}return this},set:function(a,b){void 0===b&&(b=0);this.array.set(a,b);return this},getX:function(a){return this.array[a*this.itemSize]},setX:function(a,b){this.array[a*this.itemSize]=b;return this},getY:function(a){return this.array[a*this.itemSize+1]},setY:function(a,b){this.array[a*this.itemSize+1]=b;return this},getZ:function(a){return this.array[a*this.itemSize+2]},setZ:function(a,b){this.array[a*this.itemSize+2]=b;return this},getW:function(a){return this.array[a*this.itemSize+3]},
17050 setW:function(a,b){this.array[a*this.itemSize+3]=b;return this},setXY:function(a,b,c){a*=this.itemSize;this.array[a+0]=b;this.array[a+1]=c;return this},setXYZ:function(a,b,c,d){a*=this.itemSize;this.array[a+0]=b;this.array[a+1]=c;this.array[a+2]=d;return this},setXYZW:function(a,b,c,d,e){a*=this.itemSize;this.array[a+0]=b;this.array[a+1]=c;this.array[a+2]=d;this.array[a+3]=e;return this},onUpload:function(a){this.onUploadCallback=a;return this},clone:function(){return(new this.constructor(this.array,
17051 this.itemSize)).copy(this)}});uc.prototype=Object.create(P.prototype);uc.prototype.constructor=uc;vc.prototype=Object.create(P.prototype);vc.prototype.constructor=vc;wc.prototype=Object.create(P.prototype);wc.prototype.constructor=wc;xc.prototype=Object.create(P.prototype);xc.prototype.constructor=xc;hb.prototype=Object.create(P.prototype);hb.prototype.constructor=hb;yc.prototype=Object.create(P.prototype);yc.prototype.constructor=yc;ib.prototype=Object.create(P.prototype);ib.prototype.constructor=
17052 ib;y.prototype=Object.create(P.prototype);y.prototype.constructor=y;zc.prototype=Object.create(P.prototype);zc.prototype.constructor=zc;Object.assign(Je.prototype,{computeGroups:function(a){var b=[],c=void 0;a=a.faces;for(var d=0;d<a.length;d++){var e=a[d];if(e.materialIndex!==c){c=e.materialIndex;void 0!==f&&(f.count=3*d-f.start,b.push(f));var f={start:3*d,materialIndex:c}}}void 0!==f&&(f.count=3*d-f.start,b.push(f));this.groups=b},fromGeometry:function(a){var b=a.faces,c=a.vertices,d=a.faceVertexUvs,
17053 e=d[0]&&0<d[0].length,f=d[1]&&0<d[1].length,g=a.morphTargets,h=g.length;if(0<h){var k=[];for(var l=0;l<h;l++)k[l]=[];this.morphTargets.position=k}var q=a.morphNormals,n=q.length;if(0<n){var m=[];for(l=0;l<n;l++)m[l]=[];this.morphTargets.normal=m}for(var p=a.skinIndices,u=a.skinWeights,v=p.length===c.length,w=u.length===c.length,l=0;l<b.length;l++){var x=b[l];this.vertices.push(c[x.a],c[x.b],c[x.c]);var z=x.vertexNormals;3===z.length?this.normals.push(z[0],z[1],z[2]):(z=x.normal,this.normals.push(z,
17054 z,z));z=x.vertexColors;3===z.length?this.colors.push(z[0],z[1],z[2]):(z=x.color,this.colors.push(z,z,z));!0===e&&(z=d[0][l],void 0!==z?this.uvs.push(z[0],z[1],z[2]):(console.warn("THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ",l),this.uvs.push(new C,new C,new C)));!0===f&&(z=d[1][l],void 0!==z?this.uvs2.push(z[0],z[1],z[2]):(console.warn("THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ",l),this.uvs2.push(new C,new C,new C)));for(z=0;z<h;z++){var I=g[z].vertices;k[z].push(I[x.a],
17055 I[x.b],I[x.c])}for(z=0;z<n;z++)I=q[z].vertexNormals[l],m[z].push(I.a,I.b,I.c);v&&this.skinIndices.push(p[x.a],p[x.b],p[x.c]);w&&this.skinWeights.push(u[x.a],u[x.b],u[x.c])}this.computeGroups(a);this.verticesNeedUpdate=a.verticesNeedUpdate;this.normalsNeedUpdate=a.normalsNeedUpdate;this.colorsNeedUpdate=a.colorsNeedUpdate;this.uvsNeedUpdate=a.uvsNeedUpdate;this.groupsNeedUpdate=a.groupsNeedUpdate;return this}});var Pf=1;Object.assign(D.prototype,ja.prototype,{isBufferGeometry:!0,getIndex:function(){return this.index},
17056 setIndex:function(a){Array.isArray(a)?this.index=new (65535<Qd(a)?ib:hb)(a,1):this.index=a},addAttribute:function(a,b,c){if(b&&b.isBufferAttribute||b&&b.isInterleavedBufferAttribute)if("index"===a)console.warn("THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute."),this.setIndex(b);else return this.attributes[a]=b,this;else console.warn("THREE.BufferGeometry: .addAttribute() now expects ( name, attribute )."),this.addAttribute(a,new P(b,c))},getAttribute:function(a){return this.attributes[a]},
17057 removeAttribute:function(a){delete this.attributes[a];return this},addGroup:function(a,b,c){this.groups.push({start:a,count:b,materialIndex:void 0!==c?c:0})},clearGroups:function(){this.groups=[]},setDrawRange:function(a,b){this.drawRange.start=a;this.drawRange.count=b},applyMatrix:function(a){var b=this.attributes.position;void 0!==b&&(a.applyToBufferAttribute(b),b.needsUpdate=!0);b=this.attributes.normal;void 0!==b&&((new ra).getNormalMatrix(a).applyToBufferAttribute(b),b.needsUpdate=!0);null!==
17058 this.boundingBox&&this.computeBoundingBox();null!==this.boundingSphere&&this.computeBoundingSphere();return this},rotateX:function(){var a=new K;return function(b){a.makeRotationX(b);this.applyMatrix(a);return this}}(),rotateY:function(){var a=new K;return function(b){a.makeRotationY(b);this.applyMatrix(a);return this}}(),rotateZ:function(){var a=new K;return function(b){a.makeRotationZ(b);this.applyMatrix(a);return this}}(),translate:function(){var a=new K;return function(b,c,d){a.makeTranslation(b,
17059 c,d);this.applyMatrix(a);return this}}(),scale:function(){var a=new K;return function(b,c,d){a.makeScale(b,c,d);this.applyMatrix(a);return this}}(),lookAt:function(){var a=new A;return function(b){a.lookAt(b);a.updateMatrix();this.applyMatrix(a.matrix)}}(),center:function(){this.computeBoundingBox();var a=this.boundingBox.getCenter().negate();this.translate(a.x,a.y,a.z);return a},setFromObject:function(a){var b=a.geometry;if(a.isPoints||a.isLine){a=new y(3*b.vertices.length,3);var c=new y(3*b.colors.length,
17060 3);this.addAttribute("position",a.copyVector3sArray(b.vertices));this.addAttribute("color",c.copyColorsArray(b.colors));b.lineDistances&&b.lineDistances.length===b.vertices.length&&(a=new y(b.lineDistances.length,1),this.addAttribute("lineDistance",a.copyArray(b.lineDistances)));null!==b.boundingSphere&&(this.boundingSphere=b.boundingSphere.clone());null!==b.boundingBox&&(this.boundingBox=b.boundingBox.clone())}else a.isMesh&&b&&b.isGeometry&&this.fromGeometry(b);return this},setFromPoints:function(a){for(var b=
17061 [],c=0,d=a.length;c<d;c++){var e=a[c];b.push(e.x,e.y,e.z||0)}this.addAttribute("position",new y(b,3));return this},updateFromObject:function(a){var b=a.geometry;if(a.isMesh){var c=b.__directGeometry;!0===b.elementsNeedUpdate&&(c=void 0,b.elementsNeedUpdate=!1);if(void 0===c)return this.fromGeometry(b);c.verticesNeedUpdate=b.verticesNeedUpdate;c.normalsNeedUpdate=b.normalsNeedUpdate;c.colorsNeedUpdate=b.colorsNeedUpdate;c.uvsNeedUpdate=b.uvsNeedUpdate;c.groupsNeedUpdate=b.groupsNeedUpdate;b.verticesNeedUpdate=
17062 !1;b.normalsNeedUpdate=!1;b.colorsNeedUpdate=!1;b.uvsNeedUpdate=!1;b.groupsNeedUpdate=!1;b=c}!0===b.verticesNeedUpdate&&(c=this.attributes.position,void 0!==c&&(c.copyVector3sArray(b.vertices),c.needsUpdate=!0),b.verticesNeedUpdate=!1);!0===b.normalsNeedUpdate&&(c=this.attributes.normal,void 0!==c&&(c.copyVector3sArray(b.normals),c.needsUpdate=!0),b.normalsNeedUpdate=!1);!0===b.colorsNeedUpdate&&(c=this.attributes.color,void 0!==c&&(c.copyColorsArray(b.colors),c.needsUpdate=!0),b.colorsNeedUpdate=
17063 !1);b.uvsNeedUpdate&&(c=this.attributes.uv,void 0!==c&&(c.copyVector2sArray(b.uvs),c.needsUpdate=!0),b.uvsNeedUpdate=!1);b.lineDistancesNeedUpdate&&(c=this.attributes.lineDistance,void 0!==c&&(c.copyArray(b.lineDistances),c.needsUpdate=!0),b.lineDistancesNeedUpdate=!1);b.groupsNeedUpdate&&(b.computeGroups(a.geometry),this.groups=b.groups,b.groupsNeedUpdate=!1);return this},fromGeometry:function(a){a.__directGeometry=(new Je).fromGeometry(a);return this.fromDirectGeometry(a.__directGeometry)},fromDirectGeometry:function(a){var b=
17064 new Float32Array(3*a.vertices.length);this.addAttribute("position",(new P(b,3)).copyVector3sArray(a.vertices));0<a.normals.length&&(b=new Float32Array(3*a.normals.length),this.addAttribute("normal",(new P(b,3)).copyVector3sArray(a.normals)));0<a.colors.length&&(b=new Float32Array(3*a.colors.length),this.addAttribute("color",(new P(b,3)).copyColorsArray(a.colors)));0<a.uvs.length&&(b=new Float32Array(2*a.uvs.length),this.addAttribute("uv",(new P(b,2)).copyVector2sArray(a.uvs)));0<a.uvs2.length&&(b=
17065 new Float32Array(2*a.uvs2.length),this.addAttribute("uv2",(new P(b,2)).copyVector2sArray(a.uvs2)));0<a.indices.length&&(b=new (65535<Qd(a.indices)?Uint32Array:Uint16Array)(3*a.indices.length),this.setIndex((new P(b,1)).copyIndicesArray(a.indices)));this.groups=a.groups;for(var c in a.morphTargets){for(var b=[],d=a.morphTargets[c],e=0,f=d.length;e<f;e++){var g=d[e],h=new y(3*g.length,3);b.push(h.copyVector3sArray(g))}this.morphAttributes[c]=b}0<a.skinIndices.length&&(c=new y(4*a.skinIndices.length,
17066 4),this.addAttribute("skinIndex",c.copyVector4sArray(a.skinIndices)));0<a.skinWeights.length&&(c=new y(4*a.skinWeights.length,4),this.addAttribute("skinWeight",c.copyVector4sArray(a.skinWeights)));null!==a.boundingSphere&&(this.boundingSphere=a.boundingSphere.clone());null!==a.boundingBox&&(this.boundingBox=a.boundingBox.clone());return this},computeBoundingBox:function(){null===this.boundingBox&&(this.boundingBox=new Oa);var a=this.attributes.position;void 0!==a?this.boundingBox.setFromBufferAttribute(a):
17067 this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)},computeBoundingSphere:function(){var a=new Oa,b=new p;return function(){null===this.boundingSphere&&(this.boundingSphere=new Da);var c=this.attributes.position;if(c){var d=this.boundingSphere.center;a.setFromBufferAttribute(c);
17068 a.getCenter(d);for(var e=0,f=0,g=c.count;f<g;f++)b.x=c.getX(f),b.y=c.getY(f),b.z=c.getZ(f),e=Math.max(e,d.distanceToSquared(b));this.boundingSphere.radius=Math.sqrt(e);isNaN(this.boundingSphere.radius)&&console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}}(),computeFaceNormals:function(){},computeVertexNormals:function(){var a=this.index,b=this.attributes,c=this.groups;if(b.position){var d=b.position.array;
17069 if(void 0===b.normal)this.addAttribute("normal",new P(new Float32Array(d.length),3));else for(var e=b.normal.array,f=0,g=e.length;f<g;f++)e[f]=0;var e=b.normal.array,h=new p,k=new p,l=new p,q=new p,n=new p;if(a){a=a.array;0===c.length&&this.addGroup(0,a.length);for(var m=0,r=c.length;m<r;++m){f=c[m];g=f.start;var u=f.count;f=g;for(g+=u;f<g;f+=3){u=3*a[f+0];var v=3*a[f+1];var w=3*a[f+2];h.fromArray(d,u);k.fromArray(d,v);l.fromArray(d,w);q.subVectors(l,k);n.subVectors(h,k);q.cross(n);e[u]+=q.x;e[u+
17070 1]+=q.y;e[u+2]+=q.z;e[v]+=q.x;e[v+1]+=q.y;e[v+2]+=q.z;e[w]+=q.x;e[w+1]+=q.y;e[w+2]+=q.z}}}else for(f=0,g=d.length;f<g;f+=9)h.fromArray(d,f),k.fromArray(d,f+3),l.fromArray(d,f+6),q.subVectors(l,k),n.subVectors(h,k),q.cross(n),e[f]=q.x,e[f+1]=q.y,e[f+2]=q.z,e[f+3]=q.x,e[f+4]=q.y,e[f+5]=q.z,e[f+6]=q.x,e[f+7]=q.y,e[f+8]=q.z;this.normalizeNormals();b.normal.needsUpdate=!0}},merge:function(a,b){if(a&&a.isBufferGeometry){void 0===b&&(b=0);var c=this.attributes,d;for(d in c)if(void 0!==a.attributes[d])for(var e=
17071 c[d].array,f=a.attributes[d],g=f.array,h=0,f=f.itemSize*b;h<g.length;h++,f++)e[f]=g[h];return this}console.error("THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.",a)},normalizeNormals:function(){var a=new p;return function(){for(var b=this.attributes.normal,c=0,d=b.count;c<d;c++)a.x=b.getX(c),a.y=b.getY(c),a.z=b.getZ(c),a.normalize(),b.setXYZ(c,a.x,a.y,a.z)}}(),toNonIndexed:function(){if(null===this.index)return console.warn("THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed."),
17072 this;var a=new D,b=this.index.array,c=this.attributes,d;for(d in c){for(var e=c[d],f=e.array,e=e.itemSize,g=new f.constructor(b.length*e),h,k=0,l=0,q=b.length;l<q;l++){h=b[l]*e;for(var n=0;n<e;n++)g[k++]=f[h++]}a.addAttribute(d,new P(g,e))}return a},toJSON:function(){var a={metadata:{version:4.5,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};a.uuid=this.uuid;a.type=this.type;""!==this.name&&(a.name=this.name);if(void 0!==this.parameters){var b=this.parameters;for(var c in b)void 0!==b[c]&&
17073 (a[c]=b[c]);return a}a.data={attributes:{}};var d=this.index;null!==d&&(b=Array.prototype.slice.call(d.array),a.data.index={type:d.array.constructor.name,array:b});d=this.attributes;for(c in d){var e=d[c];b=Array.prototype.slice.call(e.array);a.data.attributes[c]={itemSize:e.itemSize,type:e.array.constructor.name,array:b,normalized:e.normalized}}c=this.groups;0<c.length&&(a.data.groups=JSON.parse(JSON.stringify(c)));c=this.boundingSphere;null!==c&&(a.data.boundingSphere={center:c.center.toArray(),
17074 radius:c.radius});return a},clone:function(){return(new D).copy(this)},copy:function(a){var b;this.index=null;this.attributes={};this.morphAttributes={};this.groups=[];this.boundingSphere=this.boundingBox=null;this.name=a.name;var c=a.index;null!==c&&this.setIndex(c.clone());c=a.attributes;for(g in c)this.addAttribute(g,c[g].clone());var d=a.morphAttributes;for(g in d){var e=[],f=d[g];c=0;for(b=f.length;c<b;c++)e.push(f[c].clone());this.morphAttributes[g]=e}var g=a.groups;c=0;for(b=g.length;c<b;c++)d=
17075 g[c],this.addGroup(d.start,d.count,d.materialIndex);g=a.boundingBox;null!==g&&(this.boundingBox=g.clone());g=a.boundingSphere;null!==g&&(this.boundingSphere=g.clone());this.drawRange.start=a.drawRange.start;this.drawRange.count=a.drawRange.count;return this},dispose:function(){this.dispatchEvent({type:"dispose"})}});Lb.prototype=Object.create(N.prototype);Lb.prototype.constructor=Lb;jb.prototype=Object.create(D.prototype);jb.prototype.constructor=jb;Ac.prototype=Object.create(N.prototype);Ac.prototype.constructor=
17076 Ac;kb.prototype=Object.create(D.prototype);kb.prototype.constructor=kb;va.prototype=Object.create(Q.prototype);va.prototype.constructor=va;va.prototype.isMeshBasicMaterial=!0;va.prototype.copy=function(a){Q.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=a.aoMapIntensity;this.specularMap=a.specularMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.combine=a.combine;this.reflectivity=
17077 a.reflectivity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.skinning=a.skinning;this.morphTargets=a.morphTargets;return this};oa.prototype=Object.create(Q.prototype);oa.prototype.constructor=oa;oa.prototype.isShaderMaterial=!0;oa.prototype.copy=function(a){Q.prototype.copy.call(this,a);this.fragmentShader=a.fragmentShader;this.vertexShader=a.vertexShader;
17078 this.uniforms=Ea.clone(a.uniforms);this.defines=a.defines;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.lights=a.lights;this.clipping=a.clipping;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;this.extensions=a.extensions;return this};oa.prototype.toJSON=function(a){a=Q.prototype.toJSON.call(this,a);a.uniforms=this.uniforms;a.vertexShader=this.vertexShader;a.fragmentShader=this.fragmentShader;return a};Object.assign(lb.prototype,
17079 {set:function(a,b){this.origin.copy(a);this.direction.copy(b);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.origin.copy(a.origin);this.direction.copy(a.direction);return this},at:function(a,b){return(b||new p).copy(this.direction).multiplyScalar(a).add(this.origin)},lookAt:function(a){this.direction.copy(a).sub(this.origin).normalize();return this},recast:function(){var a=new p;return function(b){this.origin.copy(this.at(b,a));return this}}(),closestPointToPoint:function(a,
17080 b){b=b||new p;b.subVectors(a,this.origin);a=b.dot(this.direction);return 0>a?b.copy(this.origin):b.copy(this.direction).multiplyScalar(a).add(this.origin)},distanceToPoint:function(a){return Math.sqrt(this.distanceSqToPoint(a))},distanceSqToPoint:function(){var a=new p;return function(b){var c=a.subVectors(b,this.origin).dot(this.direction);if(0>c)return this.origin.distanceToSquared(b);a.copy(this.direction).multiplyScalar(c).add(this.origin);return a.distanceToSquared(b)}}(),distanceSqToSegment:function(){var a=
17081 new p,b=new p,c=new p;return function(d,e,f,g){a.copy(d).add(e).multiplyScalar(.5);b.copy(e).sub(d).normalize();c.copy(this.origin).sub(a);var h=.5*d.distanceTo(e),k=-this.direction.dot(b),l=c.dot(this.direction),q=-c.dot(b),n=c.lengthSq(),m=Math.abs(1-k*k);if(0<m){d=k*q-l;e=k*l-q;var p=h*m;0<=d?e>=-p?e<=p?(h=1/m,d*=h,e*=h,k=d*(d+k*e+2*l)+e*(k*d+e+2*q)+n):(e=h,d=Math.max(0,-(k*e+l)),k=-d*d+e*(e+2*q)+n):(e=-h,d=Math.max(0,-(k*e+l)),k=-d*d+e*(e+2*q)+n):e<=-p?(d=Math.max(0,-(-k*h+l)),e=0<d?-h:Math.min(Math.max(-h,
17082 -q),h),k=-d*d+e*(e+2*q)+n):e<=p?(d=0,e=Math.min(Math.max(-h,-q),h),k=e*(e+2*q)+n):(d=Math.max(0,-(k*h+l)),e=0<d?h:Math.min(Math.max(-h,-q),h),k=-d*d+e*(e+2*q)+n)}else e=0<k?-h:h,d=Math.max(0,-(k*e+l)),k=-d*d+e*(e+2*q)+n;f&&f.copy(this.direction).multiplyScalar(d).add(this.origin);g&&g.copy(b).multiplyScalar(e).add(a);return k}}(),intersectSphere:function(){var a=new p;return function(b,c){a.subVectors(b.center,this.origin);var d=a.dot(this.direction),e=a.dot(a)-d*d;b=b.radius*b.radius;if(e>b)return null;
17083 b=Math.sqrt(b-e);e=d-b;d+=b;return 0>e&&0>d?null:0>e?this.at(d,c):this.at(e,c)}}(),intersectsSphere:function(a){return this.distanceToPoint(a.center)<=a.radius},distanceToPlane:function(a){var b=a.normal.dot(this.direction);if(0===b)return 0===a.distanceToPoint(this.origin)?0:null;a=-(this.origin.dot(a.normal)+a.constant)/b;return 0<=a?a:null},intersectPlane:function(a,b){a=this.distanceToPlane(a);return null===a?null:this.at(a,b)},intersectsPlane:function(a){var b=a.distanceToPoint(this.origin);
17084 return 0===b||0>a.normal.dot(this.direction)*b?!0:!1},intersectBox:function(a,b){var c=1/this.direction.x;var d=1/this.direction.y;var e=1/this.direction.z,f=this.origin;if(0<=c){var g=(a.min.x-f.x)*c;c*=a.max.x-f.x}else g=(a.max.x-f.x)*c,c*=a.min.x-f.x;if(0<=d){var h=(a.min.y-f.y)*d;d*=a.max.y-f.y}else h=(a.max.y-f.y)*d,d*=a.min.y-f.y;if(g>d||h>c)return null;if(h>g||g!==g)g=h;if(d<c||c!==c)c=d;0<=e?(h=(a.min.z-f.z)*e,a=(a.max.z-f.z)*e):(h=(a.max.z-f.z)*e,a=(a.min.z-f.z)*e);if(g>a||h>c)return null;
17085 if(h>g||g!==g)g=h;if(a<c||c!==c)c=a;return 0>c?null:this.at(0<=g?g:c,b)},intersectsBox:function(){var a=new p;return function(b){return null!==this.intersectBox(b,a)}}(),intersectTriangle:function(){var a=new p,b=new p,c=new p,d=new p;return function(e,f,g,h,k){b.subVectors(f,e);c.subVectors(g,e);d.crossVectors(b,c);f=this.direction.dot(d);if(0<f){if(h)return null;h=1}else if(0>f)h=-1,f=-f;else return null;a.subVectors(this.origin,e);e=h*this.direction.dot(c.crossVectors(a,c));if(0>e)return null;
17086 g=h*this.direction.dot(b.cross(a));if(0>g||e+g>f)return null;e=-h*a.dot(d);return 0>e?null:this.at(e/f,k)}}(),applyMatrix4:function(a){this.origin.applyMatrix4(a);this.direction.transformDirection(a);return this},equals:function(a){return a.origin.equals(this.origin)&&a.direction.equals(this.direction)}});Object.assign(Mb.prototype,{set:function(a,b){this.start.copy(a);this.end.copy(b);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.start.copy(a.start);
17087 this.end.copy(a.end);return this},getCenter:function(a){return(a||new p).addVectors(this.start,this.end).multiplyScalar(.5)},delta:function(a){return(a||new p).subVectors(this.end,this.start)},distanceSq:function(){return this.start.distanceToSquared(this.end)},distance:function(){return this.start.distanceTo(this.end)},at:function(a,b){b=b||new p;return this.delta(b).multiplyScalar(a).add(this.start)},closestPointToPointParameter:function(){var a=new p,b=new p;return function(c,d){a.subVectors(c,
17088 this.start);b.subVectors(this.end,this.start);c=b.dot(b);c=b.dot(a)/c;d&&(c=R.clamp(c,0,1));return c}}(),closestPointToPoint:function(a,b,c){a=this.closestPointToPointParameter(a,b);c=c||new p;return this.delta(c).multiplyScalar(a).add(this.start)},applyMatrix4:function(a){this.start.applyMatrix4(a);this.end.applyMatrix4(a);return this},equals:function(a){return a.start.equals(this.start)&&a.end.equals(this.end)}});Object.assign(Qa,{normal:function(){var a=new p;return function(b,c,d,e){e=e||new p;
17089 e.subVectors(d,c);a.subVectors(b,c);e.cross(a);b=e.lengthSq();return 0<b?e.multiplyScalar(1/Math.sqrt(b)):e.set(0,0,0)}}(),barycoordFromPoint:function(){var a=new p,b=new p,c=new p;return function(d,e,f,g,h){a.subVectors(g,e);b.subVectors(f,e);c.subVectors(d,e);d=a.dot(a);e=a.dot(b);f=a.dot(c);var k=b.dot(b);g=b.dot(c);var l=d*k-e*e;h=h||new p;if(0===l)return h.set(-2,-1,-1);l=1/l;k=(k*f-e*g)*l;d=(d*g-e*f)*l;return h.set(1-k-d,d,k)}}(),containsPoint:function(){var a=new p;return function(b,c,d,e){b=
17090 Qa.barycoordFromPoint(b,c,d,e,a);return 0<=b.x&&0<=b.y&&1>=b.x+b.y}}()});Object.assign(Qa.prototype,{set:function(a,b,c){this.a.copy(a);this.b.copy(b);this.c.copy(c);return this},setFromPointsAndIndices:function(a,b,c,d){this.a.copy(a[b]);this.b.copy(a[c]);this.c.copy(a[d]);return this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.a.copy(a.a);this.b.copy(a.b);this.c.copy(a.c);return this},area:function(){var a=new p,b=new p;return function(){a.subVectors(this.c,
17091 this.b);b.subVectors(this.a,this.b);return.5*a.cross(b).length()}}(),midpoint:function(a){return(a||new p).addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)},normal:function(a){return Qa.normal(this.a,this.b,this.c,a)},plane:function(a){return(a||new Aa).setFromCoplanarPoints(this.a,this.b,this.c)},barycoordFromPoint:function(a,b){return Qa.barycoordFromPoint(a,this.a,this.b,this.c,b)},containsPoint:function(a){return Qa.containsPoint(a,this.a,this.b,this.c)},closestPointToPoint:function(){var a=
17092 new Aa,b=[new Mb,new Mb,new Mb],c=new p,d=new p;return function(e,f){f=f||new p;var g=Infinity;a.setFromCoplanarPoints(this.a,this.b,this.c);a.projectPoint(e,c);if(!0===this.containsPoint(c))f.copy(c);else for(b[0].set(this.a,this.b),b[1].set(this.b,this.c),b[2].set(this.c,this.a),e=0;e<b.length;e++){b[e].closestPointToPoint(c,!0,d);var h=c.distanceToSquared(d);h<g&&(g=h,f.copy(d))}return f}}(),equals:function(a){return a.a.equals(this.a)&&a.b.equals(this.b)&&a.c.equals(this.c)}});pa.prototype=Object.assign(Object.create(A.prototype),
17093 {constructor:pa,isMesh:!0,setDrawMode:function(a){this.drawMode=a},copy:function(a){A.prototype.copy.call(this,a);this.drawMode=a.drawMode;void 0!==a.morphTargetInfluences&&(this.morphTargetInfluences=a.morphTargetInfluences.slice());void 0!==a.morphTargetDictionary&&(this.morphTargetDictionary=Object.assign({},a.morphTargetDictionary));return this},updateMorphTargets:function(){var a=this.geometry;if(a.isBufferGeometry){a=a.morphAttributes;var b=Object.keys(a);if(0<b.length){var c=a[b[0]];if(void 0!==
17094 c)for(this.morphTargetInfluences=[],this.morphTargetDictionary={},a=0,b=c.length;a<b;a++){var d=c[a].name||String(a);this.morphTargetInfluences.push(0);this.morphTargetDictionary[d]=a}}}else if(c=a.morphTargets,void 0!==c&&0<c.length)for(this.morphTargetInfluences=[],this.morphTargetDictionary={},a=0,b=c.length;a<b;a++)d=c[a].name||String(a),this.morphTargetInfluences.push(0),this.morphTargetDictionary[d]=a},raycast:function(){function a(a,b,c,d,e,f,g){Qa.barycoordFromPoint(a,b,c,d,v);e.multiplyScalar(v.x);
17095 f.multiplyScalar(v.y);g.multiplyScalar(v.z);e.add(f).add(g);return e.clone()}function b(a,b,c,d,e,f,g,h){if(null===(1===b.side?d.intersectTriangle(g,f,e,!0,h):d.intersectTriangle(e,f,g,2!==b.side,h)))return null;x.copy(h);x.applyMatrix4(a.matrixWorld);b=c.ray.origin.distanceTo(x);return b<c.near||b>c.far?null:{distance:b,point:x.clone(),object:a}}function c(c,d,e,f,l,n,q,t){g.fromBufferAttribute(f,n);h.fromBufferAttribute(f,q);k.fromBufferAttribute(f,t);if(c=b(c,c.material,d,e,g,h,k,w))l&&(m.fromBufferAttribute(l,
17096 n),r.fromBufferAttribute(l,q),u.fromBufferAttribute(l,t),c.uv=a(w,g,h,k,m,r,u)),c.face=new Pa(n,q,t,Qa.normal(g,h,k)),c.faceIndex=n;return c}var d=new K,e=new lb,f=new Da,g=new p,h=new p,k=new p,l=new p,q=new p,n=new p,m=new C,r=new C,u=new C,v=new p,w=new p,x=new p;return function(t,p){var v=this.geometry,x=this.material,z=this.matrixWorld;if(void 0!==x&&(null===v.boundingSphere&&v.computeBoundingSphere(),f.copy(v.boundingSphere),f.applyMatrix4(z),!1!==t.ray.intersectsSphere(f)&&(d.getInverse(z),
17097 e.copy(t.ray).applyMatrix4(d),null===v.boundingBox||!1!==e.intersectsBox(v.boundingBox)))){var y;if(v.isBufferGeometry){var x=v.index,I=v.attributes.position,z=v.attributes.uv,C;if(null!==x){var A=0;for(C=x.count;A<C;A+=3){v=x.getX(A);var D=x.getX(A+1);var E=x.getX(A+2);if(y=c(this,t,e,I,z,v,D,E))y.faceIndex=Math.floor(A/3),p.push(y)}}else if(void 0!==I)for(A=0,C=I.count;A<C;A+=3)if(v=A,D=A+1,E=A+2,y=c(this,t,e,I,z,v,D,E))y.index=v,p.push(y)}else if(v.isGeometry){var z=Array.isArray(x);A=v.vertices;
17098 C=v.faces;D=v.faceVertexUvs[0];0<D.length&&(I=D);for(var H=0,N=C.length;H<N;H++){var M=C[H];y=z?x[M.materialIndex]:x;if(void 0!==y){D=A[M.a];E=A[M.b];var V=A[M.c];if(!0===y.morphTargets){var K=v.morphTargets,P=this.morphTargetInfluences;g.set(0,0,0);h.set(0,0,0);k.set(0,0,0);for(var Q=0,R=K.length;Q<R;Q++){var O=P[Q];if(0!==O){var S=K[Q].vertices;g.addScaledVector(l.subVectors(S[M.a],D),O);h.addScaledVector(q.subVectors(S[M.b],E),O);k.addScaledVector(n.subVectors(S[M.c],V),O)}}g.add(D);h.add(E);k.add(V);
17099 D=g;E=h;V=k}if(y=b(this,y,t,e,D,E,V,w))I&&I[H]&&(K=I[H],m.copy(K[0]),r.copy(K[1]),u.copy(K[2]),y.uv=a(w,D,E,V,m,r,u)),y.face=M,y.faceIndex=H,p.push(y)}}}}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});var ig=0;U.prototype=Object.assign(Object.create(La.prototype),{constructor:U,isPerspectiveCamera:!0,copy:function(a,b){La.prototype.copy.call(this,a,b);this.fov=a.fov;this.zoom=a.zoom;this.near=a.near;this.far=a.far;this.focus=a.focus;this.aspect=a.aspect;
17100 this.view=null===a.view?null:Object.assign({},a.view);this.filmGauge=a.filmGauge;this.filmOffset=a.filmOffset;return this},setFocalLength:function(a){a=.5*this.getFilmHeight()/a;this.fov=2*R.RAD2DEG*Math.atan(a);this.updateProjectionMatrix()},getFocalLength:function(){var a=Math.tan(.5*R.DEG2RAD*this.fov);return.5*this.getFilmHeight()/a},getEffectiveFOV:function(){return 2*R.RAD2DEG*Math.atan(Math.tan(.5*R.DEG2RAD*this.fov)/this.zoom)},getFilmWidth:function(){return this.filmGauge*Math.min(this.aspect,
17101 1)},getFilmHeight:function(){return this.filmGauge/Math.max(this.aspect,1)},setViewOffset:function(a,b,c,d,e,f){this.aspect=a/b;null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1});this.view.enabled=!0;this.view.fullWidth=a;this.view.fullHeight=b;this.view.offsetX=c;this.view.offsetY=d;this.view.width=e;this.view.height=f;this.updateProjectionMatrix()},clearViewOffset:function(){null!==this.view&&(this.view.enabled=!1);this.updateProjectionMatrix()},
17102 updateProjectionMatrix:function(){var a=this.near,b=a*Math.tan(.5*R.DEG2RAD*this.fov)/this.zoom,c=2*b,d=this.aspect*c,e=-.5*d,f=this.view;if(null!==this.view&&this.view.enabled)var g=f.fullWidth,h=f.fullHeight,e=e+f.offsetX*d/g,b=b-f.offsetY*c/h,d=f.width/g*d,c=f.height/h*c;f=this.filmOffset;0!==f&&(e+=a*f/this.getFilmWidth());this.projectionMatrix.makePerspective(e,e+d,b,b-c,a,this.far)},toJSON:function(a){a=A.prototype.toJSON.call(this,a);a.object.fov=this.fov;a.object.zoom=this.zoom;a.object.near=
17103 this.near;a.object.far=this.far;a.object.focus=this.focus;a.object.aspect=this.aspect;null!==this.view&&(a.object.view=Object.assign({},this.view));a.object.filmGauge=this.filmGauge;a.object.filmOffset=this.filmOffset;return a}});nd.prototype=Object.assign(Object.create(U.prototype),{constructor:nd,isArrayCamera:!0});Ob.prototype.isFogExp2=!0;Ob.prototype.clone=function(){return new Ob(this.color.getHex(),this.density)};Ob.prototype.toJSON=function(){return{type:"FogExp2",color:this.color.getHex(),
17104 density:this.density}};Pb.prototype.isFog=!0;Pb.prototype.clone=function(){return new Pb(this.color.getHex(),this.near,this.far)};Pb.prototype.toJSON=function(){return{type:"Fog",color:this.color.getHex(),near:this.near,far:this.far}};od.prototype=Object.assign(Object.create(A.prototype),{constructor:od,copy:function(a,b){A.prototype.copy.call(this,a,b);null!==a.background&&(this.background=a.background.clone());null!==a.fog&&(this.fog=a.fog.clone());null!==a.overrideMaterial&&(this.overrideMaterial=
17105 a.overrideMaterial.clone());this.autoUpdate=a.autoUpdate;this.matrixAutoUpdate=a.matrixAutoUpdate;return this},toJSON:function(a){var b=A.prototype.toJSON.call(this,a);null!==this.background&&(b.object.background=this.background.toJSON(a));null!==this.fog&&(b.object.fog=this.fog.toJSON());return b}});Xd.prototype=Object.assign(Object.create(A.prototype),{constructor:Xd,isLensFlare:!0,copy:function(a){A.prototype.copy.call(this,a);this.positionScreen.copy(a.positionScreen);this.customUpdateCallback=
17106 a.customUpdateCallback;for(var b=0,c=a.lensFlares.length;b<c;b++)this.lensFlares.push(a.lensFlares[b]);return this},add:function(a,b,c,d,e,f){void 0===b&&(b=-1);void 0===c&&(c=0);void 0===f&&(f=1);void 0===e&&(e=new H(16777215));void 0===d&&(d=1);c=Math.min(c,Math.max(0,c));this.lensFlares.push({texture:a,size:b,distance:c,x:0,y:0,z:0,scale:1,rotation:0,opacity:f,color:e,blending:d})},updateLensFlares:function(){var a,b=this.lensFlares.length,c=2*-this.positionScreen.x,d=2*-this.positionScreen.y;
17107 for(a=0;a<b;a++){var e=this.lensFlares[a];e.x=this.positionScreen.x+c*e.distance;e.y=this.positionScreen.y+d*e.distance;e.wantedRotation=e.x*Math.PI*.25;e.rotation+=.25*(e.wantedRotation-e.rotation)}}});Za.prototype=Object.create(Q.prototype);Za.prototype.constructor=Za;Za.prototype.isSpriteMaterial=!0;Za.prototype.copy=function(a){Q.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.rotation=a.rotation;return this};Cc.prototype=Object.assign(Object.create(A.prototype),{constructor:Cc,
17108 isSprite:!0,raycast:function(){var a=new p,b=new p,c=new p;return function(d,e){b.setFromMatrixPosition(this.matrixWorld);d.ray.closestPointToPoint(b,a);c.setFromMatrixScale(this.matrixWorld);var f=c.x*c.y/4;b.distanceToSquared(a)>f||(f=d.ray.origin.distanceTo(a),f<d.near||f>d.far||e.push({distance:f,point:a.clone(),face:null,object:this}))}}(),clone:function(){return(new this.constructor(this.material)).copy(this)}});Dc.prototype=Object.assign(Object.create(A.prototype),{constructor:Dc,copy:function(a){A.prototype.copy.call(this,
17109 a,!1);a=a.levels;for(var b=0,c=a.length;b<c;b++){var d=a[b];this.addLevel(d.object.clone(),d.distance)}return this},addLevel:function(a,b){void 0===b&&(b=0);b=Math.abs(b);for(var c=this.levels,d=0;d<c.length&&!(b<c[d].distance);d++);c.splice(d,0,{distance:b,object:a});this.add(a)},getObjectForDistance:function(a){for(var b=this.levels,c=1,d=b.length;c<d&&!(a<b[c].distance);c++);return b[c-1].object},raycast:function(){var a=new p;return function(b,c){a.setFromMatrixPosition(this.matrixWorld);var d=
17110 b.ray.origin.distanceTo(a);this.getObjectForDistance(d).raycast(b,c)}}(),update:function(){var a=new p,b=new p;return function(c){var d=this.levels;if(1<d.length){a.setFromMatrixPosition(c.matrixWorld);b.setFromMatrixPosition(this.matrixWorld);c=a.distanceTo(b);d[0].object.visible=!0;for(var e=1,f=d.length;e<f;e++)if(c>=d[e].distance)d[e-1].object.visible=!1,d[e].object.visible=!0;else break;for(;e<f;e++)d[e].object.visible=!1}}}(),toJSON:function(a){a=A.prototype.toJSON.call(this,a);a.object.levels=
17111 [];for(var b=this.levels,c=0,d=b.length;c<d;c++){var e=b[c];a.object.levels.push({object:e.object.uuid,distance:e.distance})}return a}});Object.assign(Ec.prototype,{calculateInverses:function(){this.boneInverses=[];for(var a=0,b=this.bones.length;a<b;a++){var c=new K;this.bones[a]&&c.getInverse(this.bones[a].matrixWorld);this.boneInverses.push(c)}},pose:function(){var a,b;var c=0;for(b=this.bones.length;c<b;c++)(a=this.bones[c])&&a.matrixWorld.getInverse(this.boneInverses[c]);c=0;for(b=this.bones.length;c<
17112 b;c++)if(a=this.bones[c])a.parent&&a.parent.isBone?(a.matrix.getInverse(a.parent.matrixWorld),a.matrix.multiply(a.matrixWorld)):a.matrix.copy(a.matrixWorld),a.matrix.decompose(a.position,a.quaternion,a.scale)},update:function(){var a=new K,b=new K;return function(){for(var c=this.bones,d=this.boneInverses,e=this.boneMatrices,f=this.boneTexture,g=0,h=c.length;g<h;g++)a.multiplyMatrices(c[g]?c[g].matrixWorld:b,d[g]),a.toArray(e,16*g);void 0!==f&&(f.needsUpdate=!0)}}(),clone:function(){return new Ec(this.bones,
17113 this.boneInverses)}});pd.prototype=Object.assign(Object.create(A.prototype),{constructor:pd,isBone:!0});qd.prototype=Object.assign(Object.create(pa.prototype),{constructor:qd,isSkinnedMesh:!0,initBones:function(){var a=[],b;if(this.geometry&&void 0!==this.geometry.bones){var c=0;for(b=this.geometry.bones.length;c<b;c++){var d=this.geometry.bones[c];var e=new pd;a.push(e);e.name=d.name;e.position.fromArray(d.pos);e.quaternion.fromArray(d.rotq);void 0!==d.scl&&e.scale.fromArray(d.scl)}c=0;for(b=this.geometry.bones.length;c<
17114 b;c++)d=this.geometry.bones[c],-1!==d.parent&&null!==d.parent&&void 0!==a[d.parent]?a[d.parent].add(a[c]):this.add(a[c])}this.updateMatrixWorld(!0);return a},bind:function(a,b){this.skeleton=a;void 0===b&&(this.updateMatrixWorld(!0),this.skeleton.calculateInverses(),b=this.matrixWorld);this.bindMatrix.copy(b);this.bindMatrixInverse.getInverse(b)},pose:function(){this.skeleton.pose()},normalizeSkinWeights:function(){var a;if(this.geometry&&this.geometry.isGeometry)for(a=0;a<this.geometry.skinWeights.length;a++){var b=
17115 this.geometry.skinWeights[a];var c=1/b.manhattanLength();Infinity!==c?b.multiplyScalar(c):b.set(1,0,0,0)}else if(this.geometry&&this.geometry.isBufferGeometry){var b=new da,d=this.geometry.attributes.skinWeight;for(a=0;a<d.count;a++)b.x=d.getX(a),b.y=d.getY(a),b.z=d.getZ(a),b.w=d.getW(a),c=1/b.manhattanLength(),Infinity!==c?b.multiplyScalar(c):b.set(1,0,0,0),d.setXYZW(a,b.x,b.y,b.z,b.w)}},updateMatrixWorld:function(a){pa.prototype.updateMatrixWorld.call(this,a);"attached"===this.bindMode?this.bindMatrixInverse.getInverse(this.matrixWorld):
17116 "detached"===this.bindMode?this.bindMatrixInverse.getInverse(this.bindMatrix):console.warn("THREE.SkinnedMesh: Unrecognized bindMode: "+this.bindMode)},clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});O.prototype=Object.create(Q.prototype);O.prototype.constructor=O;O.prototype.isLineBasicMaterial=!0;O.prototype.copy=function(a){Q.prototype.copy.call(this,a);this.color.copy(a.color);this.linewidth=a.linewidth;this.linecap=a.linecap;this.linejoin=a.linejoin;return this};
17117 ma.prototype=Object.assign(Object.create(A.prototype),{constructor:ma,isLine:!0,raycast:function(){var a=new K,b=new lb,c=new Da;return function(d,e){var f=d.linePrecision,f=f*f,g=this.geometry,h=this.matrixWorld;null===g.boundingSphere&&g.computeBoundingSphere();c.copy(g.boundingSphere);c.applyMatrix4(h);if(!1!==d.ray.intersectsSphere(c)){a.getInverse(h);b.copy(d.ray).applyMatrix4(a);var k=new p,l=new p,h=new p,q=new p,n=this&&this.isLineSegments?2:1;if(g.isBufferGeometry){var m=g.index;var r=g.attributes.position.array;
17118 if(null!==m)for(var u=m.array,g=0,v=u.length-1;g<v;g+=n)m=u[g+1],k.fromArray(r,3*u[g]),l.fromArray(r,3*m),m=b.distanceSqToSegment(k,l,q,h),m>f||(q.applyMatrix4(this.matrixWorld),m=d.ray.origin.distanceTo(q),m<d.near||m>d.far||e.push({distance:m,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}));else for(g=0,v=r.length/3-1;g<v;g+=n)k.fromArray(r,3*g),l.fromArray(r,3*g+3),m=b.distanceSqToSegment(k,l,q,h),m>f||(q.applyMatrix4(this.matrixWorld),m=d.ray.origin.distanceTo(q),
17119 m<d.near||m>d.far||e.push({distance:m,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}else if(g.isGeometry)for(k=g.vertices,l=k.length,g=0;g<l-1;g+=n)m=b.distanceSqToSegment(k[g],k[g+1],q,h),m>f||(q.applyMatrix4(this.matrixWorld),m=d.ray.origin.distanceTo(q),m<d.near||m>d.far||e.push({distance:m,point:h.clone().applyMatrix4(this.matrixWorld),index:g,face:null,faceIndex:null,object:this}))}}}(),clone:function(){return(new this.constructor(this.geometry,
17120 this.material)).copy(this)}});ca.prototype=Object.assign(Object.create(ma.prototype),{constructor:ca,isLineSegments:!0});rd.prototype=Object.assign(Object.create(ma.prototype),{constructor:rd,isLineLoop:!0});Ba.prototype=Object.create(Q.prototype);Ba.prototype.constructor=Ba;Ba.prototype.isPointsMaterial=!0;Ba.prototype.copy=function(a){Q.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.size=a.size;this.sizeAttenuation=a.sizeAttenuation;return this};Qb.prototype=Object.assign(Object.create(A.prototype),
17121 {constructor:Qb,isPoints:!0,raycast:function(){var a=new K,b=new lb,c=new Da;return function(d,e){function f(a,c){var f=b.distanceSqToPoint(a);if(f<m){a=b.closestPointToPoint(a);a.applyMatrix4(k);var h=d.ray.origin.distanceTo(a);h<d.near||h>d.far||e.push({distance:h,distanceToRay:Math.sqrt(f),point:a.clone(),index:c,face:null,object:g})}}var g=this,h=this.geometry,k=this.matrixWorld,l=d.params.Points.threshold;null===h.boundingSphere&&h.computeBoundingSphere();c.copy(h.boundingSphere);c.applyMatrix4(k);
17122 c.radius+=l;if(!1!==d.ray.intersectsSphere(c)){a.getInverse(k);b.copy(d.ray).applyMatrix4(a);var l=l/((this.scale.x+this.scale.y+this.scale.z)/3),m=l*l,l=new p;if(h.isBufferGeometry){var n=h.index,h=h.attributes.position.array;if(null!==n)for(var t=n.array,n=0,r=t.length;n<r;n++){var u=t[n];l.fromArray(h,3*u);f(l,u)}else for(n=0,t=h.length/3;n<t;n++)l.fromArray(h,3*n),f(l,n)}else for(l=h.vertices,n=0,t=l.length;n<t;n++)f(l[n],n)}}}(),clone:function(){return(new this.constructor(this.geometry,this.material)).copy(this)}});
17123 Fc.prototype=Object.assign(Object.create(A.prototype),{constructor:Fc});sd.prototype=Object.create(ea.prototype);sd.prototype.constructor=sd;Rb.prototype=Object.create(ea.prototype);Rb.prototype.constructor=Rb;Rb.prototype.isCompressedTexture=!0;Gc.prototype=Object.create(ea.prototype);Gc.prototype.constructor=Gc;Gc.prototype.isDepthTexture=!0;Sb.prototype=Object.create(D.prototype);Sb.prototype.constructor=Sb;Hc.prototype=Object.create(N.prototype);Hc.prototype.constructor=Hc;Tb.prototype=Object.create(D.prototype);
17124 Tb.prototype.constructor=Tb;Ic.prototype=Object.create(N.prototype);Ic.prototype.constructor=Ic;qa.prototype=Object.create(D.prototype);qa.prototype.constructor=qa;Jc.prototype=Object.create(N.prototype);Jc.prototype.constructor=Jc;Ub.prototype=Object.create(qa.prototype);Ub.prototype.constructor=Ub;Kc.prototype=Object.create(N.prototype);Kc.prototype.constructor=Kc;nb.prototype=Object.create(qa.prototype);nb.prototype.constructor=nb;Lc.prototype=Object.create(N.prototype);Lc.prototype.constructor=
17125 Lc;Vb.prototype=Object.create(qa.prototype);Vb.prototype.constructor=Vb;Mc.prototype=Object.create(N.prototype);Mc.prototype.constructor=Mc;Wb.prototype=Object.create(qa.prototype);Wb.prototype.constructor=Wb;Nc.prototype=Object.create(N.prototype);Nc.prototype.constructor=Nc;Xb.prototype=Object.create(D.prototype);Xb.prototype.constructor=Xb;Oc.prototype=Object.create(N.prototype);Oc.prototype.constructor=Oc;Yb.prototype=Object.create(D.prototype);Yb.prototype.constructor=Yb;Pc.prototype=Object.create(N.prototype);
17126 Pc.prototype.constructor=Pc;Zb.prototype=Object.create(D.prototype);Zb.prototype.constructor=Zb;var Ha={area:function(a){for(var b=a.length,c=0,d=b-1,e=0;e<b;d=e++)c+=a[d].x*a[e].y-a[e].x*a[d].y;return.5*c},triangulate:function(){return function(a,b){var c=a.length;if(3>c)return null;var d=[],e=[],f=[],g;if(0<Ha.area(a))for(g=0;g<c;g++)e[g]=g;else for(g=0;g<c;g++)e[g]=c-1-g;var h=2*c;for(g=c-1;2<c;){if(0>=h--){console.warn("THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()");break}var k=
17127 g;c<=k&&(k=0);g=k+1;c<=g&&(g=0);var l=g+1;c<=l&&(l=0);a:{var m;var n=a[e[k]].x;var p=a[e[k]].y;var r=a[e[g]].x;var u=a[e[g]].y;var v=a[e[l]].x;var w=a[e[l]].y;if(0>=(r-n)*(w-p)-(u-p)*(v-n))var x=!1;else{var z=v-r;var y=w-u;var B=n-v;var C=p-w;var A=r-n;x=u-p;for(m=0;m<c;m++){var D=a[e[m]].x;var E=a[e[m]].y;if(!(D===n&&E===p||D===r&&E===u||D===v&&E===w)){var H=D-n;var N=E-p;var K=D-r;var L=E-u;D-=v;E-=w;L=z*L-y*K;N=A*N-x*H;D=B*E-C*D;if(L>=-Number.EPSILON&&D>=-Number.EPSILON&&N>=-Number.EPSILON){x=
17128 !1;break a}}}x=!0}}if(x){d.push([a[e[k]],a[e[g]],a[e[l]]]);f.push([e[k],e[g],e[l]]);k=g;for(l=g+1;l<c;k++,l++)e[k]=e[l];c--;h=2*c}}return b?f:d}}(),triangulateShape:function(a,b){function c(a){var b=a.length;2<b&&a[b-1].equals(a[0])&&a.pop()}function d(a,b,c){return a.x!==b.x?a.x<b.x?a.x<=c.x&&c.x<=b.x:b.x<=c.x&&c.x<=a.x:a.y<b.y?a.y<=c.y&&c.y<=b.y:b.y<=c.y&&c.y<=a.y}function e(a,b,c,e,f){var g=b.x-a.x,h=b.y-a.y,k=e.x-c.x,l=e.y-c.y,m=a.x-c.x,n=a.y-c.y,q=h*k-g*l,p=h*m-g*n;if(Math.abs(q)>Number.EPSILON){if(0<
17129 q){if(0>p||p>q)return[];k=l*m-k*n;if(0>k||k>q)return[]}else{if(0<p||p<q)return[];k=l*m-k*n;if(0<k||k<q)return[]}if(0===k)return!f||0!==p&&p!==q?[a]:[];if(k===q)return!f||0!==p&&p!==q?[b]:[];if(0===p)return[c];if(p===q)return[e];f=k/q;return[{x:a.x+f*g,y:a.y+f*h}]}if(0!==p||l*m!==k*n)return[];h=0===g&&0===h;k=0===k&&0===l;if(h&&k)return a.x!==c.x||a.y!==c.y?[]:[a];if(h)return d(c,e,a)?[a]:[];if(k)return d(a,b,c)?[c]:[];0!==g?(a.x<b.x?(g=a,k=a.x,h=b,a=b.x):(g=b,k=b.x,h=a,a=a.x),c.x<e.x?(b=c,q=c.x,l=
17130 e,c=e.x):(b=e,q=e.x,l=c,c=c.x)):(a.y<b.y?(g=a,k=a.y,h=b,a=b.y):(g=b,k=b.y,h=a,a=a.y),c.y<e.y?(b=c,q=c.y,l=e,c=e.y):(b=e,q=e.y,l=c,c=c.y));return k<=q?a<q?[]:a===q?f?[]:[b]:a<=c?[b,h]:[b,l]:k>c?[]:k===c?f?[]:[g]:a<=c?[g,h]:[g,l]}function f(a,b,c,d){var e=b.x-a.x,f=b.y-a.y;b=c.x-a.x;c=c.y-a.y;var g=d.x-a.x;d=d.y-a.y;a=e*c-f*b;e=e*d-f*g;return Math.abs(a)>Number.EPSILON?(b=g*c-d*b,0<a?0<=e&&0<=b:0<=e||0<=b):0<e}c(a);b.forEach(c);var g,h={},k=a.concat();var l=0;for(g=b.length;l<g;l++)Array.prototype.push.apply(k,
17131 b[l]);l=0;for(g=k.length;l<g;l++){var m=k[l].x+":"+k[l].y;void 0!==h[m]&&console.warn("THREE.ShapeUtils: Duplicate point",m,l);h[m]=l}l=function(a,b){function c(a,b){var c=h.length-1,d=a-1;0>d&&(d=c);var e=a+1;e>c&&(e=0);c=f(h[a],h[d],h[e],D[b]);if(!c)return!1;c=D.length-1;d=b-1;0>d&&(d=c);e=b+1;e>c&&(e=0);return(c=f(D[b],D[d],D[e],h[a]))?!0:!1}function d(a,b){var c;for(c=0;c<h.length;c++){var d=c+1;d%=h.length;d=e(a,b,h[c],h[d],!0);if(0<d.length)return!0}return!1}function g(a,c){var d,f;for(d=0;d<
17132 k.length;d++){var g=b[k[d]];for(f=0;f<g.length;f++){var h=f+1;h%=g.length;h=e(a,c,g[f],g[h],!0);if(0<h.length)return!0}}return!1}var h=a.concat(),k=[],l,m;a=[];var q,n=0;for(l=b.length;n<l;n++)k.push(n);var p=0;for(var t=2*k.length;0<k.length;){t--;if(0>t){console.log('THREE.ShapeUtils: Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!');break}for(m=p;m<h.length;m++){var y=h[m];l=-1;for(n=0;n<k.length;n++){var C=k[n];var A=y.x+":"+y.y+":"+C;if(void 0===a[A]){var D=
17133 b[C];for(q=0;q<D.length;q++)if(C=D[q],c(m,q)&&!d(y,C)&&!g(y,C)){l=q;k.splice(n,1);p=h.slice(0,m+1);C=h.slice(m);q=D.slice(l);var E=D.slice(0,l+1);h=p.concat(q).concat(E).concat(C);p=m;break}if(0<=l)break;a[A]=!0}}if(0<=l)break}}return h}(a,b);k=Ha.triangulate(l,!1);l=0;for(g=k.length;l<g;l++)for(b=k[l],a=0;3>a;a++)m=b[a].x+":"+b[a].y,m=h[m],void 0!==m&&(b[a]=m);return k.concat()},isClockWise:function(a){return 0>Ha.area(a)}};$a.prototype=Object.create(N.prototype);$a.prototype.constructor=$a;Ga.prototype=
17134 Object.create(D.prototype);Ga.prototype.constructor=Ga;Ga.prototype.getArrays=function(){var a=this.getAttribute("position"),a=a?Array.prototype.slice.call(a.array):[],b=this.getAttribute("uv"),b=b?Array.prototype.slice.call(b.array):[],c=this.index,c=c?Array.prototype.slice.call(c.array):[];return{position:a,uv:b,index:c}};Ga.prototype.addShapeList=function(a,b){var c=a.length;b.arrays=this.getArrays();for(var d=0;d<c;d++)this.addShape(a[d],b);this.setIndex(b.arrays.index);this.addAttribute("position",
17135 new y(b.arrays.position,3));this.addAttribute("uv",new y(b.arrays.uv,2))};Ga.prototype.addShape=function(a,b){function c(a,b,c){b||console.error("THREE.ExtrudeGeometry: vec does not exist");return b.clone().multiplyScalar(c).add(a)}function d(a,b,c){var d=a.x-b.x;var e=a.y-b.y;var f=c.x-a.x;var g=c.y-a.y,h=d*d+e*e;if(Math.abs(d*g-e*f)>Number.EPSILON){var k=Math.sqrt(h),l=Math.sqrt(f*f+g*g),h=b.x-e/k;b=b.y+d/k;g=((c.x-g/l-h)*g-(c.y+f/l-b)*f)/(d*g-e*f);f=h+d*g-a.x;d=b+e*g-a.y;e=f*f+d*d;if(2>=e)return new C(f,
17136 d);e=Math.sqrt(e/2)}else a=!1,d>Number.EPSILON?f>Number.EPSILON&&(a=!0):d<-Number.EPSILON?f<-Number.EPSILON&&(a=!0):Math.sign(e)===Math.sign(g)&&(a=!0),a?(f=-e,e=Math.sqrt(h)):(f=d,d=e,e=Math.sqrt(h/2));return new C(f/e,d/e)}function e(a,b){for(G=a.length;0<=--G;){var c=G;var d=G-1;0>d&&(d=a.length-1);var e,f=A+2*w;for(e=0;e<f;e++){var g=Z*e,l=Z*(e+1),q=b+d+g,n=b+d+l,l=b+c+l;h(b+c+g);h(q);h(l);h(q);h(n);h(l);g=m.length/3;g=E.generateSideWallUV(R,m,g-6,g-3,g-2,g-1);k(g[0]);k(g[1]);k(g[3]);k(g[1]);
17137 k(g[2]);k(g[3])}}}function f(a,b,c){r.push(a);r.push(b);r.push(c)}function g(a,b,c){h(a);h(b);h(c);a=m.length/3;a=E.generateTopUV(R,m,a-3,a-2,a-1);k(a[0]);k(a[1]);k(a[2])}function h(a){n.push(m.length/3);m.push(r[3*a+0]);m.push(r[3*a+1]);m.push(r[3*a+2])}function k(a){t.push(a.x);t.push(a.y)}var l=b.arrays?b.arrays:this.getArrays(),m=l.position,n=l.index,t=l.uv,r=[],l=void 0!==b.amount?b.amount:100,u=void 0!==b.bevelThickness?b.bevelThickness:6,v=void 0!==b.bevelSize?b.bevelSize:u-2,w=void 0!==b.bevelSegments?
17138 b.bevelSegments:3,x=void 0!==b.bevelEnabled?b.bevelEnabled:!0,z=void 0!==b.curveSegments?b.curveSegments:12,A=void 0!==b.steps?b.steps:1,B=b.extrudePath,D=!1,E=void 0!==b.UVGenerator?b.UVGenerator:$a.WorldUVGenerator;if(B){var H=B.getSpacedPoints(A);D=!0;x=!1;var N=void 0!==b.frames?b.frames:B.computeFrenetFrames(A,!1);var K=new p;var Q=new p;var P=new p}x||(v=u=w=0);var L,R=this,z=a.extractPoints(z);a=z.shape;var O=z.holes;if(!Ha.isClockWise(a)){a=a.reverse();var M=0;for(L=O.length;M<L;M++){var V=
17139 O[M];Ha.isClockWise(V)&&(O[M]=V.reverse())}}var S=Ha.triangulateShape(a,O),W=a;M=0;for(L=O.length;M<L;M++)V=O[M],a=a.concat(V);var aa,Z=a.length,U,ca=S.length,z=[],G=0;var X=W.length;var fa=X-1;for(aa=G+1;G<X;G++,fa++,aa++)fa===X&&(fa=0),aa===X&&(aa=0),z[G]=d(W[G],W[fa],W[aa]);var B=[],ea=z.concat();M=0;for(L=O.length;M<L;M++){V=O[M];var da=[];G=0;X=V.length;fa=X-1;for(aa=G+1;G<X;G++,fa++,aa++)fa===X&&(fa=0),aa===X&&(aa=0),da[G]=d(V[G],V[fa],V[aa]);B.push(da);ea=ea.concat(da)}for(fa=0;fa<w;fa++){X=
17140 fa/w;var ga=u*Math.cos(X*Math.PI/2);aa=v*Math.sin(X*Math.PI/2);G=0;for(X=W.length;G<X;G++){var T=c(W[G],z[G],aa);f(T.x,T.y,-ga)}M=0;for(L=O.length;M<L;M++)for(V=O[M],da=B[M],G=0,X=V.length;G<X;G++)T=c(V[G],da[G],aa),f(T.x,T.y,-ga)}aa=v;for(G=0;G<Z;G++)T=x?c(a[G],ea[G],aa):a[G],D?(Q.copy(N.normals[0]).multiplyScalar(T.x),K.copy(N.binormals[0]).multiplyScalar(T.y),P.copy(H[0]).add(Q).add(K),f(P.x,P.y,P.z)):f(T.x,T.y,0);for(X=1;X<=A;X++)for(G=0;G<Z;G++)T=x?c(a[G],ea[G],aa):a[G],D?(Q.copy(N.normals[X]).multiplyScalar(T.x),
17141 K.copy(N.binormals[X]).multiplyScalar(T.y),P.copy(H[X]).add(Q).add(K),f(P.x,P.y,P.z)):f(T.x,T.y,l/A*X);for(fa=w-1;0<=fa;fa--){X=fa/w;ga=u*Math.cos(X*Math.PI/2);aa=v*Math.sin(X*Math.PI/2);G=0;for(X=W.length;G<X;G++)T=c(W[G],z[G],aa),f(T.x,T.y,l+ga);M=0;for(L=O.length;M<L;M++)for(V=O[M],da=B[M],G=0,X=V.length;G<X;G++)T=c(V[G],da[G],aa),D?f(T.x,T.y+H[A-1].y,H[A-1].x+ga):f(T.x,T.y,l+ga)}(function(){var a=m.length/3;if(x){var c=0*Z;for(G=0;G<ca;G++)U=S[G],g(U[2]+c,U[1]+c,U[0]+c);c=Z*(A+2*w);for(G=0;G<
17142 ca;G++)U=S[G],g(U[0]+c,U[1]+c,U[2]+c)}else{for(G=0;G<ca;G++)U=S[G],g(U[2],U[1],U[0]);for(G=0;G<ca;G++)U=S[G],g(U[0]+Z*A,U[1]+Z*A,U[2]+Z*A)}R.addGroup(a,m.length/3-a,void 0!==b.material?b.material:0)})();(function(){var a=m.length/3,c=0;e(W,c);c+=W.length;M=0;for(L=O.length;M<L;M++)V=O[M],e(V,c),c+=V.length;R.addGroup(a,m.length/3-a,void 0!==b.extrudeMaterial?b.extrudeMaterial:1)})();b.arrays||(this.setIndex(n),this.addAttribute("position",new y(m,3)),this.addAttribute("uv",new y(b.arrays.uv,2)))};
17143 $a.WorldUVGenerator={generateTopUV:function(a,b,c,d,e){a=b[3*d];d=b[3*d+1];var f=b[3*e];e=b[3*e+1];return[new C(b[3*c],b[3*c+1]),new C(a,d),new C(f,e)]},generateSideWallUV:function(a,b,c,d,e,f){a=b[3*c];var g=b[3*c+1];c=b[3*c+2];var h=b[3*d],k=b[3*d+1];d=b[3*d+2];var l=b[3*e],m=b[3*e+1];e=b[3*e+2];var n=b[3*f],p=b[3*f+1];b=b[3*f+2];return.01>Math.abs(g-k)?[new C(a,1-c),new C(h,1-d),new C(l,1-e),new C(n,1-b)]:[new C(g,1-c),new C(k,1-d),new C(m,1-e),new C(p,1-b)]}};Qc.prototype=Object.create(N.prototype);
17144 Qc.prototype.constructor=Qc;$b.prototype=Object.create(Ga.prototype);$b.prototype.constructor=$b;Rc.prototype=Object.create(N.prototype);Rc.prototype.constructor=Rc;ob.prototype=Object.create(D.prototype);ob.prototype.constructor=ob;Sc.prototype=Object.create(N.prototype);Sc.prototype.constructor=Sc;ac.prototype=Object.create(D.prototype);ac.prototype.constructor=ac;Tc.prototype=Object.create(N.prototype);Tc.prototype.constructor=Tc;bc.prototype=Object.create(D.prototype);bc.prototype.constructor=
17145 bc;cc.prototype=Object.create(N.prototype);cc.prototype.constructor=cc;dc.prototype=Object.create(D.prototype);dc.prototype.constructor=dc;ec.prototype=Object.create(D.prototype);ec.prototype.constructor=ec;pb.prototype=Object.create(N.prototype);pb.prototype.constructor=pb;Sa.prototype=Object.create(D.prototype);Sa.prototype.constructor=Sa;Uc.prototype=Object.create(pb.prototype);Uc.prototype.constructor=Uc;Vc.prototype=Object.create(Sa.prototype);Vc.prototype.constructor=Vc;Wc.prototype=Object.create(N.prototype);
17146 Wc.prototype.constructor=Wc;fc.prototype=Object.create(D.prototype);fc.prototype.constructor=fc;var Ca=Object.freeze({WireframeGeometry:Sb,ParametricGeometry:Hc,ParametricBufferGeometry:Tb,TetrahedronGeometry:Jc,TetrahedronBufferGeometry:Ub,OctahedronGeometry:Kc,OctahedronBufferGeometry:nb,IcosahedronGeometry:Lc,IcosahedronBufferGeometry:Vb,DodecahedronGeometry:Mc,DodecahedronBufferGeometry:Wb,PolyhedronGeometry:Ic,PolyhedronBufferGeometry:qa,TubeGeometry:Nc,TubeBufferGeometry:Xb,TorusKnotGeometry:Oc,
17147 TorusKnotBufferGeometry:Yb,TorusGeometry:Pc,TorusBufferGeometry:Zb,TextGeometry:Qc,TextBufferGeometry:$b,SphereGeometry:Rc,SphereBufferGeometry:ob,RingGeometry:Sc,RingBufferGeometry:ac,PlaneGeometry:Ac,PlaneBufferGeometry:kb,LatheGeometry:Tc,LatheBufferGeometry:bc,ShapeGeometry:cc,ShapeBufferGeometry:dc,ExtrudeGeometry:$a,ExtrudeBufferGeometry:Ga,EdgesGeometry:ec,ConeGeometry:Uc,ConeBufferGeometry:Vc,CylinderGeometry:pb,CylinderBufferGeometry:Sa,CircleGeometry:Wc,CircleBufferGeometry:fc,BoxGeometry:Lb,
17148 BoxBufferGeometry:jb});gc.prototype=Object.create(Q.prototype);gc.prototype.constructor=gc;gc.prototype.isShadowMaterial=!0;hc.prototype=Object.create(oa.prototype);hc.prototype.constructor=hc;hc.prototype.isRawShaderMaterial=!0;Ma.prototype=Object.create(Q.prototype);Ma.prototype.constructor=Ma;Ma.prototype.isMeshStandardMaterial=!0;Ma.prototype.copy=function(a){Q.prototype.copy.call(this,a);this.defines={STANDARD:""};this.color.copy(a.color);this.roughness=a.roughness;this.metalness=a.metalness;
17149 this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=a.aoMapIntensity;this.emissive.copy(a.emissive);this.emissiveMap=a.emissiveMap;this.emissiveIntensity=a.emissiveIntensity;this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.roughnessMap=a.roughnessMap;
17150 this.metalnessMap=a.metalnessMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.envMapIntensity=a.envMapIntensity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};qb.prototype=Object.create(Ma.prototype);qb.prototype.constructor=qb;qb.prototype.isMeshPhysicalMaterial=
17151 !0;qb.prototype.copy=function(a){Ma.prototype.copy.call(this,a);this.defines={PHYSICAL:""};this.reflectivity=a.reflectivity;this.clearCoat=a.clearCoat;this.clearCoatRoughness=a.clearCoatRoughness;return this};Ia.prototype=Object.create(Q.prototype);Ia.prototype.constructor=Ia;Ia.prototype.isMeshPhongMaterial=!0;Ia.prototype.copy=function(a){Q.prototype.copy.call(this,a);this.color.copy(a.color);this.specular.copy(a.specular);this.shininess=a.shininess;this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=
17152 a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=a.aoMapIntensity;this.emissive.copy(a.emissive);this.emissiveMap=a.emissiveMap;this.emissiveIntensity=a.emissiveIntensity;this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.specularMap=a.specularMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.combine=
17153 a.combine;this.reflectivity=a.reflectivity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};rb.prototype=Object.create(Ia.prototype);rb.prototype.constructor=rb;rb.prototype.isMeshToonMaterial=!0;rb.prototype.copy=function(a){Ia.prototype.copy.call(this,
17154 a);this.gradientMap=a.gradientMap;return this};sb.prototype=Object.create(Q.prototype);sb.prototype.constructor=sb;sb.prototype.isMeshNormalMaterial=!0;sb.prototype.copy=function(a){Q.prototype.copy.call(this,a);this.bumpMap=a.bumpMap;this.bumpScale=a.bumpScale;this.normalMap=a.normalMap;this.normalScale.copy(a.normalScale);this.displacementMap=a.displacementMap;this.displacementScale=a.displacementScale;this.displacementBias=a.displacementBias;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;
17155 this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};tb.prototype=Object.create(Q.prototype);tb.prototype.constructor=tb;tb.prototype.isMeshLambertMaterial=!0;tb.prototype.copy=function(a){Q.prototype.copy.call(this,a);this.color.copy(a.color);this.map=a.map;this.lightMap=a.lightMap;this.lightMapIntensity=a.lightMapIntensity;this.aoMap=a.aoMap;this.aoMapIntensity=a.aoMapIntensity;this.emissive.copy(a.emissive);this.emissiveMap=a.emissiveMap;this.emissiveIntensity=
17156 a.emissiveIntensity;this.specularMap=a.specularMap;this.alphaMap=a.alphaMap;this.envMap=a.envMap;this.combine=a.combine;this.reflectivity=a.reflectivity;this.refractionRatio=a.refractionRatio;this.wireframe=a.wireframe;this.wireframeLinewidth=a.wireframeLinewidth;this.wireframeLinecap=a.wireframeLinecap;this.wireframeLinejoin=a.wireframeLinejoin;this.skinning=a.skinning;this.morphTargets=a.morphTargets;this.morphNormals=a.morphNormals;return this};ub.prototype=Object.create(O.prototype);ub.prototype.constructor=
17157 ub;ub.prototype.isLineDashedMaterial=!0;ub.prototype.copy=function(a){O.prototype.copy.call(this,a);this.scale=a.scale;this.dashSize=a.dashSize;this.gapSize=a.gapSize;return this};var tg=Object.freeze({ShadowMaterial:gc,SpriteMaterial:Za,RawShaderMaterial:hc,ShaderMaterial:oa,PointsMaterial:Ba,MeshPhysicalMaterial:qb,MeshStandardMaterial:Ma,MeshPhongMaterial:Ia,MeshToonMaterial:rb,MeshNormalMaterial:sb,MeshLambertMaterial:tb,MeshDepthMaterial:Wa,MeshDistanceMaterial:Xa,MeshBasicMaterial:va,LineDashedMaterial:ub,
17158 LineBasicMaterial:O,Material:Q}),jd={enabled:!1,files:{},add:function(a,b){!1!==this.enabled&&(this.files[a]=b)},get:function(a){if(!1!==this.enabled)return this.files[a]},remove:function(a){delete this.files[a]},clear:function(){this.files={}}},wa=new Yd,Ta={};Object.assign(Ja.prototype,{load:function(a,b,c,d){void 0===a&&(a="");void 0!==this.path&&(a=this.path+a);a=this.manager.resolveURL(a);var e=this,f=jd.get(a);if(void 0!==f)return e.manager.itemStart(a),setTimeout(function(){b&&b(f);e.manager.itemEnd(a)},
17159 0),f;if(void 0!==Ta[a])Ta[a].push({onLoad:b,onProgress:c,onError:d});else{var g=a.match(/^data:(.*?)(;base64)?,(.*)$/);if(g){c=g[1];var h=!!g[2],g=g[3],g=window.decodeURIComponent(g);h&&(g=window.atob(g));try{var k=(this.responseType||"").toLowerCase();switch(k){case "arraybuffer":case "blob":for(var l=new Uint8Array(g.length),h=0;h<g.length;h++)l[h]=g.charCodeAt(h);var m="blob"===k?new Blob([l.buffer],{type:c}):l.buffer;break;case "document":m=(new DOMParser).parseFromString(g,c);break;case "json":m=
17160 JSON.parse(g);break;default:m=g}window.setTimeout(function(){b&&b(m);e.manager.itemEnd(a)},0)}catch(t){window.setTimeout(function(){d&&d(t);e.manager.itemEnd(a);e.manager.itemError(a)},0)}}else{Ta[a]=[];Ta[a].push({onLoad:b,onProgress:c,onError:d});var n=new XMLHttpRequest;n.open("GET",a,!0);n.addEventListener("load",function(b){var c=b.target.response;jd.add(a,c);var d=Ta[a];delete Ta[a];if(200===this.status){for(var f=0,g=d.length;f<g;f++){var h=d[f];if(h.onLoad)h.onLoad(c)}e.manager.itemEnd(a)}else if(0===
17161 this.status){console.warn("THREE.FileLoader: HTTP Status 0 received.");f=0;for(g=d.length;f<g;f++)if(h=d[f],h.onLoad)h.onLoad(c);e.manager.itemEnd(a)}else{f=0;for(g=d.length;f<g;f++)if(h=d[f],h.onError)h.onError(b);e.manager.itemEnd(a);e.manager.itemError(a)}},!1);n.addEventListener("progress",function(b){for(var c=Ta[a],d=0,e=c.length;d<e;d++){var f=c[d];if(f.onProgress)f.onProgress(b)}},!1);n.addEventListener("error",function(b){var c=Ta[a];delete Ta[a];for(var d=0,f=c.length;d<f;d++){var g=c[d];
17162 if(g.onError)g.onError(b)}e.manager.itemEnd(a);e.manager.itemError(a)},!1);void 0!==this.responseType&&(n.responseType=this.responseType);void 0!==this.withCredentials&&(n.withCredentials=this.withCredentials);n.overrideMimeType&&n.overrideMimeType(void 0!==this.mimeType?this.mimeType:"text/plain");for(h in this.requestHeader)n.setRequestHeader(h,this.requestHeader[h]);n.send(null)}e.manager.itemStart(a);return n}},setPath:function(a){this.path=a;return this},setResponseType:function(a){this.responseType=
17163 a;return this},setWithCredentials:function(a){this.withCredentials=a;return this},setMimeType:function(a){this.mimeType=a;return this},setRequestHeader:function(a){this.requestHeader=a;return this}});Object.assign(Qe.prototype,{load:function(a,b,c,d){function e(e){l.load(a[e],function(a){a=g._parser(a,!0);h[e]={width:a.width,height:a.height,format:a.format,mipmaps:a.mipmaps};f+=1;6===f&&(1===a.mipmapCount&&(k.minFilter=1006),k.format=a.format,k.needsUpdate=!0,b&&b(k))},c,d)}var f,g=this,h=[],k=new Rb;
17164 k.image=h;var l=new Ja(this.manager);l.setPath(this.path);l.setResponseType("arraybuffer");if(Array.isArray(a))for(var m=f=0,n=a.length;m<n;++m)e(m);else l.load(a,function(a){a=g._parser(a,!0);if(a.isCubemap)for(var c=a.mipmaps.length/a.mipmapCount,d=0;d<c;d++){h[d]={mipmaps:[]};for(var e=0;e<a.mipmapCount;e++)h[d].mipmaps.push(a.mipmaps[d*a.mipmapCount+e]),h[d].format=a.format,h[d].width=a.width,h[d].height=a.height}else k.image.width=a.width,k.image.height=a.height,k.mipmaps=a.mipmaps;1===a.mipmapCount&&
17165 (k.minFilter=1006);k.format=a.format;k.needsUpdate=!0;b&&b(k)},c,d);return k},setPath:function(a){this.path=a;return this}});Object.assign(Zd.prototype,{load:function(a,b,c,d){var e=this,f=new fb,g=new Ja(this.manager);g.setResponseType("arraybuffer");g.load(a,function(a){if(a=e._parser(a))void 0!==a.image?f.image=a.image:void 0!==a.data&&(f.image.width=a.width,f.image.height=a.height,f.image.data=a.data),f.wrapS=void 0!==a.wrapS?a.wrapS:1001,f.wrapT=void 0!==a.wrapT?a.wrapT:1001,f.magFilter=void 0!==
17166 a.magFilter?a.magFilter:1006,f.minFilter=void 0!==a.minFilter?a.minFilter:1008,f.anisotropy=void 0!==a.anisotropy?a.anisotropy:1,void 0!==a.format&&(f.format=a.format),void 0!==a.type&&(f.type=a.type),void 0!==a.mipmaps&&(f.mipmaps=a.mipmaps),1===a.mipmapCount&&(f.minFilter=1006),f.needsUpdate=!0,b&&b(f,a)},c,d);return f}});Object.assign(Xc.prototype,{crossOrigin:"Anonymous",load:function(a,b,c,d){void 0===a&&(a="");void 0!==this.path&&(a=this.path+a);a=this.manager.resolveURL(a);var e=this,f=jd.get(a);
17167 if(void 0!==f)return e.manager.itemStart(a),setTimeout(function(){b&&b(f);e.manager.itemEnd(a)},0),f;c=document.createElementNS("http://www.w3.org/1999/xhtml","img");c.addEventListener("load",function(){jd.add(a,this);b&&b(this);e.manager.itemEnd(a)},!1);c.addEventListener("error",function(b){d&&d(b);e.manager.itemEnd(a);e.manager.itemError(a)},!1);"data:"!==a.substr(0,5)&&void 0!==this.crossOrigin&&(c.crossOrigin=this.crossOrigin);e.manager.itemStart(a);c.src=a;return c},setCrossOrigin:function(a){this.crossOrigin=
17168 a;return this},setPath:function(a){this.path=a;return this}});Object.assign($d.prototype,{crossOrigin:"Anonymous",load:function(a,b,c,d){function e(c){g.load(a[c],function(a){f.images[c]=a;h++;6===h&&(f.needsUpdate=!0,b&&b(f))},void 0,d)}var f=new Ua,g=new Xc(this.manager);g.setCrossOrigin(this.crossOrigin);g.setPath(this.path);var h=0;for(c=0;c<a.length;++c)e(c);return f},setCrossOrigin:function(a){this.crossOrigin=a;return this},setPath:function(a){this.path=a;return this}});Object.assign(td.prototype,
17169 {crossOrigin:"Anonymous",load:function(a,b,c,d){var e=new Xc(this.manager);e.setCrossOrigin(this.crossOrigin);e.setPath(this.path);var f=new ea;f.image=e.load(a,function(){var c=0<a.search(/\.(jpg|jpeg)$/)||0===a.search(/^data\:image\/jpeg/);f.format=c?1022:1023;f.needsUpdate=!0;void 0!==b&&b(f)},c,d);return f},setCrossOrigin:function(a){this.crossOrigin=a;return this},setPath:function(a){this.path=a;return this}});ga.prototype=Object.assign(Object.create(A.prototype),{constructor:ga,isLight:!0,copy:function(a){A.prototype.copy.call(this,
17170 a);this.color.copy(a.color);this.intensity=a.intensity;return this},toJSON:function(a){a=A.prototype.toJSON.call(this,a);a.object.color=this.color.getHex();a.object.intensity=this.intensity;void 0!==this.groundColor&&(a.object.groundColor=this.groundColor.getHex());void 0!==this.distance&&(a.object.distance=this.distance);void 0!==this.angle&&(a.object.angle=this.angle);void 0!==this.decay&&(a.object.decay=this.decay);void 0!==this.penumbra&&(a.object.penumbra=this.penumbra);void 0!==this.shadow&&
17171 (a.object.shadow=this.shadow.toJSON());return a}});ud.prototype=Object.assign(Object.create(ga.prototype),{constructor:ud,isHemisphereLight:!0,copy:function(a){ga.prototype.copy.call(this,a);this.groundColor.copy(a.groundColor);return this}});Object.assign(vb.prototype,{copy:function(a){this.camera=a.camera.clone();this.bias=a.bias;this.radius=a.radius;this.mapSize.copy(a.mapSize);return this},clone:function(){return(new this.constructor).copy(this)},toJSON:function(){var a={};0!==this.bias&&(a.bias=
17172 this.bias);1!==this.radius&&(a.radius=this.radius);if(512!==this.mapSize.x||512!==this.mapSize.y)a.mapSize=this.mapSize.toArray();a.camera=this.camera.toJSON(!1).object;delete a.camera.matrix;return a}});vd.prototype=Object.assign(Object.create(vb.prototype),{constructor:vd,isSpotLightShadow:!0,update:function(a){var b=this.camera,c=2*R.RAD2DEG*a.angle,d=this.mapSize.width/this.mapSize.height;a=a.distance||b.far;if(c!==b.fov||d!==b.aspect||a!==b.far)b.fov=c,b.aspect=d,b.far=a,b.updateProjectionMatrix()}});
17173 wd.prototype=Object.assign(Object.create(ga.prototype),{constructor:wd,isSpotLight:!0,copy:function(a){ga.prototype.copy.call(this,a);this.distance=a.distance;this.angle=a.angle;this.penumbra=a.penumbra;this.decay=a.decay;this.target=a.target.clone();this.shadow=a.shadow.clone();return this}});xd.prototype=Object.assign(Object.create(ga.prototype),{constructor:xd,isPointLight:!0,copy:function(a){ga.prototype.copy.call(this,a);this.distance=a.distance;this.decay=a.decay;this.shadow=a.shadow.clone();
17174 return this}});yd.prototype=Object.assign(Object.create(vb.prototype),{constructor:yd});zd.prototype=Object.assign(Object.create(ga.prototype),{constructor:zd,isDirectionalLight:!0,copy:function(a){ga.prototype.copy.call(this,a);this.target=a.target.clone();this.shadow=a.shadow.clone();return this}});Ad.prototype=Object.assign(Object.create(ga.prototype),{constructor:Ad,isAmbientLight:!0});Bd.prototype=Object.assign(Object.create(ga.prototype),{constructor:Bd,isRectAreaLight:!0,copy:function(a){ga.prototype.copy.call(this,
17175 a);this.width=a.width;this.height=a.height;return this},toJSON:function(a){a=ga.prototype.toJSON.call(this,a);a.object.width=this.width;a.object.height=this.height;return a}});var T={arraySlice:function(a,b,c){return T.isTypedArray(a)?new a.constructor(a.subarray(b,void 0!==c?c:a.length)):a.slice(b,c)},convertArray:function(a,b,c){return!a||!c&&a.constructor===b?a:"number"===typeof b.BYTES_PER_ELEMENT?new b(a):Array.prototype.slice.call(a)},isTypedArray:function(a){return ArrayBuffer.isView(a)&&!(a instanceof
17176 DataView)},getKeyframeOrder:function(a){for(var b=a.length,c=Array(b),d=0;d!==b;++d)c[d]=d;c.sort(function(b,c){return a[b]-a[c]});return c},sortedArray:function(a,b,c){for(var d=a.length,e=new a.constructor(d),f=0,g=0;g!==d;++f)for(var h=c[f]*b,k=0;k!==b;++k)e[g++]=a[h+k];return e},flattenJSON:function(a,b,c,d){for(var e=1,f=a[0];void 0!==f&&void 0===f[d];)f=a[e++];if(void 0!==f){var g=f[d];if(void 0!==g)if(Array.isArray(g)){do g=f[d],void 0!==g&&(b.push(f.time),c.push.apply(c,g)),f=a[e++];while(void 0!==
17177 f)}else if(void 0!==g.toArray){do g=f[d],void 0!==g&&(b.push(f.time),g.toArray(c,c.length)),f=a[e++];while(void 0!==f)}else{do g=f[d],void 0!==g&&(b.push(f.time),c.push(g)),f=a[e++];while(void 0!==f)}}}};Object.assign(xa.prototype,{evaluate:function(a){var b=this.parameterPositions,c=this._cachedIndex,d=b[c],e=b[c-1];a:{b:{c:{d:if(!(a<d)){for(var f=c+2;;){if(void 0===d){if(a<e)break d;this._cachedIndex=c=b.length;return this.afterEnd_(c-1,a,e)}if(c===f)break;e=d;d=b[++c];if(a<d)break b}d=b.length;
17178 break c}if(a>=e)break a;else{f=b[1];a<f&&(c=2,e=f);for(f=c-2;;){if(void 0===e)return this._cachedIndex=0,this.beforeStart_(0,a,d);if(c===f)break;d=e;e=b[--c-1];if(a>=e)break b}d=c;c=0}}for(;c<d;)e=c+d>>>1,a<b[e]?d=e:c=e+1;d=b[c];e=b[c-1];if(void 0===e)return this._cachedIndex=0,this.beforeStart_(0,a,d);if(void 0===d)return this._cachedIndex=c=b.length,this.afterEnd_(c-1,e,a)}this._cachedIndex=c;this.intervalChanged_(c,e,d)}return this.interpolate_(c,e,a,d)},settings:null,DefaultSettings_:{},getSettings_:function(){return this.settings||
17179 this.DefaultSettings_},copySampleValue_:function(a){var b=this.resultBuffer,c=this.sampleValues,d=this.valueSize;a*=d;for(var e=0;e!==d;++e)b[e]=c[a+e];return b},interpolate_:function(){throw Error("call to abstract method");},intervalChanged_:function(){}});Object.assign(xa.prototype,{beforeStart_:xa.prototype.copySampleValue_,afterEnd_:xa.prototype.copySampleValue_});Cd.prototype=Object.assign(Object.create(xa.prototype),{constructor:Cd,DefaultSettings_:{endingStart:2400,endingEnd:2400},intervalChanged_:function(a,
17180 b,c){var d=this.parameterPositions,e=a-2,f=a+1,g=d[e],h=d[f];if(void 0===g)switch(this.getSettings_().endingStart){case 2401:e=a;g=2*b-c;break;case 2402:e=d.length-2;g=b+d[e]-d[e+1];break;default:e=a,g=c}if(void 0===h)switch(this.getSettings_().endingEnd){case 2401:f=a;h=2*c-b;break;case 2402:f=1;h=c+d[1]-d[0];break;default:f=a-1,h=b}a=.5*(c-b);d=this.valueSize;this._weightPrev=a/(b-g);this._weightNext=a/(h-c);this._offsetPrev=e*d;this._offsetNext=f*d},interpolate_:function(a,b,c,d){var e=this.resultBuffer,
17181 f=this.sampleValues,g=this.valueSize;a*=g;var h=a-g,k=this._offsetPrev,l=this._offsetNext,m=this._weightPrev,n=this._weightNext,p=(c-b)/(d-b);c=p*p;d=c*p;b=-m*d+2*m*c-m*p;m=(1+m)*d+(-1.5-2*m)*c+(-.5+m)*p+1;p=(-1-n)*d+(1.5+n)*c+.5*p;n=n*d-n*c;for(c=0;c!==g;++c)e[c]=b*f[k+c]+m*f[h+c]+p*f[a+c]+n*f[l+c];return e}});Yc.prototype=Object.assign(Object.create(xa.prototype),{constructor:Yc,interpolate_:function(a,b,c,d){var e=this.resultBuffer,f=this.sampleValues,g=this.valueSize;a*=g;var h=a-g;b=(c-b)/(d-
17182 b);c=1-b;for(d=0;d!==g;++d)e[d]=f[h+d]*c+f[a+d]*b;return e}});Dd.prototype=Object.assign(Object.create(xa.prototype),{constructor:Dd,interpolate_:function(a){return this.copySampleValue_(a-1)}});var eb={TimeBufferType:Float32Array,ValueBufferType:Float32Array,DefaultInterpolation:2301,InterpolantFactoryMethodDiscrete:function(a){return new Dd(this.times,this.values,this.getValueSize(),a)},InterpolantFactoryMethodLinear:function(a){return new Yc(this.times,this.values,this.getValueSize(),a)},InterpolantFactoryMethodSmooth:function(a){return new Cd(this.times,
17183 this.values,this.getValueSize(),a)},setInterpolation:function(a){switch(a){case 2300:var b=this.InterpolantFactoryMethodDiscrete;break;case 2301:b=this.InterpolantFactoryMethodLinear;break;case 2302:b=this.InterpolantFactoryMethodSmooth}if(void 0===b){b="unsupported interpolation for "+this.ValueTypeName+" keyframe track named "+this.name;if(void 0===this.createInterpolant)if(a!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw Error(b);console.warn("THREE.KeyframeTrackPrototype:",
17184 b)}else this.createInterpolant=b},getInterpolation:function(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return 2300;case this.InterpolantFactoryMethodLinear:return 2301;case this.InterpolantFactoryMethodSmooth:return 2302}},getValueSize:function(){return this.values.length/this.times.length},shift:function(a){if(0!==a)for(var b=this.times,c=0,d=b.length;c!==d;++c)b[c]+=a;return this},scale:function(a){if(1!==a)for(var b=this.times,c=0,d=b.length;c!==d;++c)b[c]*=a;return this},
17185 trim:function(a,b){for(var c=this.times,d=c.length,e=0,f=d-1;e!==d&&c[e]<a;)++e;for(;-1!==f&&c[f]>b;)--f;++f;if(0!==e||f!==d)e>=f&&(f=Math.max(f,1),e=f-1),a=this.getValueSize(),this.times=T.arraySlice(c,e,f),this.values=T.arraySlice(this.values,e*a,f*a);return this},validate:function(){var a=!0,b=this.getValueSize();0!==b-Math.floor(b)&&(console.error("THREE.KeyframeTrackPrototype: Invalid value size in track.",this),a=!1);var c=this.times,b=this.values,d=c.length;0===d&&(console.error("THREE.KeyframeTrackPrototype: Track is empty.",
17186 this),a=!1);for(var e=null,f=0;f!==d;f++){var g=c[f];if("number"===typeof g&&isNaN(g)){console.error("THREE.KeyframeTrackPrototype: Time is not a valid number.",this,f,g);a=!1;break}if(null!==e&&e>g){console.error("THREE.KeyframeTrackPrototype: Out of order keys.",this,f,g,e);a=!1;break}e=g}if(void 0!==b&&T.isTypedArray(b))for(f=0,c=b.length;f!==c;++f)if(d=b[f],isNaN(d)){console.error("THREE.KeyframeTrackPrototype: Value is not a valid number.",this,f,d);a=!1;break}return a},optimize:function(){for(var a,
17187 b,c=this.times,d=this.values,e=this.getValueSize(),f=2302===this.getInterpolation(),g=1,h=c.length-1,k=1;k<h;++k){a=!1;var l=c[k];if(l!==c[k+1]&&(1!==k||l!==l[0]))if(f)a=!0;else{b=k*e;for(var m=b-e,n=b+e,l=0;l!==e;++l){var p=d[b+l];if(p!==d[m+l]||p!==d[n+l]){a=!0;break}}}if(a){if(k!==g)for(c[g]=c[k],b=k*e,a=g*e,l=0;l!==e;++l)d[a+l]=d[b+l];++g}}if(0<h){c[g]=c[h];b=h*e;a=g*e;for(l=0;l!==e;++l)d[a+l]=d[b+l];++g}g!==c.length&&(this.times=T.arraySlice(c,0,g),this.values=T.arraySlice(d,0,g*e));return this}};
17188 ic.prototype=Object.assign(Object.create(eb),{constructor:ic,ValueTypeName:"vector"});Ed.prototype=Object.assign(Object.create(xa.prototype),{constructor:Ed,interpolate_:function(a,b,c,d){var e=this.resultBuffer,f=this.sampleValues,g=this.valueSize;a*=g;b=(c-b)/(d-b);for(c=a+g;a!==c;a+=4)Z.slerpFlat(e,0,f,a-g,f,a,b);return e}});Zc.prototype=Object.assign(Object.create(eb),{constructor:Zc,ValueTypeName:"quaternion",DefaultInterpolation:2301,InterpolantFactoryMethodLinear:function(a){return new Ed(this.times,
17189 this.values,this.getValueSize(),a)},InterpolantFactoryMethodSmooth:void 0});jc.prototype=Object.assign(Object.create(eb),{constructor:jc,ValueTypeName:"number"});Fd.prototype=Object.assign(Object.create(eb),{constructor:Fd,ValueTypeName:"string",ValueBufferType:Array,DefaultInterpolation:2300,InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0});Gd.prototype=Object.assign(Object.create(eb),{constructor:Gd,ValueTypeName:"bool",ValueBufferType:Array,DefaultInterpolation:2300,
17190 InterpolantFactoryMethodLinear:void 0,InterpolantFactoryMethodSmooth:void 0});Hd.prototype=Object.assign(Object.create(eb),{constructor:Hd,ValueTypeName:"color"});xb.prototype=eb;eb.constructor=xb;Object.assign(xb,{parse:function(a){if(void 0===a.type)throw Error("track type undefined, can not parse");var b=xb._getTrackTypeForValueTypeName(a.type);if(void 0===a.times){var c=[],d=[];T.flattenJSON(a.keys,c,d,"value");a.times=c;a.values=d}return void 0!==b.parse?b.parse(a):new b(a.name,a.times,a.values,
17191 a.interpolation)},toJSON:function(a){var b=a.constructor;if(void 0!==b.toJSON)b=b.toJSON(a);else{var b={name:a.name,times:T.convertArray(a.times,Array),values:T.convertArray(a.values,Array)},c=a.getInterpolation();c!==a.DefaultInterpolation&&(b.interpolation=c)}b.type=a.ValueTypeName;return b},_getTrackTypeForValueTypeName:function(a){switch(a.toLowerCase()){case "scalar":case "double":case "float":case "number":case "integer":return jc;case "vector":case "vector2":case "vector3":case "vector4":return ic;
17192 case "color":return Hd;case "quaternion":return Zc;case "bool":case "boolean":return Gd;case "string":return Fd}throw Error("Unsupported typeName: "+a);}});Object.assign(ka,{parse:function(a){for(var b=[],c=a.tracks,d=1/(a.fps||1),e=0,f=c.length;e!==f;++e)b.push(xb.parse(c[e]).scale(d));return new ka(a.name,a.duration,b)},toJSON:function(a){var b=[],c=a.tracks;a={name:a.name,duration:a.duration,tracks:b};for(var d=0,e=c.length;d!==e;++d)b.push(xb.toJSON(c[d]));return a},CreateFromMorphTargetSequence:function(a,
17193 b,c,d){for(var e=b.length,f=[],g=0;g<e;g++){var h=[],k=[];h.push((g+e-1)%e,g,(g+1)%e);k.push(0,1,0);var l=T.getKeyframeOrder(h),h=T.sortedArray(h,1,l),k=T.sortedArray(k,1,l);d||0!==h[0]||(h.push(e),k.push(k[0]));f.push((new jc(".morphTargetInfluences["+b[g].name+"]",h,k)).scale(1/c))}return new ka(a,-1,f)},findByName:function(a,b){var c=a;Array.isArray(a)||(c=a.geometry&&a.geometry.animations||a.animations);for(a=0;a<c.length;a++)if(c[a].name===b)return c[a];return null},CreateClipsFromMorphTargetSequences:function(a,
17194 b,c){for(var d,e={},f=/^([\w-]*?)([\d]+)$/,g=0,h=a.length;g<h;g++){var k=a[g],l=k.name.match(f);l&&1<l.length&&(d=l[1],(l=e[d])||(e[d]=l=[]),l.push(k))}a=[];for(d in e)a.push(ka.CreateFromMorphTargetSequence(d,e[d],b,c));return a},parseAnimation:function(a,b){if(!a)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;var c=function(a,b,c,d,e){if(0!==c.length){var f=[],g=[];T.flattenJSON(c,f,g,d);0!==f.length&&e.push(new a(b,f,g))}},d=[],e=a.name||"default",f=a.length||
17195 -1,g=a.fps||30;a=a.hierarchy||[];for(var h=0;h<a.length;h++){var k=a[h].keys;if(k&&0!==k.length)if(k[0].morphTargets){for(var f={},l=0;l<k.length;l++)if(k[l].morphTargets)for(var m=0;m<k[l].morphTargets.length;m++)f[k[l].morphTargets[m]]=-1;for(var n in f){for(var p=[],r=[],m=0;m!==k[l].morphTargets.length;++m){var u=k[l];p.push(u.time);r.push(u.morphTarget===n?1:0)}d.push(new jc(".morphTargetInfluence["+n+"]",p,r))}f=f.length*(g||1)}else l=".bones["+b[h].name+"]",c(ic,l+".position",k,"pos",d),c(Zc,
17196 l+".quaternion",k,"rot",d),c(ic,l+".scale",k,"scl",d)}return 0===d.length?null:new ka(e,f,d)}});Object.assign(ka.prototype,{resetDuration:function(){for(var a=0,b=0,c=this.tracks.length;b!==c;++b)var d=this.tracks[b],a=Math.max(a,d.times[d.times.length-1]);this.duration=a},trim:function(){for(var a=0;a<this.tracks.length;a++)this.tracks[a].trim(0,this.duration);return this},optimize:function(){for(var a=0;a<this.tracks.length;a++)this.tracks[a].optimize();return this}});Object.assign(Id.prototype,
17197 {load:function(a,b,c,d){var e=this;(new Ja(e.manager)).load(a,function(a){b(e.parse(JSON.parse(a)))},c,d)},setTextures:function(a){this.textures=a},parse:function(a){function b(a){void 0===c[a]&&console.warn("THREE.MaterialLoader: Undefined texture",a);return c[a]}var c=this.textures,d=new tg[a.type];void 0!==a.uuid&&(d.uuid=a.uuid);void 0!==a.name&&(d.name=a.name);void 0!==a.color&&d.color.setHex(a.color);void 0!==a.roughness&&(d.roughness=a.roughness);void 0!==a.metalness&&(d.metalness=a.metalness);
17198 void 0!==a.emissive&&d.emissive.setHex(a.emissive);void 0!==a.specular&&d.specular.setHex(a.specular);void 0!==a.shininess&&(d.shininess=a.shininess);void 0!==a.clearCoat&&(d.clearCoat=a.clearCoat);void 0!==a.clearCoatRoughness&&(d.clearCoatRoughness=a.clearCoatRoughness);void 0!==a.uniforms&&(d.uniforms=a.uniforms);void 0!==a.vertexShader&&(d.vertexShader=a.vertexShader);void 0!==a.fragmentShader&&(d.fragmentShader=a.fragmentShader);void 0!==a.vertexColors&&(d.vertexColors=a.vertexColors);void 0!==
17199 a.fog&&(d.fog=a.fog);void 0!==a.flatShading&&(d.flatShading=a.flatShading);void 0!==a.blending&&(d.blending=a.blending);void 0!==a.side&&(d.side=a.side);void 0!==a.opacity&&(d.opacity=a.opacity);void 0!==a.transparent&&(d.transparent=a.transparent);void 0!==a.alphaTest&&(d.alphaTest=a.alphaTest);void 0!==a.depthTest&&(d.depthTest=a.depthTest);void 0!==a.depthWrite&&(d.depthWrite=a.depthWrite);void 0!==a.colorWrite&&(d.colorWrite=a.colorWrite);void 0!==a.wireframe&&(d.wireframe=a.wireframe);void 0!==
17200 a.wireframeLinewidth&&(d.wireframeLinewidth=a.wireframeLinewidth);void 0!==a.wireframeLinecap&&(d.wireframeLinecap=a.wireframeLinecap);void 0!==a.wireframeLinejoin&&(d.wireframeLinejoin=a.wireframeLinejoin);void 0!==a.rotation&&(d.rotation=a.rotation);1!==a.linewidth&&(d.linewidth=a.linewidth);void 0!==a.dashSize&&(d.dashSize=a.dashSize);void 0!==a.gapSize&&(d.gapSize=a.gapSize);void 0!==a.scale&&(d.scale=a.scale);void 0!==a.skinning&&(d.skinning=a.skinning);void 0!==a.morphTargets&&(d.morphTargets=
17201 a.morphTargets);void 0!==a.dithering&&(d.dithering=a.dithering);void 0!==a.visible&&(d.visible=a.visible);void 0!==a.userData&&(d.userData=a.userData);void 0!==a.shading&&(d.flatShading=1===a.shading);void 0!==a.size&&(d.size=a.size);void 0!==a.sizeAttenuation&&(d.sizeAttenuation=a.sizeAttenuation);void 0!==a.map&&(d.map=b(a.map));void 0!==a.alphaMap&&(d.alphaMap=b(a.alphaMap),d.transparent=!0);void 0!==a.bumpMap&&(d.bumpMap=b(a.bumpMap));void 0!==a.bumpScale&&(d.bumpScale=a.bumpScale);void 0!==a.normalMap&&
17202 (d.normalMap=b(a.normalMap));if(void 0!==a.normalScale){var e=a.normalScale;!1===Array.isArray(e)&&(e=[e,e]);d.normalScale=(new C).fromArray(e)}void 0!==a.displacementMap&&(d.displacementMap=b(a.displacementMap));void 0!==a.displacementScale&&(d.displacementScale=a.displacementScale);void 0!==a.displacementBias&&(d.displacementBias=a.displacementBias);void 0!==a.roughnessMap&&(d.roughnessMap=b(a.roughnessMap));void 0!==a.metalnessMap&&(d.metalnessMap=b(a.metalnessMap));void 0!==a.emissiveMap&&(d.emissiveMap=
17203 b(a.emissiveMap));void 0!==a.emissiveIntensity&&(d.emissiveIntensity=a.emissiveIntensity);void 0!==a.specularMap&&(d.specularMap=b(a.specularMap));void 0!==a.envMap&&(d.envMap=b(a.envMap));void 0!==a.reflectivity&&(d.reflectivity=a.reflectivity);void 0!==a.lightMap&&(d.lightMap=b(a.lightMap));void 0!==a.lightMapIntensity&&(d.lightMapIntensity=a.lightMapIntensity);void 0!==a.aoMap&&(d.aoMap=b(a.aoMap));void 0!==a.aoMapIntensity&&(d.aoMapIntensity=a.aoMapIntensity);void 0!==a.gradientMap&&(d.gradientMap=
17204 b(a.gradientMap));return d}});Object.assign(ae.prototype,{load:function(a,b,c,d){var e=this;(new Ja(e.manager)).load(a,function(a){b(e.parse(JSON.parse(a)))},c,d)},parse:function(a){var b=new D;var c=a.data.index;void 0!==c&&(c=new gf[c.type](c.array),b.setIndex(new P(c,1)));var d=a.data.attributes;for(f in d){var e=d[f];c=new gf[e.type](e.array);b.addAttribute(f,new P(c,e.itemSize,e.normalized))}var f=a.data.groups||a.data.drawcalls||a.data.offsets;if(void 0!==f)for(c=0,d=f.length;c!==d;++c)e=f[c],
17205 b.addGroup(e.start,e.count,e.materialIndex);a=a.data.boundingSphere;void 0!==a&&(f=new p,void 0!==a.center&&f.fromArray(a.center),b.boundingSphere=new Da(f,a.radius));return b}});var gf={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:"undefined"!==typeof Uint8ClampedArray?Uint8ClampedArray:Uint8Array,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};kc.Handlers={handlers:[],add:function(a,b){this.handlers.push(a,
17206 b)},get:function(a){for(var b=this.handlers,c=0,d=b.length;c<d;c+=2){var e=b[c+1];if(b[c].test(a))return e}return null}};Object.assign(kc.prototype,{crossOrigin:void 0,extractUrlBase:function(a){a=a.split("/");if(1===a.length)return"./";a.pop();return a.join("/")+"/"},initMaterials:function(a,b,c){for(var d=[],e=0;e<a.length;++e)d[e]=this.createMaterial(a[e],b,c);return d},createMaterial:function(){var a={NoBlending:0,NormalBlending:1,AdditiveBlending:2,SubtractiveBlending:3,MultiplyBlending:4,CustomBlending:5},
17207 b=new H,c=new td,d=new Id;return function(e,f,g){function h(a,b,d,e,h){a=f+a;var l=kc.Handlers.get(a);null!==l?a=l.load(a):(c.setCrossOrigin(g),a=c.load(a));void 0!==b&&(a.repeat.fromArray(b),1!==b[0]&&(a.wrapS=1E3),1!==b[1]&&(a.wrapT=1E3));void 0!==d&&a.offset.fromArray(d);void 0!==e&&("repeat"===e[0]&&(a.wrapS=1E3),"mirror"===e[0]&&(a.wrapS=1002),"repeat"===e[1]&&(a.wrapT=1E3),"mirror"===e[1]&&(a.wrapT=1002));void 0!==h&&(a.anisotropy=h);b=R.generateUUID();k[b]=a;return b}var k={},l={uuid:R.generateUUID(),
17208 type:"MeshLambertMaterial"},m;for(m in e){var n=e[m];switch(m){case "DbgColor":case "DbgIndex":case "opticalDensity":case "illumination":break;case "DbgName":l.name=n;break;case "blending":l.blending=a[n];break;case "colorAmbient":case "mapAmbient":console.warn("THREE.Loader.createMaterial:",m,"is no longer supported.");break;case "colorDiffuse":l.color=b.fromArray(n).getHex();break;case "colorSpecular":l.specular=b.fromArray(n).getHex();break;case "colorEmissive":l.emissive=b.fromArray(n).getHex();
17209 break;case "specularCoef":l.shininess=n;break;case "shading":"basic"===n.toLowerCase()&&(l.type="MeshBasicMaterial");"phong"===n.toLowerCase()&&(l.type="MeshPhongMaterial");"standard"===n.toLowerCase()&&(l.type="MeshStandardMaterial");break;case "mapDiffuse":l.map=h(n,e.mapDiffuseRepeat,e.mapDiffuseOffset,e.mapDiffuseWrap,e.mapDiffuseAnisotropy);break;case "mapDiffuseRepeat":case "mapDiffuseOffset":case "mapDiffuseWrap":case "mapDiffuseAnisotropy":break;case "mapEmissive":l.emissiveMap=h(n,e.mapEmissiveRepeat,
17210 e.mapEmissiveOffset,e.mapEmissiveWrap,e.mapEmissiveAnisotropy);break;case "mapEmissiveRepeat":case "mapEmissiveOffset":case "mapEmissiveWrap":case "mapEmissiveAnisotropy":break;case "mapLight":l.lightMap=h(n,e.mapLightRepeat,e.mapLightOffset,e.mapLightWrap,e.mapLightAnisotropy);break;case "mapLightRepeat":case "mapLightOffset":case "mapLightWrap":case "mapLightAnisotropy":break;case "mapAO":l.aoMap=h(n,e.mapAORepeat,e.mapAOOffset,e.mapAOWrap,e.mapAOAnisotropy);break;case "mapAORepeat":case "mapAOOffset":case "mapAOWrap":case "mapAOAnisotropy":break;
17211 case "mapBump":l.bumpMap=h(n,e.mapBumpRepeat,e.mapBumpOffset,e.mapBumpWrap,e.mapBumpAnisotropy);break;case "mapBumpScale":l.bumpScale=n;break;case "mapBumpRepeat":case "mapBumpOffset":case "mapBumpWrap":case "mapBumpAnisotropy":break;case "mapNormal":l.normalMap=h(n,e.mapNormalRepeat,e.mapNormalOffset,e.mapNormalWrap,e.mapNormalAnisotropy);break;case "mapNormalFactor":l.normalScale=[n,n];break;case "mapNormalRepeat":case "mapNormalOffset":case "mapNormalWrap":case "mapNormalAnisotropy":break;case "mapSpecular":l.specularMap=
17212 h(n,e.mapSpecularRepeat,e.mapSpecularOffset,e.mapSpecularWrap,e.mapSpecularAnisotropy);break;case "mapSpecularRepeat":case "mapSpecularOffset":case "mapSpecularWrap":case "mapSpecularAnisotropy":break;case "mapMetalness":l.metalnessMap=h(n,e.mapMetalnessRepeat,e.mapMetalnessOffset,e.mapMetalnessWrap,e.mapMetalnessAnisotropy);break;case "mapMetalnessRepeat":case "mapMetalnessOffset":case "mapMetalnessWrap":case "mapMetalnessAnisotropy":break;case "mapRoughness":l.roughnessMap=h(n,e.mapRoughnessRepeat,
17213 e.mapRoughnessOffset,e.mapRoughnessWrap,e.mapRoughnessAnisotropy);break;case "mapRoughnessRepeat":case "mapRoughnessOffset":case "mapRoughnessWrap":case "mapRoughnessAnisotropy":break;case "mapAlpha":l.alphaMap=h(n,e.mapAlphaRepeat,e.mapAlphaOffset,e.mapAlphaWrap,e.mapAlphaAnisotropy);break;case "mapAlphaRepeat":case "mapAlphaOffset":case "mapAlphaWrap":case "mapAlphaAnisotropy":break;case "flipSided":l.side=1;break;case "doubleSided":l.side=2;break;case "transparency":console.warn("THREE.Loader.createMaterial: transparency has been renamed to opacity");
17214 l.opacity=n;break;case "depthTest":case "depthWrite":case "colorWrite":case "opacity":case "reflectivity":case "transparent":case "visible":case "wireframe":l[m]=n;break;case "vertexColors":!0===n&&(l.vertexColors=2);"face"===n&&(l.vertexColors=1);break;default:console.error("THREE.Loader.createMaterial: Unsupported",m,n)}}"MeshBasicMaterial"===l.type&&delete l.emissive;"MeshPhongMaterial"!==l.type&&delete l.specular;1>l.opacity&&(l.transparent=!0);d.setTextures(k);return d.parse(l)}}()});Object.assign(be.prototype,
17215 {load:function(a,b,c,d){var e=this,f=this.texturePath&&"string"===typeof this.texturePath?this.texturePath:kc.prototype.extractUrlBase(a),g=new Ja(this.manager);g.setWithCredentials(this.withCredentials);g.load(a,function(c){c=JSON.parse(c);var d=c.metadata;if(void 0!==d&&(d=d.type,void 0!==d)){if("object"===d.toLowerCase()){console.error("THREE.JSONLoader: "+a+" should be loaded with THREE.ObjectLoader instead.");return}if("scene"===d.toLowerCase()){console.error("THREE.JSONLoader: "+a+" should be loaded with THREE.SceneLoader instead.");
17216 return}}c=e.parse(c,f);b(c.geometry,c.materials)},c,d)},setTexturePath:function(a){this.texturePath=a},parse:function(){return function(a,b){void 0!==a.data&&(a=a.data);a.scale=void 0!==a.scale?1/a.scale:1;var c=new N,d=a,e,f,g,h=d.faces;var k=d.vertices;var l=d.normals,m=d.colors;var n=d.scale;var t=0;if(void 0!==d.uvs){for(e=0;e<d.uvs.length;e++)d.uvs[e].length&&t++;for(e=0;e<t;e++)c.faceVertexUvs[e]=[]}var r=0;for(g=k.length;r<g;)e=new p,e.x=k[r++]*n,e.y=k[r++]*n,e.z=k[r++]*n,c.vertices.push(e);
17217 r=0;for(g=h.length;r<g;){k=h[r++];var u=k&1;var v=k&2;e=k&8;var w=k&16;var x=k&32;n=k&64;k&=128;if(u){u=new Pa;u.a=h[r];u.b=h[r+1];u.c=h[r+3];var z=new Pa;z.a=h[r+1];z.b=h[r+2];z.c=h[r+3];r+=4;v&&(v=h[r++],u.materialIndex=v,z.materialIndex=v);v=c.faces.length;if(e)for(e=0;e<t;e++){var y=d.uvs[e];c.faceVertexUvs[e][v]=[];c.faceVertexUvs[e][v+1]=[];for(f=0;4>f;f++){var B=h[r++];var A=y[2*B];B=y[2*B+1];A=new C(A,B);2!==f&&c.faceVertexUvs[e][v].push(A);0!==f&&c.faceVertexUvs[e][v+1].push(A)}}w&&(w=3*
17218 h[r++],u.normal.set(l[w++],l[w++],l[w]),z.normal.copy(u.normal));if(x)for(e=0;4>e;e++)w=3*h[r++],x=new p(l[w++],l[w++],l[w]),2!==e&&u.vertexNormals.push(x),0!==e&&z.vertexNormals.push(x);n&&(n=h[r++],n=m[n],u.color.setHex(n),z.color.setHex(n));if(k)for(e=0;4>e;e++)n=h[r++],n=m[n],2!==e&&u.vertexColors.push(new H(n)),0!==e&&z.vertexColors.push(new H(n));c.faces.push(u);c.faces.push(z)}else{u=new Pa;u.a=h[r++];u.b=h[r++];u.c=h[r++];v&&(v=h[r++],u.materialIndex=v);v=c.faces.length;if(e)for(e=0;e<t;e++)for(y=
17219 d.uvs[e],c.faceVertexUvs[e][v]=[],f=0;3>f;f++)B=h[r++],A=y[2*B],B=y[2*B+1],A=new C(A,B),c.faceVertexUvs[e][v].push(A);w&&(w=3*h[r++],u.normal.set(l[w++],l[w++],l[w]));if(x)for(e=0;3>e;e++)w=3*h[r++],x=new p(l[w++],l[w++],l[w]),u.vertexNormals.push(x);n&&(n=h[r++],u.color.setHex(m[n]));if(k)for(e=0;3>e;e++)n=h[r++],u.vertexColors.push(new H(m[n]));c.faces.push(u)}}d=a;r=void 0!==d.influencesPerVertex?d.influencesPerVertex:2;if(d.skinWeights)for(g=0,h=d.skinWeights.length;g<h;g+=r)c.skinWeights.push(new da(d.skinWeights[g],
17220 1<r?d.skinWeights[g+1]:0,2<r?d.skinWeights[g+2]:0,3<r?d.skinWeights[g+3]:0));if(d.skinIndices)for(g=0,h=d.skinIndices.length;g<h;g+=r)c.skinIndices.push(new da(d.skinIndices[g],1<r?d.skinIndices[g+1]:0,2<r?d.skinIndices[g+2]:0,3<r?d.skinIndices[g+3]:0));c.bones=d.bones;c.bones&&0<c.bones.length&&(c.skinWeights.length!==c.skinIndices.length||c.skinIndices.length!==c.vertices.length)&&console.warn("When skinning, number of vertices ("+c.vertices.length+"), skinIndices ("+c.skinIndices.length+"), and skinWeights ("+
17221 c.skinWeights.length+") should match.");g=a;h=g.scale;if(void 0!==g.morphTargets)for(d=0,r=g.morphTargets.length;d<r;d++)for(c.morphTargets[d]={},c.morphTargets[d].name=g.morphTargets[d].name,c.morphTargets[d].vertices=[],l=c.morphTargets[d].vertices,m=g.morphTargets[d].vertices,t=0,k=m.length;t<k;t+=3)n=new p,n.x=m[t]*h,n.y=m[t+1]*h,n.z=m[t+2]*h,l.push(n);if(void 0!==g.morphColors&&0<g.morphColors.length)for(console.warn('THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.'),
17222 h=c.faces,g=g.morphColors[0].colors,d=0,r=h.length;d<r;d++)h[d].color.fromArray(g,3*d);g=a;d=[];r=[];void 0!==g.animation&&r.push(g.animation);void 0!==g.animations&&(g.animations.length?r=r.concat(g.animations):r.push(g.animations));for(g=0;g<r.length;g++)(h=ka.parseAnimation(r[g],c.bones))&&d.push(h);c.morphTargets&&(r=ka.CreateClipsFromMorphTargetSequences(c.morphTargets,10),d=d.concat(r));0<d.length&&(c.animations=d);c.computeFaceNormals();c.computeBoundingSphere();if(void 0===a.materials||0===
17223 a.materials.length)return{geometry:c};a=kc.prototype.initMaterials(a.materials,b,this.crossOrigin);return{geometry:c,materials:a}}}()});Object.assign(Re.prototype,{load:function(a,b,c,d){""===this.texturePath&&(this.texturePath=a.substring(0,a.lastIndexOf("/")+1));var e=this;(new Ja(e.manager)).load(a,function(c){var f=null;try{f=JSON.parse(c)}catch(h){void 0!==d&&d(h);console.error("THREE:ObjectLoader: Can't parse "+a+".",h.message);return}c=f.metadata;void 0===c||void 0===c.type||"geometry"===c.type.toLowerCase()?
17224 console.error("THREE.ObjectLoader: Can't load "+a+". Use THREE.JSONLoader instead."):e.parse(f,b)},c,d)},setTexturePath:function(a){this.texturePath=a},setCrossOrigin:function(a){this.crossOrigin=a},parse:function(a,b){var c=this.parseGeometries(a.geometries),d=this.parseImages(a.images,function(){void 0!==b&&b(e)}),d=this.parseTextures(a.textures,d),d=this.parseMaterials(a.materials,d),e=this.parseObject(a.object,c,d);a.animations&&(e.animations=this.parseAnimations(a.animations));void 0!==a.images&&
17225 0!==a.images.length||void 0===b||b(e);return e},parseGeometries:function(a){var b={};if(void 0!==a)for(var c=new be,d=new ae,e=0,f=a.length;e<f;e++){var g=a[e];switch(g.type){case "PlaneGeometry":case "PlaneBufferGeometry":var h=new Ca[g.type](g.width,g.height,g.widthSegments,g.heightSegments);break;case "BoxGeometry":case "BoxBufferGeometry":case "CubeGeometry":h=new Ca[g.type](g.width,g.height,g.depth,g.widthSegments,g.heightSegments,g.depthSegments);break;case "CircleGeometry":case "CircleBufferGeometry":h=
17226 new Ca[g.type](g.radius,g.segments,g.thetaStart,g.thetaLength);break;case "CylinderGeometry":case "CylinderBufferGeometry":h=new Ca[g.type](g.radiusTop,g.radiusBottom,g.height,g.radialSegments,g.heightSegments,g.openEnded,g.thetaStart,g.thetaLength);break;case "ConeGeometry":case "ConeBufferGeometry":h=new Ca[g.type](g.radius,g.height,g.radialSegments,g.heightSegments,g.openEnded,g.thetaStart,g.thetaLength);break;case "SphereGeometry":case "SphereBufferGeometry":h=new Ca[g.type](g.radius,g.widthSegments,
17227 g.heightSegments,g.phiStart,g.phiLength,g.thetaStart,g.thetaLength);break;case "DodecahedronGeometry":case "DodecahedronBufferGeometry":case "IcosahedronGeometry":case "IcosahedronBufferGeometry":case "OctahedronGeometry":case "OctahedronBufferGeometry":case "TetrahedronGeometry":case "TetrahedronBufferGeometry":h=new Ca[g.type](g.radius,g.detail);break;case "RingGeometry":case "RingBufferGeometry":h=new Ca[g.type](g.innerRadius,g.outerRadius,g.thetaSegments,g.phiSegments,g.thetaStart,g.thetaLength);
17228 break;case "TorusGeometry":case "TorusBufferGeometry":h=new Ca[g.type](g.radius,g.tube,g.radialSegments,g.tubularSegments,g.arc);break;case "TorusKnotGeometry":case "TorusKnotBufferGeometry":h=new Ca[g.type](g.radius,g.tube,g.tubularSegments,g.radialSegments,g.p,g.q);break;case "LatheGeometry":case "LatheBufferGeometry":h=new Ca[g.type](g.points,g.segments,g.phiStart,g.phiLength);break;case "PolyhedronGeometry":case "PolyhedronBufferGeometry":h=new Ca[g.type](g.vertices,g.indices,g.radius,g.details);
17229 break;case "BufferGeometry":h=d.parse(g);break;case "Geometry":h=c.parse(g,this.texturePath).geometry;break;default:console.warn('THREE.ObjectLoader: Unsupported geometry type "'+g.type+'"');continue}h.uuid=g.uuid;void 0!==g.name&&(h.name=g.name);b[g.uuid]=h}return b},parseMaterials:function(a,b){var c={};if(void 0!==a){var d=new Id;d.setTextures(b);b=0;for(var e=a.length;b<e;b++){var f=a[b];if("MultiMaterial"===f.type){for(var g=[],h=0;h<f.materials.length;h++)g.push(d.parse(f.materials[h]));c[f.uuid]=
17230 g}else c[f.uuid]=d.parse(f)}}return c},parseAnimations:function(a){for(var b=[],c=0;c<a.length;c++){var d=ka.parse(a[c]);b.push(d)}return b},parseImages:function(a,b){function c(a){d.manager.itemStart(a);return f.load(a,function(){d.manager.itemEnd(a)},void 0,function(){d.manager.itemEnd(a);d.manager.itemError(a)})}var d=this,e={};if(void 0!==a&&0<a.length){b=new Yd(b);var f=new Xc(b);f.setCrossOrigin(this.crossOrigin);b=0;for(var g=a.length;b<g;b++){var h=a[b],k=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(h.url)?
17231 h.url:d.texturePath+h.url;e[h.uuid]=c(k)}}return e},parseTextures:function(a,b){function c(a,b){if("number"===typeof a)return a;console.warn("THREE.ObjectLoader.parseTexture: Constant should be in numeric form.",a);return b[a]}var d={};if(void 0!==a)for(var e=0,f=a.length;e<f;e++){var g=a[e];void 0===g.image&&console.warn('THREE.ObjectLoader: No "image" specified for',g.uuid);void 0===b[g.image]&&console.warn("THREE.ObjectLoader: Undefined image",g.image);var h=new ea(b[g.image]);h.needsUpdate=!0;
17232 h.uuid=g.uuid;void 0!==g.name&&(h.name=g.name);void 0!==g.mapping&&(h.mapping=c(g.mapping,ug));void 0!==g.offset&&h.offset.fromArray(g.offset);void 0!==g.repeat&&h.repeat.fromArray(g.repeat);void 0!==g.center&&h.center.fromArray(g.center);void 0!==g.rotation&&(h.rotation=g.rotation);void 0!==g.wrap&&(h.wrapS=c(g.wrap[0],hf),h.wrapT=c(g.wrap[1],hf));void 0!==g.minFilter&&(h.minFilter=c(g.minFilter,jf));void 0!==g.magFilter&&(h.magFilter=c(g.magFilter,jf));void 0!==g.anisotropy&&(h.anisotropy=g.anisotropy);
17233 void 0!==g.flipY&&(h.flipY=g.flipY);d[g.uuid]=h}return d},parseObject:function(){var a=new K;return function(b,c,d){function e(a){void 0===c[a]&&console.warn("THREE.ObjectLoader: Undefined geometry",a);return c[a]}function f(a){if(void 0!==a){if(Array.isArray(a)){for(var b=[],c=0,e=a.length;c<e;c++){var f=a[c];void 0===d[f]&&console.warn("THREE.ObjectLoader: Undefined material",f);b.push(d[f])}return b}void 0===d[a]&&console.warn("THREE.ObjectLoader: Undefined material",a);return d[a]}}switch(b.type){case "Scene":var g=
17234 new od;void 0!==b.background&&Number.isInteger(b.background)&&(g.background=new H(b.background));void 0!==b.fog&&("Fog"===b.fog.type?g.fog=new Pb(b.fog.color,b.fog.near,b.fog.far):"FogExp2"===b.fog.type&&(g.fog=new Ob(b.fog.color,b.fog.density)));break;case "PerspectiveCamera":g=new U(b.fov,b.aspect,b.near,b.far);void 0!==b.focus&&(g.focus=b.focus);void 0!==b.zoom&&(g.zoom=b.zoom);void 0!==b.filmGauge&&(g.filmGauge=b.filmGauge);void 0!==b.filmOffset&&(g.filmOffset=b.filmOffset);void 0!==b.view&&(g.view=
17235 Object.assign({},b.view));break;case "OrthographicCamera":g=new Kb(b.left,b.right,b.top,b.bottom,b.near,b.far);break;case "AmbientLight":g=new Ad(b.color,b.intensity);break;case "DirectionalLight":g=new zd(b.color,b.intensity);break;case "PointLight":g=new xd(b.color,b.intensity,b.distance,b.decay);break;case "RectAreaLight":g=new Bd(b.color,b.intensity,b.width,b.height);break;case "SpotLight":g=new wd(b.color,b.intensity,b.distance,b.angle,b.penumbra,b.decay);break;case "HemisphereLight":g=new ud(b.color,
17236 b.groundColor,b.intensity);break;case "SkinnedMesh":console.warn("THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.");case "Mesh":g=e(b.geometry);var h=f(b.material);g=g.bones&&0<g.bones.length?new qd(g,h):new pa(g,h);break;case "LOD":g=new Dc;break;case "Line":g=new ma(e(b.geometry),f(b.material),b.mode);break;case "LineLoop":g=new rd(e(b.geometry),f(b.material));break;case "LineSegments":g=new ca(e(b.geometry),f(b.material));break;case "PointCloud":case "Points":g=new Qb(e(b.geometry),
17237 f(b.material));break;case "Sprite":g=new Cc(f(b.material));break;case "Group":g=new Fc;break;default:g=new A}g.uuid=b.uuid;void 0!==b.name&&(g.name=b.name);void 0!==b.matrix?(a.fromArray(b.matrix),a.decompose(g.position,g.quaternion,g.scale)):(void 0!==b.position&&g.position.fromArray(b.position),void 0!==b.rotation&&g.rotation.fromArray(b.rotation),void 0!==b.quaternion&&g.quaternion.fromArray(b.quaternion),void 0!==b.scale&&g.scale.fromArray(b.scale));void 0!==b.castShadow&&(g.castShadow=b.castShadow);
17238 void 0!==b.receiveShadow&&(g.receiveShadow=b.receiveShadow);b.shadow&&(void 0!==b.shadow.bias&&(g.shadow.bias=b.shadow.bias),void 0!==b.shadow.radius&&(g.shadow.radius=b.shadow.radius),void 0!==b.shadow.mapSize&&g.shadow.mapSize.fromArray(b.shadow.mapSize),void 0!==b.shadow.camera&&(g.shadow.camera=this.parseObject(b.shadow.camera)));void 0!==b.visible&&(g.visible=b.visible);void 0!==b.userData&&(g.userData=b.userData);if(void 0!==b.children)for(var h=b.children,k=0;k<h.length;k++)g.add(this.parseObject(h[k],
17239 c,d));if("LOD"===b.type)for(b=b.levels,h=0;h<b.length;h++){var k=b[h],l=g.getObjectByProperty("uuid",k.object);void 0!==l&&g.addLevel(l,k.distance)}return g}}()});var ug={UVMapping:300,CubeReflectionMapping:301,CubeRefractionMapping:302,EquirectangularReflectionMapping:303,EquirectangularRefractionMapping:304,SphericalReflectionMapping:305,CubeUVReflectionMapping:306,CubeUVRefractionMapping:307},hf={RepeatWrapping:1E3,ClampToEdgeWrapping:1001,MirroredRepeatWrapping:1002},jf={NearestFilter:1003,NearestMipMapNearestFilter:1004,
17240 NearestMipMapLinearFilter:1005,LinearFilter:1006,LinearMipMapNearestFilter:1007,LinearMipMapLinearFilter:1008};Object.assign(S.prototype,{getPoint:function(){console.warn("THREE.Curve: .getPoint() not implemented.");return null},getPointAt:function(a,b){a=this.getUtoTmapping(a);return this.getPoint(a,b)},getPoints:function(a){void 0===a&&(a=5);for(var b=[],c=0;c<=a;c++)b.push(this.getPoint(c/a));return b},getSpacedPoints:function(a){void 0===a&&(a=5);for(var b=[],c=0;c<=a;c++)b.push(this.getPointAt(c/
17241 a));return b},getLength:function(){var a=this.getLengths();return a[a.length-1]},getLengths:function(a){void 0===a&&(a=this.arcLengthDivisions);if(this.cacheArcLengths&&this.cacheArcLengths.length===a+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var b=[],c=this.getPoint(0),d,e=0;b.push(0);for(d=1;d<=a;d++){var f=this.getPoint(d/a);e+=f.distanceTo(c);b.push(e);c=f}return this.cacheArcLengths=b},updateArcLengths:function(){this.needsUpdate=!0;this.getLengths()},getUtoTmapping:function(a,
17242 b){var c=this.getLengths(),d=c.length;b=b?b:a*c[d-1];for(var e=0,f=d-1,g;e<=f;)if(a=Math.floor(e+(f-e)/2),g=c[a]-b,0>g)e=a+1;else if(0<g)f=a-1;else{f=a;break}a=f;if(c[a]===b)return a/(d-1);e=c[a];return(a+(b-e)/(c[a+1]-e))/(d-1)},getTangent:function(a){var b=a-1E-4;a+=1E-4;0>b&&(b=0);1<a&&(a=1);b=this.getPoint(b);return this.getPoint(a).clone().sub(b).normalize()},getTangentAt:function(a){a=this.getUtoTmapping(a);return this.getTangent(a)},computeFrenetFrames:function(a,b){var c=new p,d=[],e=[],f=
17243 [],g=new p,h=new K,k;for(k=0;k<=a;k++){var l=k/a;d[k]=this.getTangentAt(l);d[k].normalize()}e[0]=new p;f[0]=new p;k=Number.MAX_VALUE;l=Math.abs(d[0].x);var m=Math.abs(d[0].y),n=Math.abs(d[0].z);l<=k&&(k=l,c.set(1,0,0));m<=k&&(k=m,c.set(0,1,0));n<=k&&c.set(0,0,1);g.crossVectors(d[0],c).normalize();e[0].crossVectors(d[0],g);f[0].crossVectors(d[0],e[0]);for(k=1;k<=a;k++)e[k]=e[k-1].clone(),f[k]=f[k-1].clone(),g.crossVectors(d[k-1],d[k]),g.length()>Number.EPSILON&&(g.normalize(),c=Math.acos(R.clamp(d[k-
17244 1].dot(d[k]),-1,1)),e[k].applyMatrix4(h.makeRotationAxis(g,c))),f[k].crossVectors(d[k],e[k]);if(!0===b)for(c=Math.acos(R.clamp(e[0].dot(e[a]),-1,1)),c/=a,0<d[0].dot(g.crossVectors(e[0],e[a]))&&(c=-c),k=1;k<=a;k++)e[k].applyMatrix4(h.makeRotationAxis(d[k],c*k)),f[k].crossVectors(d[k],e[k]);return{tangents:d,normals:e,binormals:f}},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.arcLengthDivisions=a.arcLengthDivisions;return this}});Ka.prototype=Object.create(S.prototype);
17245 Ka.prototype.constructor=Ka;Ka.prototype.isLineCurve=!0;Ka.prototype.getPoint=function(a,b){b=b||new C;1===a?b.copy(this.v2):(b.copy(this.v2).sub(this.v1),b.multiplyScalar(a).add(this.v1));return b};Ka.prototype.getPointAt=function(a,b){return this.getPoint(a,b)};Ka.prototype.getTangent=function(){return this.v2.clone().sub(this.v1).normalize()};Ka.prototype.copy=function(a){S.prototype.copy.call(this,a);this.v1.copy(a.v1);this.v2.copy(a.v2);return this};Ab.prototype=Object.assign(Object.create(S.prototype),
17246 {constructor:Ab,add:function(a){this.curves.push(a)},closePath:function(){var a=this.curves[0].getPoint(0),b=this.curves[this.curves.length-1].getPoint(1);a.equals(b)||this.curves.push(new Ka(b,a))},getPoint:function(a){var b=a*this.getLength(),c=this.getCurveLengths();for(a=0;a<c.length;){if(c[a]>=b)return b=c[a]-b,a=this.curves[a],c=a.getLength(),a.getPointAt(0===c?0:1-b/c);a++}return null},getLength:function(){var a=this.getCurveLengths();return a[a.length-1]},updateArcLengths:function(){this.needsUpdate=
17247 !0;this.cacheLengths=null;this.getCurveLengths()},getCurveLengths:function(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;for(var a=[],b=0,c=0,d=this.curves.length;c<d;c++)b+=this.curves[c].getLength(),a.push(b);return this.cacheLengths=a},getSpacedPoints:function(a){void 0===a&&(a=40);for(var b=[],c=0;c<=a;c++)b.push(this.getPoint(c/a));this.autoClose&&b.push(b[0]);return b},getPoints:function(a){a=a||12;for(var b=[],c,d=0,e=this.curves;d<e.length;d++)for(var f=
17248 e[d],f=f.getPoints(f&&f.isEllipseCurve?2*a:f&&f.isLineCurve?1:f&&f.isSplineCurve?a*f.points.length:a),g=0;g<f.length;g++){var h=f[g];c&&c.equals(h)||(b.push(h),c=h)}this.autoClose&&1<b.length&&!b[b.length-1].equals(b[0])&&b.push(b[0]);return b},copy:function(a){S.prototype.copy.call(this,a);this.curves=[];for(var b=0,c=a.curves.length;b<c;b++)this.curves.push(a.curves[b].clone());this.autoClose=a.autoClose;return this}});Na.prototype=Object.create(S.prototype);Na.prototype.constructor=Na;Na.prototype.isEllipseCurve=
17249 !0;Na.prototype.getPoint=function(a,b){b=b||new C;for(var c=2*Math.PI,d=this.aEndAngle-this.aStartAngle,e=Math.abs(d)<Number.EPSILON;0>d;)d+=c;for(;d>c;)d-=c;d<Number.EPSILON&&(d=e?0:c);!0!==this.aClockwise||e||(d=d===c?-c:d-c);c=this.aStartAngle+a*d;a=this.aX+this.xRadius*Math.cos(c);var f=this.aY+this.yRadius*Math.sin(c);0!==this.aRotation&&(c=Math.cos(this.aRotation),d=Math.sin(this.aRotation),e=a-this.aX,f-=this.aY,a=e*c-f*d+this.aX,f=e*d+f*c+this.aY);return b.set(a,f)};Na.prototype.copy=function(a){S.prototype.copy.call(this,
17250 a);this.aX=a.aX;this.aY=a.aY;this.xRadius=a.xRadius;this.yRadius=a.yRadius;this.aStartAngle=a.aStartAngle;this.aEndAngle=a.aEndAngle;this.aClockwise=a.aClockwise;this.aRotation=a.aRotation;return this};ab.prototype=Object.create(S.prototype);ab.prototype.constructor=ab;ab.prototype.isSplineCurve=!0;ab.prototype.getPoint=function(a,b){b=b||new C;var c=this.points,d=(c.length-1)*a;a=Math.floor(d);var d=d-a,e=c[0===a?a:a-1],f=c[a],g=c[a>c.length-2?c.length-1:a+1],c=c[a>c.length-3?c.length-1:a+2];b.set(Se(d,
17251 e.x,f.x,g.x,c.x),Se(d,e.y,f.y,g.y,c.y));return b};ab.prototype.copy=function(a){S.prototype.copy.call(this,a);this.points=[];for(var b=0,c=a.points.length;b<c;b++)this.points.push(a.points[b].clone());return this};bb.prototype=Object.create(S.prototype);bb.prototype.constructor=bb;bb.prototype.isCubicBezierCurve=!0;bb.prototype.getPoint=function(a,b){b=b||new C;var c=this.v0,d=this.v1,e=this.v2,f=this.v3;b.set(zb(a,c.x,d.x,e.x,f.x),zb(a,c.y,d.y,e.y,f.y));return b};bb.prototype.copy=function(a){S.prototype.copy.call(this,
17252 a);this.v0.copy(a.v0);this.v1.copy(a.v1);this.v2.copy(a.v2);this.v3.copy(a.v3);return this};cb.prototype=Object.create(S.prototype);cb.prototype.constructor=cb;cb.prototype.isQuadraticBezierCurve=!0;cb.prototype.getPoint=function(a,b){b=b||new C;var c=this.v0,d=this.v1,e=this.v2;b.set(yb(a,c.x,d.x,e.x),yb(a,c.y,d.y,e.y));return b};cb.prototype.copy=function(a){S.prototype.copy.call(this,a);this.v0.copy(a.v0);this.v1.copy(a.v1);this.v2.copy(a.v2);return this};var se=Object.assign(Object.create(Ab.prototype),
17253 {setFromPoints:function(a){this.moveTo(a[0].x,a[0].y);for(var b=1,c=a.length;b<c;b++)this.lineTo(a[b].x,a[b].y)},moveTo:function(a,b){this.currentPoint.set(a,b)},lineTo:function(a,b){var c=new Ka(this.currentPoint.clone(),new C(a,b));this.curves.push(c);this.currentPoint.set(a,b)},quadraticCurveTo:function(a,b,c,d){a=new cb(this.currentPoint.clone(),new C(a,b),new C(c,d));this.curves.push(a);this.currentPoint.set(c,d)},bezierCurveTo:function(a,b,c,d,e,f){a=new bb(this.currentPoint.clone(),new C(a,
17254 b),new C(c,d),new C(e,f));this.curves.push(a);this.currentPoint.set(e,f)},splineThru:function(a){var b=[this.currentPoint.clone()].concat(a),b=new ab(b);this.curves.push(b);this.currentPoint.copy(a[a.length-1])},arc:function(a,b,c,d,e,f){this.absarc(a+this.currentPoint.x,b+this.currentPoint.y,c,d,e,f)},absarc:function(a,b,c,d,e,f){this.absellipse(a,b,c,c,d,e,f)},ellipse:function(a,b,c,d,e,f,g,h){this.absellipse(a+this.currentPoint.x,b+this.currentPoint.y,c,d,e,f,g,h)},absellipse:function(a,b,c,d,
17255 e,f,g,h){a=new Na(a,b,c,d,e,f,g,h);0<this.curves.length&&(b=a.getPoint(0),b.equals(this.currentPoint)||this.lineTo(b.x,b.y));this.curves.push(a);a=a.getPoint(1);this.currentPoint.copy(a)},copy:function(a){Ab.prototype.copy.call(this,a);this.currentPoint.copy(a.currentPoint);return this}});Bb.prototype=se;se.constructor=Bb;Cb.prototype=Object.assign(Object.create(se),{constructor:Cb,getPointsHoles:function(a){for(var b=[],c=0,d=this.holes.length;c<d;c++)b[c]=this.holes[c].getPoints(a);return b},extractPoints:function(a){return{shape:this.getPoints(a),
17256 holes:this.getPointsHoles(a)}},copy:function(a){Bb.prototype.copy.call(this,a);this.holes=[];for(var b=0,c=a.holes.length;b<c;b++)this.holes.push(a.holes[b].clone());return this}});Object.assign(ce.prototype,{moveTo:function(a,b){this.currentPath=new Bb;this.subPaths.push(this.currentPath);this.currentPath.moveTo(a,b)},lineTo:function(a,b){this.currentPath.lineTo(a,b)},quadraticCurveTo:function(a,b,c,d){this.currentPath.quadraticCurveTo(a,b,c,d)},bezierCurveTo:function(a,b,c,d,e,f){this.currentPath.bezierCurveTo(a,
17257 b,c,d,e,f)},splineThru:function(a){this.currentPath.splineThru(a)},toShapes:function(a,b){function c(a){for(var b=[],c=0,d=a.length;c<d;c++){var e=a[c],f=new Cb;f.curves=e.curves;b.push(f)}return b}function d(a,b){for(var c=b.length,d=!1,e=c-1,f=0;f<c;e=f++){var g=b[e],h=b[f],k=h.x-g.x,l=h.y-g.y;if(Math.abs(l)>Number.EPSILON){if(0>l&&(g=b[f],k=-k,h=b[e],l=-l),!(a.y<g.y||a.y>h.y))if(a.y===g.y){if(a.x===g.x)return!0}else{e=l*(a.x-g.x)-k*(a.y-g.y);if(0===e)return!0;0>e||(d=!d)}}else if(a.y===g.y&&(h.x<=
17258 a.x&&a.x<=g.x||g.x<=a.x&&a.x<=h.x))return!0}return d}var e=Ha.isClockWise,f=this.subPaths;if(0===f.length)return[];if(!0===b)return c(f);b=[];if(1===f.length){var g=f[0];var h=new Cb;h.curves=g.curves;b.push(h);return b}var k=!e(f[0].getPoints()),k=a?!k:k;h=[];var l=[],m=[],n=0;l[n]=void 0;m[n]=[];for(var p=0,r=f.length;p<r;p++){g=f[p];var u=g.getPoints();var v=e(u);(v=a?!v:v)?(!k&&l[n]&&n++,l[n]={s:new Cb,p:u},l[n].s.curves=g.curves,k&&n++,m[n]=[]):m[n].push({h:g,p:u[0]})}if(!l[0])return c(f);if(1<
17259 l.length){p=!1;a=[];e=0;for(f=l.length;e<f;e++)h[e]=[];e=0;for(f=l.length;e<f;e++)for(g=m[e],v=0;v<g.length;v++){k=g[v];n=!0;for(u=0;u<l.length;u++)d(k.p,l[u].p)&&(e!==u&&a.push({froms:e,tos:u,hole:v}),n?(n=!1,h[u].push(k)):p=!0);n&&h[e].push(k)}0<a.length&&(p||(m=h))}p=0;for(e=l.length;p<e;p++)for(h=l[p].s,b.push(h),a=m[p],f=0,g=a.length;f<g;f++)h.holes.push(a[f].h);return b}});Object.assign(de.prototype,{isFont:!0,generateShapes:function(a,b,c){void 0===b&&(b=100);void 0===c&&(c=4);var d=this.data;
17260 a=String(a).split("");var e=b/d.resolution,f=(d.boundingBox.yMax-d.boundingBox.yMin+d.underlineThickness)*e,g=0,h=0;b=[];for(var k=0;k<a.length;k++){var l=a[k];if("\n"===l)g=0,h-=f;else{var m;var n=e;var p=g,r=h;if(l=d.glyphs[l]||d.glyphs["?"]){var u=new ce,v=[];if(l.o)for(var w=l._cachedOutline||(l._cachedOutline=l.o.split(" ")),x=0,y=w.length;x<y;)switch(w[x++]){case "m":var A=w[x++]*n+p;var B=w[x++]*n+r;u.moveTo(A,B);break;case "l":A=w[x++]*n+p;B=w[x++]*n+r;u.lineTo(A,B);break;case "q":var C=w[x++]*
17261 n+p;var D=w[x++]*n+r;var E=w[x++]*n+p;var H=w[x++]*n+r;u.quadraticCurveTo(E,H,C,D);if(m=v[v.length-1]){var N=m.x;m=m.y;for(var K=1;K<=c;K++){var O=K/c;yb(O,N,E,C);yb(O,m,H,D)}}break;case "b":if(C=w[x++]*n+p,D=w[x++]*n+r,E=w[x++]*n+p,H=w[x++]*n+r,A=w[x++]*n+p,B=w[x++]*n+r,u.bezierCurveTo(E,H,A,B,C,D),m=v[v.length-1])for(N=m.x,m=m.y,K=1;K<=c;K++)O=K/c,zb(O,N,E,A,C),zb(O,m,H,B,D)}n={offsetX:l.ha*n,path:u}}else n=void 0;g+=n.offsetX;b.push(n.path)}}c=[];d=0;for(a=b.length;d<a;d++)Array.prototype.push.apply(c,
17262 b[d].toShapes());return c}});Object.assign(Te.prototype,{load:function(a,b,c,d){var e=this,f=new Ja(this.manager);f.setPath(this.path);f.load(a,function(a){try{var c=JSON.parse(a)}catch(k){console.warn("THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead."),c=JSON.parse(a.substring(65,a.length-2))}a=e.parse(c);b&&b(a)},c,d)},parse:function(a){return new de(a)},setPath:function(a){this.path=a;return this}});var Md,ge={getContext:function(){void 0===Md&&(Md=new (window.AudioContext||
17263 window.webkitAudioContext));return Md},setContext:function(a){Md=a}};Object.assign(ee.prototype,{load:function(a,b,c,d){var e=new Ja(this.manager);e.setResponseType("arraybuffer");e.load(a,function(a){ge.getContext().decodeAudioData(a,function(a){b(a)})},c,d)}});Object.assign(Ue.prototype,{update:function(){var a,b,c,d,e,f,g,h,k=new K,l=new K;return function(m){if(a!==this||b!==m.focus||c!==m.fov||d!==m.aspect*this.aspect||e!==m.near||f!==m.far||g!==m.zoom||h!==this.eyeSep){a=this;b=m.focus;c=m.fov;
17264 d=m.aspect*this.aspect;e=m.near;f=m.far;g=m.zoom;var n=m.projectionMatrix.clone();h=this.eyeSep/2;var q=h*e/b,p=e*Math.tan(R.DEG2RAD*c*.5)/g;l.elements[12]=-h;k.elements[12]=h;var u=-p*d+q;var v=p*d+q;n.elements[0]=2*e/(v-u);n.elements[8]=(v+u)/(v-u);this.cameraL.projectionMatrix.copy(n);u=-p*d-q;v=p*d-q;n.elements[0]=2*e/(v-u);n.elements[8]=(v+u)/(v-u);this.cameraR.projectionMatrix.copy(n)}this.cameraL.matrixWorld.copy(m.matrixWorld).multiply(l);this.cameraR.matrixWorld.copy(m.matrixWorld).multiply(k)}}()});
17265 $c.prototype=Object.create(A.prototype);$c.prototype.constructor=$c;fe.prototype=Object.assign(Object.create(A.prototype),{constructor:fe,getInput:function(){return this.gain},removeFilter:function(){null!==this.filter&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null)},getFilter:function(){return this.filter},setFilter:function(a){null!==this.filter?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):
17266 this.gain.disconnect(this.context.destination);this.filter=a;this.gain.connect(this.filter);this.filter.connect(this.context.destination)},getMasterVolume:function(){return this.gain.gain.value},setMasterVolume:function(a){this.gain.gain.value=a},updateMatrixWorld:function(){var a=new p,b=new Z,c=new p,d=new p;return function(e){A.prototype.updateMatrixWorld.call(this,e);e=this.context.listener;var f=this.up;this.matrixWorld.decompose(a,b,c);d.set(0,0,-1).applyQuaternion(b);e.positionX?(e.positionX.setValueAtTime(a.x,
17267 this.context.currentTime),e.positionY.setValueAtTime(a.y,this.context.currentTime),e.positionZ.setValueAtTime(a.z,this.context.currentTime),e.forwardX.setValueAtTime(d.x,this.context.currentTime),e.forwardY.setValueAtTime(d.y,this.context.currentTime),e.forwardZ.setValueAtTime(d.z,this.context.currentTime),e.upX.setValueAtTime(f.x,this.context.currentTime),e.upY.setValueAtTime(f.y,this.context.currentTime),e.upZ.setValueAtTime(f.z,this.context.currentTime)):(e.setPosition(a.x,a.y,a.z),e.setOrientation(d.x,
17268 d.y,d.z,f.x,f.y,f.z))}}()});lc.prototype=Object.assign(Object.create(A.prototype),{constructor:lc,getOutput:function(){return this.gain},setNodeSource:function(a){this.hasPlaybackControl=!1;this.sourceType="audioNode";this.source=a;this.connect();return this},setBuffer:function(a){this.buffer=a;this.sourceType="buffer";this.autoplay&&this.play();return this},play:function(){if(!0===this.isPlaying)console.warn("THREE.Audio: Audio is already playing.");else if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");
17269 else{var a=this.context.createBufferSource();a.buffer=this.buffer;a.loop=this.loop;a.onended=this.onEnded.bind(this);a.playbackRate.setValueAtTime(this.playbackRate,this.startTime);this.startTime=this.context.currentTime;a.start(this.startTime,this.offset);this.isPlaying=!0;this.source=a;return this.connect()}},pause:function(){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");else return!0===this.isPlaying&&(this.source.stop(),this.offset+=(this.context.currentTime-
17270 this.startTime)*this.playbackRate,this.isPlaying=!1),this},stop:function(){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");else return this.source.stop(),this.offset=0,this.isPlaying=!1,this},connect:function(){if(0<this.filters.length){this.source.connect(this.filters[0]);for(var a=1,b=this.filters.length;a<b;a++)this.filters[a-1].connect(this.filters[a]);this.filters[this.filters.length-1].connect(this.getOutput())}else this.source.connect(this.getOutput());
17271 return this},disconnect:function(){if(0<this.filters.length){this.source.disconnect(this.filters[0]);for(var a=1,b=this.filters.length;a<b;a++)this.filters[a-1].disconnect(this.filters[a]);this.filters[this.filters.length-1].disconnect(this.getOutput())}else this.source.disconnect(this.getOutput());return this},getFilters:function(){return this.filters},setFilters:function(a){a||(a=[]);!0===this.isPlaying?(this.disconnect(),this.filters=a,this.connect()):this.filters=a;return this},getFilter:function(){return this.getFilters()[0]},
17272 setFilter:function(a){return this.setFilters(a?[a]:[])},setPlaybackRate:function(a){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");else return this.playbackRate=a,!0===this.isPlaying&&this.source.playbackRate.setValueAtTime(this.playbackRate,this.context.currentTime),this},getPlaybackRate:function(){return this.playbackRate},onEnded:function(){this.isPlaying=!1},getLoop:function(){return!1===this.hasPlaybackControl?(console.warn("THREE.Audio: this Audio has no playback control."),
17273 !1):this.loop},setLoop:function(a){if(!1===this.hasPlaybackControl)console.warn("THREE.Audio: this Audio has no playback control.");else return this.loop=a,!0===this.isPlaying&&(this.source.loop=this.loop),this},getVolume:function(){return this.gain.gain.value},setVolume:function(a){this.gain.gain.value=a;return this}});he.prototype=Object.assign(Object.create(lc.prototype),{constructor:he,getOutput:function(){return this.panner},getRefDistance:function(){return this.panner.refDistance},setRefDistance:function(a){this.panner.refDistance=
17274 a},getRolloffFactor:function(){return this.panner.rolloffFactor},setRolloffFactor:function(a){this.panner.rolloffFactor=a},getDistanceModel:function(){return this.panner.distanceModel},setDistanceModel:function(a){this.panner.distanceModel=a},getMaxDistance:function(){return this.panner.maxDistance},setMaxDistance:function(a){this.panner.maxDistance=a},updateMatrixWorld:function(){var a=new p;return function(b){A.prototype.updateMatrixWorld.call(this,b);a.setFromMatrixPosition(this.matrixWorld);this.panner.setPosition(a.x,
17275 a.y,a.z)}}()});Object.assign(ie.prototype,{getFrequencyData:function(){this.analyser.getByteFrequencyData(this.data);return this.data},getAverageFrequency:function(){for(var a=0,b=this.getFrequencyData(),c=0;c<b.length;c++)a+=b[c];return a/b.length}});Object.assign(je.prototype,{accumulate:function(a,b){var c=this.buffer,d=this.valueSize;a=a*d+d;var e=this.cumulativeWeight;if(0===e){for(e=0;e!==d;++e)c[a+e]=c[e];e=b}else e+=b,this._mixBufferRegion(c,a,0,b/e,d);this.cumulativeWeight=e},apply:function(a){var b=
17276 this.valueSize,c=this.buffer;a=a*b+b;var d=this.cumulativeWeight,e=this.binding;this.cumulativeWeight=0;1>d&&this._mixBufferRegion(c,a,3*b,1-d,b);for(var d=b,f=b+b;d!==f;++d)if(c[d]!==c[d+b]){e.setValue(c,a);break}},saveOriginalState:function(){var a=this.buffer,b=this.valueSize,c=3*b;this.binding.getValue(a,c);for(var d=b;d!==c;++d)a[d]=a[c+d%b];this.cumulativeWeight=0},restoreOriginalState:function(){this.binding.setValue(this.buffer,3*this.valueSize)},_select:function(a,b,c,d,e){if(.5<=d)for(d=
17277 0;d!==e;++d)a[b+d]=a[c+d]},_slerp:function(a,b,c,d){Z.slerpFlat(a,b,a,b,a,c,d)},_lerp:function(a,b,c,d,e){for(var f=1-d,g=0;g!==e;++g){var h=b+g;a[h]=a[h]*f+a[c+g]*d}}});Object.assign(Ve.prototype,{getValue:function(a,b){this.bind();var c=this._bindings[this._targetGroup.nCachedObjects_];void 0!==c&&c.getValue(a,b)},setValue:function(a,b){for(var c=this._bindings,d=this._targetGroup.nCachedObjects_,e=c.length;d!==e;++d)c[d].setValue(a,b)},bind:function(){for(var a=this._bindings,b=this._targetGroup.nCachedObjects_,
17278 c=a.length;b!==c;++b)a[b].bind()},unbind:function(){for(var a=this._bindings,b=this._targetGroup.nCachedObjects_,c=a.length;b!==c;++b)a[b].unbind()}});Object.assign(na,{Composite:Ve,create:function(a,b,c){return a&&a.isAnimationObjectGroup?new na.Composite(a,b,c):new na(a,b,c)},sanitizeNodeName:function(a){return a.replace(/\s/g,"_").replace(/[^\w-]/g,"")},parseTrackName:function(){var a=new RegExp("^"+/((?:[\w-]+[\/:])*)/.source+/([\w-\.]+)?/.source+/(?:\.([\w-]+)(?:\[(.+)\])?)?/.source+/\.([\w-]+)(?:\[(.+)\])?/.source+
17279 "$"),b=["material","materials","bones"];return function(c){var d=a.exec(c);if(!d)throw Error("PropertyBinding: Cannot parse trackName: "+c);var d={nodeName:d[2],objectName:d[3],objectIndex:d[4],propertyName:d[5],propertyIndex:d[6]},e=d.nodeName&&d.nodeName.lastIndexOf(".");if(void 0!==e&&-1!==e){var f=d.nodeName.substring(e+1);-1!==b.indexOf(f)&&(d.nodeName=d.nodeName.substring(0,e),d.objectName=f)}if(null===d.propertyName||0===d.propertyName.length)throw Error("PropertyBinding: can not parse propertyName from trackName: "+
17280 c);return d}}(),findNode:function(a,b){if(!b||""===b||"root"===b||"."===b||-1===b||b===a.name||b===a.uuid)return a;if(a.skeleton){var c=function(a){for(var c=0;c<a.bones.length;c++){var d=a.bones[c];if(d.name===b)return d}return null}(a.skeleton);if(c)return c}if(a.children){var d=function(a){for(var c=0;c<a.length;c++){var e=a[c];if(e.name===b||e.uuid===b||(e=d(e.children)))return e}return null};if(a=d(a.children))return a}return null}});Object.assign(na.prototype,{_getValue_unavailable:function(){},
17281 _setValue_unavailable:function(){},BindingType:{Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},Versioning:{None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},GetterByBindingType:[function(a,b){a[b]=this.node[this.propertyName]},function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)a[b++]=c[d]},function(a,b){a[b]=this.resolvedProperty[this.propertyIndex]},function(a,b){this.resolvedProperty.toArray(a,b)}],SetterByBindingTypeAndVersioning:[[function(a,b){this.targetObject[this.propertyName]=
17282 a[b]},function(a,b){this.targetObject[this.propertyName]=a[b];this.targetObject.needsUpdate=!0},function(a,b){this.targetObject[this.propertyName]=a[b];this.targetObject.matrixWorldNeedsUpdate=!0}],[function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)c[d]=a[b++]},function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)c[d]=a[b++];this.targetObject.needsUpdate=!0},function(a,b){for(var c=this.resolvedProperty,d=0,e=c.length;d!==e;++d)c[d]=a[b++];this.targetObject.matrixWorldNeedsUpdate=
17283 !0}],[function(a,b){this.resolvedProperty[this.propertyIndex]=a[b]},function(a,b){this.resolvedProperty[this.propertyIndex]=a[b];this.targetObject.needsUpdate=!0},function(a,b){this.resolvedProperty[this.propertyIndex]=a[b];this.targetObject.matrixWorldNeedsUpdate=!0}],[function(a,b){this.resolvedProperty.fromArray(a,b)},function(a,b){this.resolvedProperty.fromArray(a,b);this.targetObject.needsUpdate=!0},function(a,b){this.resolvedProperty.fromArray(a,b);this.targetObject.matrixWorldNeedsUpdate=!0}]],
17284 getValue:function(a,b){this.bind();this.getValue(a,b)},setValue:function(a,b){this.bind();this.setValue(a,b)},bind:function(){var a=this.node,b=this.parsedPath,c=b.objectName,d=b.propertyName,e=b.propertyIndex;a||(this.node=a=na.findNode(this.rootNode,b.nodeName)||this.rootNode);this.getValue=this._getValue_unavailable;this.setValue=this._setValue_unavailable;if(a){if(c){var f=b.objectIndex;switch(c){case "materials":if(!a.material){console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.",
17285 this);return}if(!a.material.materials){console.error("THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.",this);return}a=a.material.materials;break;case "bones":if(!a.skeleton){console.error("THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.",this);return}a=a.skeleton.bones;for(c=0;c<a.length;c++)if(a[c].name===f){f=c;break}break;default:if(void 0===a[c]){console.error("THREE.PropertyBinding: Can not bind to objectName of node undefined.",
17286 this);return}a=a[c]}if(void 0!==f){if(void 0===a[f]){console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.",this,a);return}a=a[f]}}f=a[d];if(void 0===f)console.error("THREE.PropertyBinding: Trying to update property for track: "+b.nodeName+"."+d+" but it wasn't found.",a);else{b=this.Versioning.None;void 0!==a.needsUpdate?(b=this.Versioning.NeedsUpdate,this.targetObject=a):void 0!==a.matrixWorldNeedsUpdate&&(b=this.Versioning.MatrixWorldNeedsUpdate,this.targetObject=
17287 a);c=this.BindingType.Direct;if(void 0!==e){if("morphTargetInfluences"===d){if(!a.geometry){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.",this);return}if(a.geometry.isBufferGeometry){if(!a.geometry.morphAttributes){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.",this);return}for(c=0;c<this.node.geometry.morphAttributes.position.length;c++)if(a.geometry.morphAttributes.position[c].name===
17288 e){e=c;break}}else{if(!a.geometry.morphTargets){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.",this);return}for(c=0;c<this.node.geometry.morphTargets.length;c++)if(a.geometry.morphTargets[c].name===e){e=c;break}}}c=this.BindingType.ArrayElement;this.resolvedProperty=f;this.propertyIndex=e}else void 0!==f.fromArray&&void 0!==f.toArray?(c=this.BindingType.HasFromToArray,this.resolvedProperty=f):Array.isArray(f)?(c=this.BindingType.EntireArray,
17289 this.resolvedProperty=f):this.propertyName=d;this.getValue=this.GetterByBindingType[c];this.setValue=this.SetterByBindingTypeAndVersioning[c][b]}}else console.error("THREE.PropertyBinding: Trying to update node for track: "+this.path+" but it wasn't found.")},unbind:function(){this.node=null;this.getValue=this._getValue_unbound;this.setValue=this._setValue_unbound}});Object.assign(na.prototype,{_getValue_unbound:na.prototype.getValue,_setValue_unbound:na.prototype.setValue});Object.assign(We.prototype,
17290 {isAnimationObjectGroup:!0,add:function(){for(var a=this._objects,b=a.length,c=this.nCachedObjects_,d=this._indicesByUUID,e=this._paths,f=this._parsedPaths,g=this._bindings,h=g.length,k=0,l=arguments.length;k!==l;++k){var m=arguments[k],n=m.uuid,p=d[n];if(void 0===p){p=b++;d[n]=p;a.push(m);for(var n=0,r=h;n!==r;++n)g[n].push(new na(m,e[n],f[n]))}else if(p<c){var u=--c,r=a[u];d[r.uuid]=p;a[p]=r;d[n]=u;a[u]=m;n=0;for(r=h;n!==r;++n){var v=g[n],w=v[p];v[p]=v[u];void 0===w&&(w=new na(m,e[n],f[n]));v[u]=
17291 w}}else void 0!==a[p]&&console.error("THREE.AnimationObjectGroup: Different objects with the same UUID detected. Clean the caches or recreate your infrastructure when reloading scenes.")}this.nCachedObjects_=c},remove:function(){for(var a=this._objects,b=this.nCachedObjects_,c=this._indicesByUUID,d=this._bindings,e=d.length,f=0,g=arguments.length;f!==g;++f){var h=arguments[f],k=h.uuid,l=c[k];if(void 0!==l&&l>=b){var m=b++,n=a[m];c[n.uuid]=l;a[l]=n;c[k]=m;a[m]=h;h=0;for(k=e;h!==k;++h){var n=d[h],p=
17292 n[l];n[l]=n[m];n[m]=p}}}this.nCachedObjects_=b},uncache:function(){for(var a,b,c=this._objects,d=c.length,e=this.nCachedObjects_,f=this._indicesByUUID,g=this._bindings,h=g.length,k=0,l=arguments.length;k!==l;++k){b=arguments[k].uuid;var m=f[b];if(void 0!==m)if(delete f[b],m<e){var n=--e,p=c[n];b=--d;a=c[b];f[p.uuid]=m;c[m]=p;f[a.uuid]=n;c[n]=a;c.pop();for(var p=0,r=h;p!==r;++p){a=g[p];var u=a[b];a[m]=a[n];a[n]=u;a.pop()}}else for(b=--d,a=c[b],f[a.uuid]=m,c[m]=a,c.pop(),p=0,r=h;p!==r;++p)a=g[p],a[m]=
17293 a[b],a.pop()}this.nCachedObjects_=e},subscribe_:function(a,b){var c=this._bindingsIndicesByPath,d=c[a],e=this._bindings;if(void 0!==d)return e[d];var f=this._paths,g=this._parsedPaths,h=this._objects,k=this.nCachedObjects_,l=Array(h.length),d=e.length;c[a]=d;f.push(a);g.push(b);e.push(l);c=k;for(d=h.length;c!==d;++c)l[c]=new na(h[c],a,b);return l},unsubscribe_:function(a){var b=this._bindingsIndicesByPath,c=b[a];if(void 0!==c){var d=this._paths,e=this._parsedPaths,f=this._bindings,g=f.length-1,h=
17294 f[g];b[a[g]]=c;f[c]=h;f.pop();e[c]=e[g];e.pop();d[c]=d[g];d.pop()}}});Object.assign(Xe.prototype,{play:function(){this._mixer._activateAction(this);return this},stop:function(){this._mixer._deactivateAction(this);return this.reset()},reset:function(){this.paused=!1;this.enabled=!0;this.time=0;this._loopCount=-1;this._startTime=null;return this.stopFading().stopWarping()},isRunning:function(){return this.enabled&&!this.paused&&0!==this.timeScale&&null===this._startTime&&this._mixer._isActiveAction(this)},
17295 isScheduled:function(){return this._mixer._isActiveAction(this)},startAt:function(a){this._startTime=a;return this},setLoop:function(a,b){this.loop=a;this.repetitions=b;return this},setEffectiveWeight:function(a){this.weight=a;this._effectiveWeight=this.enabled?a:0;return this.stopFading()},getEffectiveWeight:function(){return this._effectiveWeight},fadeIn:function(a){return this._scheduleFading(a,0,1)},fadeOut:function(a){return this._scheduleFading(a,1,0)},crossFadeFrom:function(a,b,c){a.fadeOut(b);
17296 this.fadeIn(b);if(c){c=this._clip.duration;var d=a._clip.duration,e=c/d;a.warp(1,d/c,b);this.warp(e,1,b)}return this},crossFadeTo:function(a,b,c){return a.crossFadeFrom(this,b,c)},stopFading:function(){var a=this._weightInterpolant;null!==a&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(a));return this},setEffectiveTimeScale:function(a){this.timeScale=a;this._effectiveTimeScale=this.paused?0:a;return this.stopWarping()},getEffectiveTimeScale:function(){return this._effectiveTimeScale},
17297 setDuration:function(a){this.timeScale=this._clip.duration/a;return this.stopWarping()},syncWith:function(a){this.time=a.time;this.timeScale=a.timeScale;return this.stopWarping()},halt:function(a){return this.warp(this._effectiveTimeScale,0,a)},warp:function(a,b,c){var d=this._mixer,e=d.time,f=this._timeScaleInterpolant,g=this.timeScale;null===f&&(this._timeScaleInterpolant=f=d._lendControlInterpolant());d=f.parameterPositions;f=f.sampleValues;d[0]=e;d[1]=e+c;f[0]=a/g;f[1]=b/g;return this},stopWarping:function(){var a=
17298 this._timeScaleInterpolant;null!==a&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(a));return this},getMixer:function(){return this._mixer},getClip:function(){return this._clip},getRoot:function(){return this._localRoot||this._mixer._root},_update:function(a,b,c,d){if(this.enabled){var e=this._startTime;if(null!==e){b=(a-e)*c;if(0>b||0===c)return;this._startTime=null;b*=c}b*=this._updateTimeScale(a);c=this._updateTime(b);a=this._updateWeight(a);if(0<a){b=this._interpolants;
17299 for(var e=this._propertyBindings,f=0,g=b.length;f!==g;++f)b[f].evaluate(c),e[f].accumulate(d,a)}}else this._updateWeight(a)},_updateWeight:function(a){var b=0;if(this.enabled){var b=this.weight,c=this._weightInterpolant;if(null!==c){var d=c.evaluate(a)[0],b=b*d;a>c.parameterPositions[1]&&(this.stopFading(),0===d&&(this.enabled=!1))}}return this._effectiveWeight=b},_updateTimeScale:function(a){var b=0;if(!this.paused){var b=this.timeScale,c=this._timeScaleInterpolant;if(null!==c){var d=c.evaluate(a)[0],
17300 b=b*d;a>c.parameterPositions[1]&&(this.stopWarping(),0===b?this.paused=!0:this.timeScale=b)}}return this._effectiveTimeScale=b},_updateTime:function(a){var b=this.time+a;if(0===a)return b;var c=this._clip.duration,d=this.loop,e=this._loopCount;if(2200===d)a:{if(-1===e&&(this._loopCount=0,this._setEndings(!0,!0,!1)),b>=c)b=c;else if(0>b)b=0;else break a;this.clampWhenFinished?this.paused=!0:this.enabled=!1;this._mixer.dispatchEvent({type:"finished",action:this,direction:0>a?-1:1})}else{d=2202===d;
17301 -1===e&&(0<=a?(e=0,this._setEndings(!0,0===this.repetitions,d)):this._setEndings(0===this.repetitions,!0,d));if(b>=c||0>b){var f=Math.floor(b/c),b=b-c*f,e=e+Math.abs(f),g=this.repetitions-e;0>g?(this.clampWhenFinished?this.paused=!0:this.enabled=!1,b=0<a?c:0,this._mixer.dispatchEvent({type:"finished",action:this,direction:0<a?1:-1})):(0===g?(a=0>a,this._setEndings(a,!a,d)):this._setEndings(!1,!1,d),this._loopCount=e,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:f}))}if(d&&1===(e&1))return this.time=
17302 b,c-b}return this.time=b},_setEndings:function(a,b,c){var d=this._interpolantSettings;c?(d.endingStart=2401,d.endingEnd=2401):(d.endingStart=a?this.zeroSlopeAtStart?2401:2400:2402,d.endingEnd=b?this.zeroSlopeAtEnd?2401:2400:2402)},_scheduleFading:function(a,b,c){var d=this._mixer,e=d.time,f=this._weightInterpolant;null===f&&(this._weightInterpolant=f=d._lendControlInterpolant());d=f.parameterPositions;f=f.sampleValues;d[0]=e;f[0]=b;d[1]=e+a;f[1]=c;return this}});Object.assign(Ye.prototype,ja.prototype,
17303 {_bindAction:function(a,b){var c=a._localRoot||this._root,d=a._clip.tracks,e=d.length,f=a._propertyBindings;a=a._interpolants;var g=c.uuid,h=this._bindingsByRootAndName,k=h[g];void 0===k&&(k={},h[g]=k);for(h=0;h!==e;++h){var l=d[h],m=l.name,n=k[m];if(void 0===n){n=f[h];if(void 0!==n){null===n._cacheIndex&&(++n.referenceCount,this._addInactiveBinding(n,g,m));continue}n=new je(na.create(c,m,b&&b._propertyBindings[h].binding.parsedPath),l.ValueTypeName,l.getValueSize());++n.referenceCount;this._addInactiveBinding(n,
17304 g,m)}f[h]=n;a[h].resultBuffer=n.buffer}},_activateAction:function(a){if(!this._isActiveAction(a)){if(null===a._cacheIndex){var b=(a._localRoot||this._root).uuid,c=a._clip.uuid,d=this._actionsByClip[c];this._bindAction(a,d&&d.knownActions[0]);this._addInactiveAction(a,c,b)}b=a._propertyBindings;c=0;for(d=b.length;c!==d;++c){var e=b[c];0===e.useCount++&&(this._lendBinding(e),e.saveOriginalState())}this._lendAction(a)}},_deactivateAction:function(a){if(this._isActiveAction(a)){for(var b=a._propertyBindings,
17305 c=0,d=b.length;c!==d;++c){var e=b[c];0===--e.useCount&&(e.restoreOriginalState(),this._takeBackBinding(e))}this._takeBackAction(a)}},_initMemoryManager:function(){this._actions=[];this._nActiveActions=0;this._actionsByClip={};this._bindings=[];this._nActiveBindings=0;this._bindingsByRootAndName={};this._controlInterpolants=[];this._nActiveControlInterpolants=0;var a=this;this.stats={actions:{get total(){return a._actions.length},get inUse(){return a._nActiveActions}},bindings:{get total(){return a._bindings.length},
17306 get inUse(){return a._nActiveBindings}},controlInterpolants:{get total(){return a._controlInterpolants.length},get inUse(){return a._nActiveControlInterpolants}}}},_isActiveAction:function(a){a=a._cacheIndex;return null!==a&&a<this._nActiveActions},_addInactiveAction:function(a,b,c){var d=this._actions,e=this._actionsByClip,f=e[b];void 0===f?(f={knownActions:[a],actionByRoot:{}},a._byClipCacheIndex=0,e[b]=f):(b=f.knownActions,a._byClipCacheIndex=b.length,b.push(a));a._cacheIndex=d.length;d.push(a);
17307 f.actionByRoot[c]=a},_removeInactiveAction:function(a){var b=this._actions,c=b[b.length-1],d=a._cacheIndex;c._cacheIndex=d;b[d]=c;b.pop();a._cacheIndex=null;var b=a._clip.uuid,c=this._actionsByClip,d=c[b],e=d.knownActions,f=e[e.length-1],g=a._byClipCacheIndex;f._byClipCacheIndex=g;e[g]=f;e.pop();a._byClipCacheIndex=null;delete d.actionByRoot[(a._localRoot||this._root).uuid];0===e.length&&delete c[b];this._removeInactiveBindingsForAction(a)},_removeInactiveBindingsForAction:function(a){a=a._propertyBindings;
17308 for(var b=0,c=a.length;b!==c;++b){var d=a[b];0===--d.referenceCount&&this._removeInactiveBinding(d)}},_lendAction:function(a){var b=this._actions,c=a._cacheIndex,d=this._nActiveActions++,e=b[d];a._cacheIndex=d;b[d]=a;e._cacheIndex=c;b[c]=e},_takeBackAction:function(a){var b=this._actions,c=a._cacheIndex,d=--this._nActiveActions,e=b[d];a._cacheIndex=d;b[d]=a;e._cacheIndex=c;b[c]=e},_addInactiveBinding:function(a,b,c){var d=this._bindingsByRootAndName,e=d[b],f=this._bindings;void 0===e&&(e={},d[b]=
17309 e);e[c]=a;a._cacheIndex=f.length;f.push(a)},_removeInactiveBinding:function(a){var b=this._bindings,c=a.binding,d=c.rootNode.uuid,c=c.path,e=this._bindingsByRootAndName,f=e[d],g=b[b.length-1];a=a._cacheIndex;g._cacheIndex=a;b[a]=g;b.pop();delete f[c];a:{for(var h in f)break a;delete e[d]}},_lendBinding:function(a){var b=this._bindings,c=a._cacheIndex,d=this._nActiveBindings++,e=b[d];a._cacheIndex=d;b[d]=a;e._cacheIndex=c;b[c]=e},_takeBackBinding:function(a){var b=this._bindings,c=a._cacheIndex,d=
17310 --this._nActiveBindings,e=b[d];a._cacheIndex=d;b[d]=a;e._cacheIndex=c;b[c]=e},_lendControlInterpolant:function(){var a=this._controlInterpolants,b=this._nActiveControlInterpolants++,c=a[b];void 0===c&&(c=new Yc(new Float32Array(2),new Float32Array(2),1,this._controlInterpolantsResultBuffer),c.__cacheIndex=b,a[b]=c);return c},_takeBackControlInterpolant:function(a){var b=this._controlInterpolants,c=a.__cacheIndex,d=--this._nActiveControlInterpolants,e=b[d];a.__cacheIndex=d;b[d]=a;e.__cacheIndex=c;
17311 b[c]=e},_controlInterpolantsResultBuffer:new Float32Array(1),clipAction:function(a,b){var c=b||this._root,d=c.uuid,c="string"===typeof a?ka.findByName(c,a):a;a=null!==c?c.uuid:a;var e=this._actionsByClip[a],f=null;if(void 0!==e){f=e.actionByRoot[d];if(void 0!==f)return f;f=e.knownActions[0];null===c&&(c=f._clip)}if(null===c)return null;b=new Xe(this,c,b);this._bindAction(b,f);this._addInactiveAction(b,a,d);return b},existingAction:function(a,b){var c=b||this._root;b=c.uuid;c="string"===typeof a?ka.findByName(c,
17312 a):a;a=this._actionsByClip[c?c.uuid:a];return void 0!==a?a.actionByRoot[b]||null:null},stopAllAction:function(){for(var a=this._actions,b=this._nActiveActions,c=this._bindings,d=this._nActiveBindings,e=this._nActiveBindings=this._nActiveActions=0;e!==b;++e)a[e].reset();for(e=0;e!==d;++e)c[e].useCount=0;return this},update:function(a){a*=this.timeScale;for(var b=this._actions,c=this._nActiveActions,d=this.time+=a,e=Math.sign(a),f=this._accuIndex^=1,g=0;g!==c;++g)b[g]._update(d,a,e,f);a=this._bindings;
17313 b=this._nActiveBindings;for(g=0;g!==b;++g)a[g].apply(f);return this},getRoot:function(){return this._root},uncacheClip:function(a){var b=this._actions;a=a.uuid;var c=this._actionsByClip,d=c[a];if(void 0!==d){for(var d=d.knownActions,e=0,f=d.length;e!==f;++e){var g=d[e];this._deactivateAction(g);var h=g._cacheIndex,k=b[b.length-1];g._cacheIndex=null;g._byClipCacheIndex=null;k._cacheIndex=h;b[h]=k;b.pop();this._removeInactiveBindingsForAction(g)}delete c[a]}},uncacheRoot:function(a){a=a.uuid;var b=
17314 this._actionsByClip;for(d in b){var c=b[d].actionByRoot[a];void 0!==c&&(this._deactivateAction(c),this._removeInactiveAction(c))}var d=this._bindingsByRootAndName[a];if(void 0!==d)for(var e in d)a=d[e],a.restoreOriginalState(),this._removeInactiveBinding(a)},uncacheAction:function(a,b){a=this.existingAction(a,b);null!==a&&(this._deactivateAction(a),this._removeInactiveAction(a))}});Jd.prototype.clone=function(){return new Jd(void 0===this.value.clone?this.value:this.value.clone())};ke.prototype=Object.assign(Object.create(D.prototype),
17315 {constructor:ke,isInstancedBufferGeometry:!0,copy:function(a){D.prototype.copy.call(this,a);this.maxInstancedCount=a.maxInstancedCount;return this},clone:function(){return(new this.constructor).copy(this)}});Object.defineProperties(le.prototype,{count:{get:function(){return this.data.count}},array:{get:function(){return this.data.array}}});Object.assign(le.prototype,{isInterleavedBufferAttribute:!0,setX:function(a,b){this.data.array[a*this.data.stride+this.offset]=b;return this},setY:function(a,b){this.data.array[a*
17316 this.data.stride+this.offset+1]=b;return this},setZ:function(a,b){this.data.array[a*this.data.stride+this.offset+2]=b;return this},setW:function(a,b){this.data.array[a*this.data.stride+this.offset+3]=b;return this},getX:function(a){return this.data.array[a*this.data.stride+this.offset]},getY:function(a){return this.data.array[a*this.data.stride+this.offset+1]},getZ:function(a){return this.data.array[a*this.data.stride+this.offset+2]},getW:function(a){return this.data.array[a*this.data.stride+this.offset+
17317 3]},setXY:function(a,b,c){a=a*this.data.stride+this.offset;this.data.array[a+0]=b;this.data.array[a+1]=c;return this},setXYZ:function(a,b,c,d){a=a*this.data.stride+this.offset;this.data.array[a+0]=b;this.data.array[a+1]=c;this.data.array[a+2]=d;return this},setXYZW:function(a,b,c,d,e){a=a*this.data.stride+this.offset;this.data.array[a+0]=b;this.data.array[a+1]=c;this.data.array[a+2]=d;this.data.array[a+3]=e;return this}});Object.defineProperty(mc.prototype,"needsUpdate",{set:function(a){!0===a&&this.version++}});
17318 Object.assign(mc.prototype,{isInterleavedBuffer:!0,setArray:function(a){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.count=void 0!==a?a.length/this.stride:0;this.array=a},setDynamic:function(a){this.dynamic=a;return this},copy:function(a){this.array=new a.array.constructor(a.array);this.count=a.count;this.stride=a.stride;this.dynamic=a.dynamic;return this},copyAt:function(a,b,c){a*=this.stride;c*=b.stride;for(var d=0,e=this.stride;d<e;d++)this.array[a+
17319 d]=b.array[c+d];return this},set:function(a,b){void 0===b&&(b=0);this.array.set(a,b);return this},clone:function(){return(new this.constructor).copy(this)},onUpload:function(a){this.onUploadCallback=a;return this}});me.prototype=Object.assign(Object.create(mc.prototype),{constructor:me,isInstancedInterleavedBuffer:!0,copy:function(a){mc.prototype.copy.call(this,a);this.meshPerAttribute=a.meshPerAttribute;return this}});ne.prototype=Object.assign(Object.create(P.prototype),{constructor:ne,isInstancedBufferAttribute:!0,
17320 copy:function(a){P.prototype.copy.call(this,a);this.meshPerAttribute=a.meshPerAttribute;return this}});Object.assign(Ze.prototype,{linePrecision:1,set:function(a,b){this.ray.set(a,b)},setFromCamera:function(a,b){b&&b.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(b.matrixWorld),this.ray.direction.set(a.x,a.y,.5).unproject(b).sub(this.ray.origin).normalize()):b&&b.isOrthographicCamera?(this.ray.origin.set(a.x,a.y,(b.near+b.far)/(b.near-b.far)).unproject(b),this.ray.direction.set(0,0,-1).transformDirection(b.matrixWorld)):
17321 console.error("THREE.Raycaster: Unsupported camera type.")},intersectObject:function(a,b){var c=[];oe(a,this,c,b);c.sort($e);return c},intersectObjects:function(a,b){var c=[];if(!1===Array.isArray(a))return console.warn("THREE.Raycaster.intersectObjects: objects is not an Array."),c;for(var d=0,e=a.length;d<e;d++)oe(a[d],this,c,b);c.sort($e);return c}});Object.assign(af.prototype,{start:function(){this.oldTime=this.startTime=("undefined"===typeof performance?Date:performance).now();this.elapsedTime=
17322 0;this.running=!0},stop:function(){this.getElapsedTime();this.autoStart=this.running=!1},getElapsedTime:function(){this.getDelta();return this.elapsedTime},getDelta:function(){var a=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){var b=("undefined"===typeof performance?Date:performance).now(),a=(b-this.oldTime)/1E3;this.oldTime=b;this.elapsedTime+=a}return a}});Object.assign(bf.prototype,{set:function(a,b,c){this.radius=a;this.phi=b;this.theta=c;return this},clone:function(){return(new this.constructor).copy(this)},
17323 copy:function(a){this.radius=a.radius;this.phi=a.phi;this.theta=a.theta;return this},makeSafe:function(){this.phi=Math.max(1E-6,Math.min(Math.PI-1E-6,this.phi));return this},setFromVector3:function(a){this.radius=a.length();0===this.radius?this.phi=this.theta=0:(this.theta=Math.atan2(a.x,a.z),this.phi=Math.acos(R.clamp(a.y/this.radius,-1,1)));return this}});Object.assign(cf.prototype,{set:function(a,b,c){this.radius=a;this.theta=b;this.y=c;return this},clone:function(){return(new this.constructor).copy(this)},
17324 copy:function(a){this.radius=a.radius;this.theta=a.theta;this.y=a.y;return this},setFromVector3:function(a){this.radius=Math.sqrt(a.x*a.x+a.z*a.z);this.theta=Math.atan2(a.x,a.z);this.y=a.y;return this}});ad.prototype=Object.create(A.prototype);ad.prototype.constructor=ad;ad.prototype.isImmediateRenderObject=!0;bd.prototype=Object.create(ca.prototype);bd.prototype.constructor=bd;bd.prototype.update=function(){var a=new p,b=new p,c=new ra;return function(){var d,e=["a","b","c"];this.object.updateMatrixWorld(!0);
17325 c.getNormalMatrix(this.object.matrixWorld);var f=this.object.matrixWorld,g=this.geometry.attributes.position;if((d=this.object.geometry)&&d.isGeometry)for(var h=d.vertices,k=d.faces,l=d=0,m=k.length;l<m;l++)for(var n=k[l],p=0,r=n.vertexNormals.length;p<r;p++){var u=n.vertexNormals[p];a.copy(h[n[e[p]]]).applyMatrix4(f);b.copy(u).applyMatrix3(c).normalize().multiplyScalar(this.size).add(a);g.setXYZ(d,a.x,a.y,a.z);d+=1;g.setXYZ(d,b.x,b.y,b.z);d+=1}else if(d&&d.isBufferGeometry)for(e=d.attributes.position,
17326 h=d.attributes.normal,p=d=0,r=e.count;p<r;p++)a.set(e.getX(p),e.getY(p),e.getZ(p)).applyMatrix4(f),b.set(h.getX(p),h.getY(p),h.getZ(p)),b.applyMatrix3(c).normalize().multiplyScalar(this.size).add(a),g.setXYZ(d,a.x,a.y,a.z),d+=1,g.setXYZ(d,b.x,b.y,b.z),d+=1;g.needsUpdate=!0}}();nc.prototype=Object.create(A.prototype);nc.prototype.constructor=nc;nc.prototype.dispose=function(){this.cone.geometry.dispose();this.cone.material.dispose()};nc.prototype.update=function(){var a=new p,b=new p;return function(){this.light.updateMatrixWorld();
17327 var c=this.light.distance?this.light.distance:1E3,d=c*Math.tan(this.light.angle);this.cone.scale.set(d,d,c);a.setFromMatrixPosition(this.light.matrixWorld);b.setFromMatrixPosition(this.light.target.matrixWorld);this.cone.lookAt(b.sub(a));void 0!==this.color?this.cone.material.color.set(this.color):this.cone.material.color.copy(this.light.color)}}();oc.prototype=Object.create(ca.prototype);oc.prototype.constructor=oc;oc.prototype.updateMatrixWorld=function(){var a=new p,b=new K,c=new K;return function(d){var e=
17328 this.bones,f=this.geometry,g=f.getAttribute("position");c.getInverse(this.root.matrixWorld);for(var h=0,k=0;h<e.length;h++){var l=e[h];l.parent&&l.parent.isBone&&(b.multiplyMatrices(c,l.matrixWorld),a.setFromMatrixPosition(b),g.setXYZ(k,a.x,a.y,a.z),b.multiplyMatrices(c,l.parent.matrixWorld),a.setFromMatrixPosition(b),g.setXYZ(k+1,a.x,a.y,a.z),k+=2)}f.getAttribute("position").needsUpdate=!0;A.prototype.updateMatrixWorld.call(this,d)}}();pc.prototype=Object.create(pa.prototype);pc.prototype.constructor=
17329 pc;pc.prototype.dispose=function(){this.geometry.dispose();this.material.dispose()};pc.prototype.update=function(){void 0!==this.color?this.material.color.set(this.color):this.material.color.copy(this.light.color)};qc.prototype=Object.create(A.prototype);qc.prototype.constructor=qc;qc.prototype.dispose=function(){this.children[0].geometry.dispose();this.children[0].material.dispose()};qc.prototype.update=function(){var a=.5*this.light.width,b=.5*this.light.height,c=this.line.geometry.attributes.position,
17330 d=c.array;d[0]=a;d[1]=-b;d[2]=0;d[3]=a;d[4]=b;d[5]=0;d[6]=-a;d[7]=b;d[8]=0;d[9]=-a;d[10]=-b;d[11]=0;d[12]=a;d[13]=-b;d[14]=0;c.needsUpdate=!0;void 0!==this.color?this.line.material.color.set(this.color):this.line.material.color.copy(this.light.color)};rc.prototype=Object.create(A.prototype);rc.prototype.constructor=rc;rc.prototype.dispose=function(){this.children[0].geometry.dispose();this.children[0].material.dispose()};rc.prototype.update=function(){var a=new p,b=new H,c=new H;return function(){var d=
17331 this.children[0];if(void 0!==this.color)this.material.color.set(this.color);else{var e=d.geometry.getAttribute("color");b.copy(this.light.color);c.copy(this.light.groundColor);for(var f=0,g=e.count;f<g;f++){var h=f<g/2?b:c;e.setXYZ(f,h.r,h.g,h.b)}e.needsUpdate=!0}d.lookAt(a.setFromMatrixPosition(this.light.matrixWorld).negate())}}();cd.prototype=Object.create(ca.prototype);cd.prototype.constructor=cd;Kd.prototype=Object.create(ca.prototype);Kd.prototype.constructor=Kd;dd.prototype=Object.create(ca.prototype);
17332 dd.prototype.constructor=dd;dd.prototype.update=function(){var a=new p,b=new p,c=new ra;return function(){this.object.updateMatrixWorld(!0);c.getNormalMatrix(this.object.matrixWorld);for(var d=this.object.matrixWorld,e=this.geometry.attributes.position,f=this.object.geometry,g=f.vertices,f=f.faces,h=0,k=0,l=f.length;k<l;k++){var m=f[k],n=m.normal;a.copy(g[m.a]).add(g[m.b]).add(g[m.c]).divideScalar(3).applyMatrix4(d);b.copy(n).applyMatrix3(c).normalize().multiplyScalar(this.size).add(a);e.setXYZ(h,
17333 a.x,a.y,a.z);h+=1;e.setXYZ(h,b.x,b.y,b.z);h+=1}e.needsUpdate=!0}}();sc.prototype=Object.create(A.prototype);sc.prototype.constructor=sc;sc.prototype.dispose=function(){this.lightPlane.geometry.dispose();this.lightPlane.material.dispose();this.targetLine.geometry.dispose();this.targetLine.material.dispose()};sc.prototype.update=function(){var a=new p,b=new p,c=new p;return function(){a.setFromMatrixPosition(this.light.matrixWorld);b.setFromMatrixPosition(this.light.target.matrixWorld);c.subVectors(b,
17334 a);this.lightPlane.lookAt(c);void 0!==this.color?(this.lightPlane.material.color.set(this.color),this.targetLine.material.color.set(this.color)):(this.lightPlane.material.color.copy(this.light.color),this.targetLine.material.color.copy(this.light.color));this.targetLine.lookAt(c);this.targetLine.scale.z=c.length()}}();ed.prototype=Object.create(ca.prototype);ed.prototype.constructor=ed;ed.prototype.update=function(){function a(a,g,h,k){d.set(g,h,k).unproject(e);a=c[a];if(void 0!==a)for(g=b.getAttribute("position"),
17335 h=0,k=a.length;h<k;h++)g.setXYZ(a[h],d.x,d.y,d.z)}var b,c,d=new p,e=new La;return function(){b=this.geometry;c=this.pointMap;e.projectionMatrix.copy(this.camera.projectionMatrix);a("c",0,0,-1);a("t",0,0,1);a("n1",-1,-1,-1);a("n2",1,-1,-1);a("n3",-1,1,-1);a("n4",1,1,-1);a("f1",-1,-1,1);a("f2",1,-1,1);a("f3",-1,1,1);a("f4",1,1,1);a("u1",.7,1.1,-1);a("u2",-.7,1.1,-1);a("u3",0,2,-1);a("cf1",-1,0,1);a("cf2",1,0,1);a("cf3",0,-1,1);a("cf4",0,1,1);a("cn1",-1,0,-1);a("cn2",1,0,-1);a("cn3",0,-1,-1);a("cn4",
17336 0,1,-1);b.getAttribute("position").needsUpdate=!0}}();Db.prototype=Object.create(ca.prototype);Db.prototype.constructor=Db;Db.prototype.update=function(){var a=new Oa;return function(b){void 0!==b&&console.warn("THREE.BoxHelper: .update() has no longer arguments.");void 0!==this.object&&a.setFromObject(this.object);if(!a.isEmpty()){b=a.min;var c=a.max,d=this.geometry.attributes.position,e=d.array;e[0]=c.x;e[1]=c.y;e[2]=c.z;e[3]=b.x;e[4]=c.y;e[5]=c.z;e[6]=b.x;e[7]=b.y;e[8]=c.z;e[9]=c.x;e[10]=b.y;e[11]=
17337 c.z;e[12]=c.x;e[13]=c.y;e[14]=b.z;e[15]=b.x;e[16]=c.y;e[17]=b.z;e[18]=b.x;e[19]=b.y;e[20]=b.z;e[21]=c.x;e[22]=b.y;e[23]=b.z;d.needsUpdate=!0;this.geometry.computeBoundingSphere()}}}();Db.prototype.setFromObject=function(a){this.object=a;this.update();return this};fd.prototype=Object.create(ca.prototype);fd.prototype.constructor=fd;fd.prototype.updateMatrixWorld=function(a){var b=this.box;b.isEmpty()||(b.getCenter(this.position),b.getSize(this.scale),this.scale.multiplyScalar(.5),A.prototype.updateMatrixWorld.call(this,
17338 a))};gd.prototype=Object.create(ma.prototype);gd.prototype.constructor=gd;gd.prototype.updateMatrixWorld=function(a){var b=-this.plane.constant;1E-8>Math.abs(b)&&(b=1E-8);this.scale.set(.5*this.size,.5*this.size,b);this.lookAt(this.plane.normal);A.prototype.updateMatrixWorld.call(this,a)};var Ld,pe;Eb.prototype=Object.create(A.prototype);Eb.prototype.constructor=Eb;Eb.prototype.setDirection=function(){var a=new p,b;return function(c){.99999<c.y?this.quaternion.set(0,0,0,1):-.99999>c.y?this.quaternion.set(1,
17339 0,0,0):(a.set(c.z,0,-c.x).normalize(),b=Math.acos(c.y),this.quaternion.setFromAxisAngle(a,b))}}();Eb.prototype.setLength=function(a,b,c){void 0===b&&(b=.2*a);void 0===c&&(c=.2*b);this.line.scale.set(1,Math.max(0,a-b),1);this.line.updateMatrix();this.cone.scale.set(c,b,c);this.cone.position.y=a;this.cone.updateMatrix()};Eb.prototype.setColor=function(a){this.line.material.color.copy(a);this.cone.material.color.copy(a)};hd.prototype=Object.create(ca.prototype);hd.prototype.constructor=hd;var Nd=new p,
17340 te=new qe,ue=new qe,ve=new qe;ya.prototype=Object.create(S.prototype);ya.prototype.constructor=ya;ya.prototype.isCatmullRomCurve3=!0;ya.prototype.getPoint=function(a,b){b=b||new p;var c=this.points,d=c.length;a*=d-(this.closed?0:1);var e=Math.floor(a);a-=e;this.closed?e+=0<e?0:(Math.floor(Math.abs(e)/c.length)+1)*c.length:0===a&&e===d-1&&(e=d-2,a=1);if(this.closed||0<e)var f=c[(e-1)%d];else Nd.subVectors(c[0],c[1]).add(c[0]),f=Nd;var g=c[e%d];var h=c[(e+1)%d];this.closed||e+2<d?c=c[(e+2)%d]:(Nd.subVectors(c[d-
17341 1],c[d-2]).add(c[d-1]),c=Nd);if("centripetal"===this.curveType||"chordal"===this.curveType){var k="chordal"===this.curveType?.5:.25,d=Math.pow(f.distanceToSquared(g),k),e=Math.pow(g.distanceToSquared(h),k),k=Math.pow(h.distanceToSquared(c),k);1E-4>e&&(e=1);1E-4>d&&(d=e);1E-4>k&&(k=e);te.initNonuniformCatmullRom(f.x,g.x,h.x,c.x,d,e,k);ue.initNonuniformCatmullRom(f.y,g.y,h.y,c.y,d,e,k);ve.initNonuniformCatmullRom(f.z,g.z,h.z,c.z,d,e,k)}else"catmullrom"===this.curveType&&(te.initCatmullRom(f.x,g.x,h.x,
17342 c.x,this.tension),ue.initCatmullRom(f.y,g.y,h.y,c.y,this.tension),ve.initCatmullRom(f.z,g.z,h.z,c.z,this.tension));b.set(te.calc(a),ue.calc(a),ve.calc(a));return b};ya.prototype.copy=function(a){S.prototype.copy.call(this,a);this.points=[];for(var b=0,c=a.points.length;b<c;b++)this.points.push(a.points[b].clone());this.closed=a.closed;this.curveType=a.curveType;this.tension=a.tension;return this};Fb.prototype=Object.create(S.prototype);Fb.prototype.constructor=Fb;Fb.prototype.isCubicBezierCurve3=
17343 !0;Fb.prototype.getPoint=function(a,b){b=b||new p;var c=this.v0,d=this.v1,e=this.v2,f=this.v3;b.set(zb(a,c.x,d.x,e.x,f.x),zb(a,c.y,d.y,e.y,f.y),zb(a,c.z,d.z,e.z,f.z));return b};Fb.prototype.copy=function(a){S.prototype.copy.call(this,a);this.v0.copy(a.v0);this.v1.copy(a.v1);this.v2.copy(a.v2);this.v3.copy(a.v3);return this};Gb.prototype=Object.create(S.prototype);Gb.prototype.constructor=Gb;Gb.prototype.isQuadraticBezierCurve3=!0;Gb.prototype.getPoint=function(a,b){b=b||new p;var c=this.v0,d=this.v1,
17344 e=this.v2;b.set(yb(a,c.x,d.x,e.x),yb(a,c.y,d.y,e.y),yb(a,c.z,d.z,e.z));return b};Gb.prototype.copy=function(a){S.prototype.copy.call(this,a);this.v0.copy(a.v0);this.v1.copy(a.v1);this.v2.copy(a.v2);return this};db.prototype=Object.create(S.prototype);db.prototype.constructor=db;db.prototype.isLineCurve3=!0;db.prototype.getPoint=function(a,b){b=b||new p;1===a?b.copy(this.v2):(b.copy(this.v2).sub(this.v1),b.multiplyScalar(a).add(this.v1));return b};db.prototype.getPointAt=function(a,b){return this.getPoint(a,
17345 b)};db.prototype.copy=function(a){S.prototype.copy.call(this,a);this.v1.copy(a.v1);this.v2.copy(a.v2);return this};id.prototype=Object.create(Na.prototype);id.prototype.constructor=id;id.prototype.isArcCurve=!0;S.create=function(a,b){console.log("THREE.Curve.create() has been deprecated");a.prototype=Object.create(S.prototype);a.prototype.constructor=a;a.prototype.getPoint=b;return a};Object.assign(Ab.prototype,{createPointsGeometry:function(a){console.warn("THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.");
17346 a=this.getPoints(a);return this.createGeometry(a)},createSpacedPointsGeometry:function(a){console.warn("THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.");a=this.getSpacedPoints(a);return this.createGeometry(a)},createGeometry:function(a){console.warn("THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.");for(var b=new N,c=0,d=a.length;c<d;c++){var e=a[c];b.vertices.push(new p(e.x,
17347 e.y,e.z||0))}return b}});Object.assign(Bb.prototype,{fromPoints:function(a){console.warn("THREE.Path: .fromPoints() has been renamed to .setFromPoints().");this.setFromPoints(a)}});ef.prototype=Object.create(ya.prototype);ff.prototype=Object.create(ya.prototype);re.prototype=Object.create(ya.prototype);Object.assign(re.prototype,{initFromArray:function(){console.error("THREE.Spline: .initFromArray() has been removed.")},getControlPointsArray:function(){console.error("THREE.Spline: .getControlPointsArray() has been removed.")},
17348 reparametrizeByArcLength:function(){console.error("THREE.Spline: .reparametrizeByArcLength() has been removed.")}});cd.prototype.setColors=function(){console.error("THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.")};oc.prototype.update=function(){console.error("THREE.SkeletonHelper: update() no longer needs to be called.")};Object.assign(kd.prototype,{center:function(a){console.warn("THREE.Box2: .center() has been renamed to .getCenter().");return this.getCenter(a)},
17349 empty:function(){console.warn("THREE.Box2: .empty() has been renamed to .isEmpty().");return this.isEmpty()},isIntersectionBox:function(a){console.warn("THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().");return this.intersectsBox(a)},size:function(a){console.warn("THREE.Box2: .size() has been renamed to .getSize().");return this.getSize(a)}});Object.assign(Oa.prototype,{center:function(a){console.warn("THREE.Box3: .center() has been renamed to .getCenter().");return this.getCenter(a)},
17350 empty:function(){console.warn("THREE.Box3: .empty() has been renamed to .isEmpty().");return this.isEmpty()},isIntersectionBox:function(a){console.warn("THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().");return this.intersectsBox(a)},isIntersectionSphere:function(a){console.warn("THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().");return this.intersectsSphere(a)},size:function(a){console.warn("THREE.Box3: .size() has been renamed to .getSize().");return this.getSize(a)}});
17351 Mb.prototype.center=function(a){console.warn("THREE.Line3: .center() has been renamed to .getCenter().");return this.getCenter(a)};Object.assign(R,{random16:function(){console.warn("THREE.Math: .random16() has been deprecated. Use Math.random() instead.");return Math.random()},nearestPowerOfTwo:function(a){console.warn("THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().");return R.floorPowerOfTwo(a)},nextPowerOfTwo:function(a){console.warn("THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().");
17352 return R.ceilPowerOfTwo(a)}});Object.assign(ra.prototype,{flattenToArrayOffset:function(a,b){console.warn("THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");return this.toArray(a,b)},multiplyVector3:function(a){console.warn("THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.");return a.applyMatrix3(this)},multiplyVector3Array:function(){console.error("THREE.Matrix3: .multiplyVector3Array() has been removed.")},applyToBuffer:function(a){console.warn("THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.");
17353 return this.applyToBufferAttribute(a)},applyToVector3Array:function(){console.error("THREE.Matrix3: .applyToVector3Array() has been removed.")}});Object.assign(K.prototype,{extractPosition:function(a){console.warn("THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().");return this.copyPosition(a)},flattenToArrayOffset:function(a,b){console.warn("THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");return this.toArray(a,b)},getPosition:function(){var a;
17354 return function(){void 0===a&&(a=new p);console.warn("THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.");return a.setFromMatrixColumn(this,3)}}(),setRotationFromQuaternion:function(a){console.warn("THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().");return this.makeRotationFromQuaternion(a)},multiplyToArray:function(){console.warn("THREE.Matrix4: .multiplyToArray() has been removed.")},multiplyVector3:function(a){console.warn("THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.");
17355 return a.applyMatrix4(this)},multiplyVector4:function(a){console.warn("THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.");return a.applyMatrix4(this)},multiplyVector3Array:function(){console.error("THREE.Matrix4: .multiplyVector3Array() has been removed.")},rotateAxis:function(a){console.warn("THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.");a.transformDirection(this)},crossVector:function(a){console.warn("THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.");
17356 return a.applyMatrix4(this)},translate:function(){console.error("THREE.Matrix4: .translate() has been removed.")},rotateX:function(){console.error("THREE.Matrix4: .rotateX() has been removed.")},rotateY:function(){console.error("THREE.Matrix4: .rotateY() has been removed.")},rotateZ:function(){console.error("THREE.Matrix4: .rotateZ() has been removed.")},rotateByAxis:function(){console.error("THREE.Matrix4: .rotateByAxis() has been removed.")},applyToBuffer:function(a){console.warn("THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.");
17357 return this.applyToBufferAttribute(a)},applyToVector3Array:function(){console.error("THREE.Matrix4: .applyToVector3Array() has been removed.")},makeFrustum:function(a,b,c,d,e,f){console.warn("THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.");return this.makePerspective(a,b,d,c,e,f)}});Aa.prototype.isIntersectionLine=function(a){console.warn("THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().");return this.intersectsLine(a)};
17358 Z.prototype.multiplyVector3=function(a){console.warn("THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.");return a.applyQuaternion(this)};Object.assign(lb.prototype,{isIntersectionBox:function(a){console.warn("THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().");return this.intersectsBox(a)},isIntersectionPlane:function(a){console.warn("THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().");return this.intersectsPlane(a)},
17359 isIntersectionSphere:function(a){console.warn("THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().");return this.intersectsSphere(a)}});Object.assign(Cb.prototype,{extractAllPoints:function(a){console.warn("THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.");return this.extractPoints(a)},extrude:function(a){console.warn("THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.");return new $a(this,a)},makeGeometry:function(a){console.warn("THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.");
17360 return new cc(this,a)}});Object.assign(C.prototype,{fromAttribute:function(a,b,c){console.warn("THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().");return this.fromBufferAttribute(a,b,c)},distanceToManhattan:function(a){console.warn("THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().");return this.manhattanDistanceTo(a)},lengthManhattan:function(){console.warn("THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().");return this.manhattanLength()}});
17361 Object.assign(p.prototype,{setEulerFromRotationMatrix:function(){console.error("THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.")},setEulerFromQuaternion:function(){console.error("THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.")},getPositionFromMatrix:function(a){console.warn("THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().");return this.setFromMatrixPosition(a)},
17362 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,
17363 b,c){console.warn("THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().");return this.fromBufferAttribute(a,b,c)},distanceToManhattan:function(a){console.warn("THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().");return this.manhattanDistanceTo(a)},lengthManhattan:function(){console.warn("THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().");return this.manhattanLength()}});Object.assign(da.prototype,{fromAttribute:function(a,
17364 b,c){console.warn("THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().");return this.fromBufferAttribute(a,b,c)},lengthManhattan:function(){console.warn("THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().");return this.manhattanLength()}});N.prototype.computeTangents=function(){console.warn("THREE.Geometry: .computeTangents() has been removed.")};Object.assign(A.prototype,{getChildByName:function(a){console.warn("THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().");
17365 return this.getObjectByName(a)},renderDepth:function(){console.warn("THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.")},translate:function(a,b){console.warn("THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.");return this.translateOnAxis(b,a)}});Object.defineProperties(A.prototype,{eulerOrder:{get:function(){console.warn("THREE.Object3D: .eulerOrder is now .rotation.order.");return this.rotation.order},set:function(a){console.warn("THREE.Object3D: .eulerOrder is now .rotation.order.");
17366 this.rotation.order=a}},useQuaternion:{get:function(){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")},set:function(){console.warn("THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.")}}});Object.defineProperties(Dc.prototype,{objects:{get:function(){console.warn("THREE.LOD: .objects has been renamed to .levels.");return this.levels}}});Object.defineProperty(Ec.prototype,"useVertexTexture",{get:function(){console.warn("THREE.Skeleton: useVertexTexture has been removed.")},
17367 set:function(){console.warn("THREE.Skeleton: useVertexTexture has been removed.")}});Object.defineProperty(S.prototype,"__arcLengthDivisions",{get:function(){console.warn("THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.");return this.arcLengthDivisions},set:function(a){console.warn("THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.");this.arcLengthDivisions=a}});U.prototype.setLens=function(a,b){console.warn("THREE.PerspectiveCamera.setLens is deprecated. Use .setFocalLength and .filmGauge for a photographic setup.");
17368 void 0!==b&&(this.filmGauge=b);this.setFocalLength(a)};Object.defineProperties(ga.prototype,{onlyShadow:{set:function(){console.warn("THREE.Light: .onlyShadow has been removed.")}},shadowCameraFov:{set:function(a){console.warn("THREE.Light: .shadowCameraFov is now .shadow.camera.fov.");this.shadow.camera.fov=a}},shadowCameraLeft:{set:function(a){console.warn("THREE.Light: .shadowCameraLeft is now .shadow.camera.left.");this.shadow.camera.left=a}},shadowCameraRight:{set:function(a){console.warn("THREE.Light: .shadowCameraRight is now .shadow.camera.right.");
17369 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.");
17370 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.");
17371 this.shadow.mapSize.width=a}},shadowMapHeight:{set:function(a){console.warn("THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.");this.shadow.mapSize.height=a}}});Object.defineProperties(P.prototype,{length:{get:function(){console.warn("THREE.BufferAttribute: .length has been deprecated. Use .count instead.");return this.array.length}}});Object.assign(D.prototype,{addIndex:function(a){console.warn("THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().");this.setIndex(a)},addDrawCall:function(a,
17372 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.")}});
17373 Object.defineProperties(D.prototype,{drawcalls:{get:function(){console.error("THREE.BufferGeometry: .drawcalls has been renamed to .groups.");return this.groups}},offsets:{get:function(){console.warn("THREE.BufferGeometry: .offsets has been renamed to .groups.");return this.groups}}});Object.defineProperties(Jd.prototype,{dynamic:{set:function(){console.warn("THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.")}},onUpdate:{value:function(){console.warn("THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.");
17374 return this}}});Object.defineProperties(Q.prototype,{wrapAround:{get:function(){console.warn("THREE.Material: .wrapAround has been removed.")},set:function(){console.warn("THREE.Material: .wrapAround has been removed.")}},wrapRGB:{get:function(){console.warn("THREE.Material: .wrapRGB has been removed.");return new H}},shading:{get:function(){console.error("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead.")},set:function(a){console.warn("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead.");
17375 this.flatShading=1===a}}});Object.defineProperties(Ia.prototype,{metal:{get:function(){console.warn("THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.");return!1},set:function(){console.warn("THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead")}}});Object.defineProperties(oa.prototype,{derivatives:{get:function(){console.warn("THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.");return this.extensions.derivatives},
17376 set:function(a){console.warn("THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.");this.extensions.derivatives=a}}});Object.assign(Wd.prototype,{getCurrentRenderTarget:function(){console.warn("THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().");return this.getRenderTarget()},getMaxAnisotropy:function(){console.warn("THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().");return this.capabilities.getMaxAnisotropy()},getPrecision:function(){console.warn("THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.");
17377 return this.capabilities.precision},resetGLState:function(){console.warn("THREE.WebGLRenderer: .resetGLState() is now .state.reset().");return this.state.reset()},supportsFloatTextures:function(){console.warn("THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( 'OES_texture_float' ).");return this.extensions.get("OES_texture_float")},supportsHalfFloatTextures:function(){console.warn("THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( 'OES_texture_half_float' ).");
17378 return this.extensions.get("OES_texture_half_float")},supportsStandardDerivatives:function(){console.warn("THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( 'OES_standard_derivatives' ).");return this.extensions.get("OES_standard_derivatives")},supportsCompressedTextureS3TC:function(){console.warn("THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( 'WEBGL_compressed_texture_s3tc' ).");return this.extensions.get("WEBGL_compressed_texture_s3tc")},
17379 supportsCompressedTexturePVRTC:function(){console.warn("THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( 'WEBGL_compressed_texture_pvrtc' ).");return this.extensions.get("WEBGL_compressed_texture_pvrtc")},supportsBlendMinMax:function(){console.warn("THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( 'EXT_blend_minmax' ).");return this.extensions.get("EXT_blend_minmax")},supportsVertexTextures:function(){console.warn("THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.");
17380 return this.capabilities.vertexTextures},supportsInstancedArrays:function(){console.warn("THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( 'ANGLE_instanced_arrays' ).");return this.extensions.get("ANGLE_instanced_arrays")},enableScissorTest:function(a){console.warn("THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().");this.setScissorTest(a)},initMaterial:function(){console.warn("THREE.WebGLRenderer: .initMaterial() has been removed.")},addPrePlugin:function(){console.warn("THREE.WebGLRenderer: .addPrePlugin() has been removed.")},
17381 addPostPlugin:function(){console.warn("THREE.WebGLRenderer: .addPostPlugin() has been removed.")},updateShadowMap:function(){console.warn("THREE.WebGLRenderer: .updateShadowMap() has been removed.")}});Object.defineProperties(Wd.prototype,{shadowMapEnabled:{get:function(){return this.shadowMap.enabled},set:function(a){console.warn("THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.");this.shadowMap.enabled=a}},shadowMapType:{get:function(){return this.shadowMap.type},set:function(a){console.warn("THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.");
17382 this.shadowMap.type=a}},shadowMapCullFace:{get:function(){return this.shadowMap.cullFace},set:function(a){console.warn("THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.");this.shadowMap.cullFace=a}}});Object.defineProperties(Ie.prototype,{cullFace:{get:function(){return this.renderReverseSided?2:1},set:function(a){a=1!==a;console.warn("WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to "+a+".");this.renderReverseSided=a}}});Object.defineProperties(Hb.prototype,
17383 {wrapS:{get:function(){console.warn("THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.");return this.texture.wrapS},set:function(a){console.warn("THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.");this.texture.wrapS=a}},wrapT:{get:function(){console.warn("THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.");return this.texture.wrapT},set:function(a){console.warn("THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.");this.texture.wrapT=a}},magFilter:{get:function(){console.warn("THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.");
17384 return this.texture.magFilter},set:function(a){console.warn("THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.");this.texture.magFilter=a}},minFilter:{get:function(){console.warn("THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.");return this.texture.minFilter},set:function(a){console.warn("THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.");this.texture.minFilter=a}},anisotropy:{get:function(){console.warn("THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.");
17385 return this.texture.anisotropy},set:function(a){console.warn("THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.");this.texture.anisotropy=a}},offset:{get:function(){console.warn("THREE.WebGLRenderTarget: .offset is now .texture.offset.");return this.texture.offset},set:function(a){console.warn("THREE.WebGLRenderTarget: .offset is now .texture.offset.");this.texture.offset=a}},repeat:{get:function(){console.warn("THREE.WebGLRenderTarget: .repeat is now .texture.repeat.");return this.texture.repeat},
17386 set:function(a){console.warn("THREE.WebGLRenderTarget: .repeat is now .texture.repeat.");this.texture.repeat=a}},format:{get:function(){console.warn("THREE.WebGLRenderTarget: .format is now .texture.format.");return this.texture.format},set:function(a){console.warn("THREE.WebGLRenderTarget: .format is now .texture.format.");this.texture.format=a}},type:{get:function(){console.warn("THREE.WebGLRenderTarget: .type is now .texture.type.");return this.texture.type},set:function(a){console.warn("THREE.WebGLRenderTarget: .type is now .texture.type.");
17387 this.texture.type=a}},generateMipmaps:{get:function(){console.warn("THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.");return this.texture.generateMipmaps},set:function(a){console.warn("THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.");this.texture.generateMipmaps=a}}});lc.prototype.load=function(a){console.warn("THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.");var b=this;(new ee).load(a,function(a){b.setBuffer(a)});return this};
17388 ie.prototype.getData=function(){console.warn("THREE.AudioAnalyser: .getData() is now .getFrequencyData().");return this.getFrequencyData()};$c.prototype.updateCubeMap=function(a,b){console.warn("THREE.CubeCamera: .updateCubeMap() is now .update().");return this.update(a,b)};m.WebGLRenderTargetCube=Ib;m.WebGLRenderTarget=Hb;m.WebGLRenderer=Wd;m.ShaderLib=mb;m.UniformsLib=E;m.UniformsUtils=Ea;m.ShaderChunk=W;m.FogExp2=Ob;m.Fog=Pb;m.Scene=od;m.LensFlare=Xd;m.Sprite=Cc;m.LOD=Dc;m.SkinnedMesh=qd;m.Skeleton=
17389 Ec;m.Bone=pd;m.Mesh=pa;m.LineSegments=ca;m.LineLoop=rd;m.Line=ma;m.Points=Qb;m.Group=Fc;m.VideoTexture=sd;m.DataTexture=fb;m.CompressedTexture=Rb;m.CubeTexture=Ua;m.CanvasTexture=tc;m.DepthTexture=Gc;m.Texture=ea;m.CompressedTextureLoader=Qe;m.DataTextureLoader=Zd;m.CubeTextureLoader=$d;m.TextureLoader=td;m.ObjectLoader=Re;m.MaterialLoader=Id;m.BufferGeometryLoader=ae;m.DefaultLoadingManager=wa;m.LoadingManager=Yd;m.JSONLoader=be;m.ImageLoader=Xc;m.FontLoader=Te;m.FileLoader=Ja;m.Loader=kc;m.Cache=
17390 jd;m.AudioLoader=ee;m.SpotLightShadow=vd;m.SpotLight=wd;m.PointLight=xd;m.RectAreaLight=Bd;m.HemisphereLight=ud;m.DirectionalLightShadow=yd;m.DirectionalLight=zd;m.AmbientLight=Ad;m.LightShadow=vb;m.Light=ga;m.StereoCamera=Ue;m.PerspectiveCamera=U;m.OrthographicCamera=Kb;m.CubeCamera=$c;m.ArrayCamera=nd;m.Camera=La;m.AudioListener=fe;m.PositionalAudio=he;m.AudioContext=ge;m.AudioAnalyser=ie;m.Audio=lc;m.VectorKeyframeTrack=ic;m.StringKeyframeTrack=Fd;m.QuaternionKeyframeTrack=Zc;m.NumberKeyframeTrack=
17391 jc;m.ColorKeyframeTrack=Hd;m.BooleanKeyframeTrack=Gd;m.PropertyMixer=je;m.PropertyBinding=na;m.KeyframeTrack=xb;m.AnimationUtils=T;m.AnimationObjectGroup=We;m.AnimationMixer=Ye;m.AnimationClip=ka;m.Uniform=Jd;m.InstancedBufferGeometry=ke;m.BufferGeometry=D;m.Geometry=N;m.InterleavedBufferAttribute=le;m.InstancedInterleavedBuffer=me;m.InterleavedBuffer=mc;m.InstancedBufferAttribute=ne;m.Face3=Pa;m.Object3D=A;m.Raycaster=Ze;m.Layers=Pd;m.EventDispatcher=ja;m.Clock=af;m.QuaternionLinearInterpolant=Ed;
17392 m.LinearInterpolant=Yc;m.DiscreteInterpolant=Dd;m.CubicInterpolant=Cd;m.Interpolant=xa;m.Triangle=Qa;m.Math=R;m.Spherical=bf;m.Cylindrical=cf;m.Plane=Aa;m.Frustum=ld;m.Sphere=Da;m.Ray=lb;m.Matrix4=K;m.Matrix3=ra;m.Box3=Oa;m.Box2=kd;m.Line3=Mb;m.Euler=Ya;m.Vector4=da;m.Vector3=p;m.Vector2=C;m.Quaternion=Z;m.Color=H;m.ImmediateRenderObject=ad;m.VertexNormalsHelper=bd;m.SpotLightHelper=nc;m.SkeletonHelper=oc;m.PointLightHelper=pc;m.RectAreaLightHelper=qc;m.HemisphereLightHelper=rc;m.GridHelper=cd;m.PolarGridHelper=
17393 Kd;m.FaceNormalsHelper=dd;m.DirectionalLightHelper=sc;m.CameraHelper=ed;m.BoxHelper=Db;m.Box3Helper=fd;m.PlaneHelper=gd;m.ArrowHelper=Eb;m.AxesHelper=hd;m.CatmullRomCurve3=ya;m.CubicBezierCurve3=Fb;m.QuadraticBezierCurve3=Gb;m.LineCurve3=db;m.ArcCurve=id;m.EllipseCurve=Na;m.SplineCurve=ab;m.CubicBezierCurve=bb;m.QuadraticBezierCurve=cb;m.LineCurve=Ka;m.Shape=Cb;m.Path=Bb;m.ShapePath=ce;m.Font=de;m.CurvePath=Ab;m.Curve=S;m.ShapeUtils=Ha;m.SceneUtils={createMultiMaterialObject:function(a,b){for(var c=
17394 new Fc,d=0,e=b.length;d<e;d++)c.add(new pa(a,b[d]));return c},detach:function(a,b,c){a.applyMatrix(b.matrixWorld);b.remove(a);c.add(a)},attach:function(a,b,c){a.applyMatrix((new K).getInverse(c.matrixWorld));b.remove(a);c.add(a)}};m.WebGLUtils=Pe;m.WireframeGeometry=Sb;m.ParametricGeometry=Hc;m.ParametricBufferGeometry=Tb;m.TetrahedronGeometry=Jc;m.TetrahedronBufferGeometry=Ub;m.OctahedronGeometry=Kc;m.OctahedronBufferGeometry=nb;m.IcosahedronGeometry=Lc;m.IcosahedronBufferGeometry=Vb;m.DodecahedronGeometry=
17395 Mc;m.DodecahedronBufferGeometry=Wb;m.PolyhedronGeometry=Ic;m.PolyhedronBufferGeometry=qa;m.TubeGeometry=Nc;m.TubeBufferGeometry=Xb;m.TorusKnotGeometry=Oc;m.TorusKnotBufferGeometry=Yb;m.TorusGeometry=Pc;m.TorusBufferGeometry=Zb;m.TextGeometry=Qc;m.TextBufferGeometry=$b;m.SphereGeometry=Rc;m.SphereBufferGeometry=ob;m.RingGeometry=Sc;m.RingBufferGeometry=ac;m.PlaneGeometry=Ac;m.PlaneBufferGeometry=kb;m.LatheGeometry=Tc;m.LatheBufferGeometry=bc;m.ShapeGeometry=cc;m.ShapeBufferGeometry=dc;m.ExtrudeGeometry=
17396 $a;m.ExtrudeBufferGeometry=Ga;m.EdgesGeometry=ec;m.ConeGeometry=Uc;m.ConeBufferGeometry=Vc;m.CylinderGeometry=pb;m.CylinderBufferGeometry=Sa;m.CircleGeometry=Wc;m.CircleBufferGeometry=fc;m.BoxGeometry=Lb;m.BoxBufferGeometry=jb;m.ShadowMaterial=gc;m.SpriteMaterial=Za;m.RawShaderMaterial=hc;m.ShaderMaterial=oa;m.PointsMaterial=Ba;m.MeshPhysicalMaterial=qb;m.MeshStandardMaterial=Ma;m.MeshPhongMaterial=Ia;m.MeshToonMaterial=rb;m.MeshNormalMaterial=sb;m.MeshLambertMaterial=tb;m.MeshDepthMaterial=Wa;m.MeshDistanceMaterial=
17397 Xa;m.MeshBasicMaterial=va;m.LineDashedMaterial=ub;m.LineBasicMaterial=O;m.Material=Q;m.Float64BufferAttribute=zc;m.Float32BufferAttribute=y;m.Uint32BufferAttribute=ib;m.Int32BufferAttribute=yc;m.Uint16BufferAttribute=hb;m.Int16BufferAttribute=xc;m.Uint8ClampedBufferAttribute=wc;m.Uint8BufferAttribute=vc;m.Int8BufferAttribute=uc;m.BufferAttribute=P;m.REVISION="88";m.MOUSE={LEFT:0,MIDDLE:1,RIGHT:2};m.CullFaceNone=0;m.CullFaceBack=1;m.CullFaceFront=2;m.CullFaceFrontBack=3;m.FrontFaceDirectionCW=0;m.FrontFaceDirectionCCW=
17398 1;m.BasicShadowMap=0;m.PCFShadowMap=1;m.PCFSoftShadowMap=2;m.FrontSide=0;m.BackSide=1;m.DoubleSide=2;m.FlatShading=1;m.SmoothShading=2;m.NoColors=0;m.FaceColors=1;m.VertexColors=2;m.NoBlending=0;m.NormalBlending=1;m.AdditiveBlending=2;m.SubtractiveBlending=3;m.MultiplyBlending=4;m.CustomBlending=5;m.AddEquation=100;m.SubtractEquation=101;m.ReverseSubtractEquation=102;m.MinEquation=103;m.MaxEquation=104;m.ZeroFactor=200;m.OneFactor=201;m.SrcColorFactor=202;m.OneMinusSrcColorFactor=203;m.SrcAlphaFactor=
17399 204;m.OneMinusSrcAlphaFactor=205;m.DstAlphaFactor=206;m.OneMinusDstAlphaFactor=207;m.DstColorFactor=208;m.OneMinusDstColorFactor=209;m.SrcAlphaSaturateFactor=210;m.NeverDepth=0;m.AlwaysDepth=1;m.LessDepth=2;m.LessEqualDepth=3;m.EqualDepth=4;m.GreaterEqualDepth=5;m.GreaterDepth=6;m.NotEqualDepth=7;m.MultiplyOperation=0;m.MixOperation=1;m.AddOperation=2;m.NoToneMapping=0;m.LinearToneMapping=1;m.ReinhardToneMapping=2;m.Uncharted2ToneMapping=3;m.CineonToneMapping=4;m.UVMapping=300;m.CubeReflectionMapping=
17400 301;m.CubeRefractionMapping=302;m.EquirectangularReflectionMapping=303;m.EquirectangularRefractionMapping=304;m.SphericalReflectionMapping=305;m.CubeUVReflectionMapping=306;m.CubeUVRefractionMapping=307;m.RepeatWrapping=1E3;m.ClampToEdgeWrapping=1001;m.MirroredRepeatWrapping=1002;m.NearestFilter=1003;m.NearestMipMapNearestFilter=1004;m.NearestMipMapLinearFilter=1005;m.LinearFilter=1006;m.LinearMipMapNearestFilter=1007;m.LinearMipMapLinearFilter=1008;m.UnsignedByteType=1009;m.ByteType=1010;m.ShortType=
17401 1011;m.UnsignedShortType=1012;m.IntType=1013;m.UnsignedIntType=1014;m.FloatType=1015;m.HalfFloatType=1016;m.UnsignedShort4444Type=1017;m.UnsignedShort5551Type=1018;m.UnsignedShort565Type=1019;m.UnsignedInt248Type=1020;m.AlphaFormat=1021;m.RGBFormat=1022;m.RGBAFormat=1023;m.LuminanceFormat=1024;m.LuminanceAlphaFormat=1025;m.RGBEFormat=1023;m.DepthFormat=1026;m.DepthStencilFormat=1027;m.RGB_S3TC_DXT1_Format=2001;m.RGBA_S3TC_DXT1_Format=2002;m.RGBA_S3TC_DXT3_Format=2003;m.RGBA_S3TC_DXT5_Format=2004;
17402 m.RGB_PVRTC_4BPPV1_Format=2100;m.RGB_PVRTC_2BPPV1_Format=2101;m.RGBA_PVRTC_4BPPV1_Format=2102;m.RGBA_PVRTC_2BPPV1_Format=2103;m.RGB_ETC1_Format=2151;m.LoopOnce=2200;m.LoopRepeat=2201;m.LoopPingPong=2202;m.InterpolateDiscrete=2300;m.InterpolateLinear=2301;m.InterpolateSmooth=2302;m.ZeroCurvatureEnding=2400;m.ZeroSlopeEnding=2401;m.WrapAroundEnding=2402;m.TrianglesDrawMode=0;m.TriangleStripDrawMode=1;m.TriangleFanDrawMode=2;m.LinearEncoding=3E3;m.sRGBEncoding=3001;m.GammaEncoding=3007;m.RGBEEncoding=
17403 3002;m.LogLuvEncoding=3003;m.RGBM7Encoding=3004;m.RGBM16Encoding=3005;m.RGBDEncoding=3006;m.BasicDepthPacking=3200;m.RGBADepthPacking=3201;m.CubeGeometry=Lb;m.Face4=function(a,b,c,d,e,f,g){console.warn("THREE.Face4 has been removed. A THREE.Face3 will be created instead.");return new Pa(a,b,c,e,f,g)};m.LineStrip=0;m.LinePieces=1;m.MeshFaceMaterial=function(a){console.warn("THREE.MeshFaceMaterial has been removed. Use an Array instead.");return a};m.MultiMaterial=function(a){void 0===a&&(a=[]);console.warn("THREE.MultiMaterial has been removed. Use an Array instead.");
17404 a.isMultiMaterial=!0;a.materials=a;a.clone=function(){return a.slice()};return a};m.PointCloud=function(a,b){console.warn("THREE.PointCloud has been renamed to THREE.Points.");return new Qb(a,b)};m.Particle=function(a){console.warn("THREE.Particle has been renamed to THREE.Sprite.");return new Cc(a)};m.ParticleSystem=function(a,b){console.warn("THREE.ParticleSystem has been renamed to THREE.Points.");return new Qb(a,b)};m.PointCloudMaterial=function(a){console.warn("THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.");
17405 return new Ba(a)};m.ParticleBasicMaterial=function(a){console.warn("THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.");return new Ba(a)};m.ParticleSystemMaterial=function(a){console.warn("THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.");return new Ba(a)};m.Vertex=function(a,b,c){console.warn("THREE.Vertex has been removed. Use THREE.Vector3 instead.");return new p(a,b,c)};m.DynamicBufferAttribute=function(a,b){console.warn("THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.");
17406 return(new P(a,b)).setDynamic(!0)};m.Int8Attribute=function(a,b){console.warn("THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.");return new uc(a,b)};m.Uint8Attribute=function(a,b){console.warn("THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.");return new vc(a,b)};m.Uint8ClampedAttribute=function(a,b){console.warn("THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.");return new wc(a,
17407 b)};m.Int16Attribute=function(a,b){console.warn("THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.");return new xc(a,b)};m.Uint16Attribute=function(a,b){console.warn("THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.");return new hb(a,b)};m.Int32Attribute=function(a,b){console.warn("THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.");return new yc(a,b)};m.Uint32Attribute=function(a,b){console.warn("THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.");
17408 return new ib(a,b)};m.Float32Attribute=function(a,b){console.warn("THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.");return new y(a,b)};m.Float64Attribute=function(a,b){console.warn("THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.");return new zc(a,b)};m.ClosedSplineCurve3=ef;m.SplineCurve3=ff;m.Spline=re;m.AxisHelper=function(a){console.warn("THREE.AxisHelper has been renamed to THREE.AxesHelper.");return new hd(a)};
17409 m.BoundingBoxHelper=function(a,b){console.warn("THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.");return new Db(a,b)};m.EdgesHelper=function(a,b){console.warn("THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.");return new ca(new ec(a.geometry),new O({color:void 0!==b?b:16777215}))};m.WireframeHelper=function(a,b){console.warn("THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.");return new ca(new Sb(a.geometry),new O({color:void 0!==
17410 b?b:16777215}))};m.XHRLoader=function(a){console.warn("THREE.XHRLoader has been renamed to THREE.FileLoader.");return new Ja(a)};m.BinaryTextureLoader=function(a){console.warn("THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.");return new Zd(a)};m.GeometryUtils={merge:function(a,b,c){console.warn("THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.");if(b.isMesh){b.matrixAutoUpdate&&b.updateMatrix();
17411 var d=b.matrix;b=b.geometry}a.merge(b,d,c)},center:function(a){console.warn("THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.");return a.center()}};m.ImageUtils={crossOrigin:void 0,loadTexture:function(a,b,c,d){console.warn("THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.");var e=new td;e.setCrossOrigin(this.crossOrigin);a=e.load(a,c,void 0,d);b&&(a.mapping=b);return a},loadTextureCube:function(a,b,c,d){console.warn("THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.");
17412 var e=new $d;e.setCrossOrigin(this.crossOrigin);a=e.load(a,c,void 0,d);b&&(a.mapping=b);return a},loadCompressedTexture:function(){console.error("THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.")},loadCompressedTextureCube:function(){console.error("THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.")}};m.Projector=function(){console.error("THREE.Projector has been moved to /examples/js/renderers/Projector.js.");this.projectVector=
17413 function(a,b){console.warn("THREE.Projector: .projectVector() is now vector.project().");a.project(b)};this.unprojectVector=function(a,b){console.warn("THREE.Projector: .unprojectVector() is now vector.unproject().");a.unproject(b)};this.pickingRay=function(){console.error("THREE.Projector: .pickingRay() is now raycaster.setFromCamera().")}};m.CanvasRenderer=function(){console.error("THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js");this.domElement=document.createElementNS("http://www.w3.org/1999/xhtml",
17414 "canvas");this.clear=function(){};this.render=function(){};this.setClearColor=function(){};this.setSize=function(){}};Object.defineProperty(m,"__esModule",{value:!0})});
17415
17416 },{}],242:[function(require,module,exports){
17417 'use strict';
17418
17419 module.exports = TinyQueue;
17420
17421 function TinyQueue(data, compare) {
17422     if (!(this instanceof TinyQueue)) return new TinyQueue(data, compare);
17423
17424     this.data = data || [];
17425     this.length = this.data.length;
17426     this.compare = compare || defaultCompare;
17427
17428     if (this.length > 0) {
17429         for (var i = (this.length >> 1); i >= 0; i--) this._down(i);
17430     }
17431 }
17432
17433 function defaultCompare(a, b) {
17434     return a < b ? -1 : a > b ? 1 : 0;
17435 }
17436
17437 TinyQueue.prototype = {
17438
17439     push: function (item) {
17440         this.data.push(item);
17441         this.length++;
17442         this._up(this.length - 1);
17443     },
17444
17445     pop: function () {
17446         if (this.length === 0) return undefined;
17447         var top = this.data[0];
17448         this.length--;
17449         if (this.length > 0) {
17450             this.data[0] = this.data[this.length];
17451             this._down(0);
17452         }
17453         this.data.pop();
17454         return top;
17455     },
17456
17457     peek: function () {
17458         return this.data[0];
17459     },
17460
17461     _up: function (pos) {
17462         var data = this.data;
17463         var compare = this.compare;
17464         var item = data[pos];
17465
17466         while (pos > 0) {
17467             var parent = (pos - 1) >> 1;
17468             var current = data[parent];
17469             if (compare(item, current) >= 0) break;
17470             data[pos] = current;
17471             pos = parent;
17472         }
17473
17474         data[pos] = item;
17475     },
17476
17477     _down: function (pos) {
17478         var data = this.data;
17479         var compare = this.compare;
17480         var len = this.length;
17481         var halfLen = len >> 1;
17482         var item = data[pos];
17483
17484         while (pos < halfLen) {
17485             var left = (pos << 1) + 1;
17486             var right = left + 1;
17487             var best = data[left];
17488
17489             if (right < len && compare(data[right], best) < 0) {
17490                 left = right;
17491                 best = data[right];
17492             }
17493             if (compare(best, item) >= 0) break;
17494
17495             data[pos] = best;
17496             pos = left;
17497         }
17498
17499         data[pos] = item;
17500     }
17501 };
17502
17503 },{}],243:[function(require,module,exports){
17504 //     Underscore.js 1.8.3
17505 //     http://underscorejs.org
17506 //     (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
17507 //     Underscore may be freely distributed under the MIT license.
17508
17509 (function() {
17510
17511   // Baseline setup
17512   // --------------
17513
17514   // Establish the root object, `window` in the browser, or `exports` on the server.
17515   var root = this;
17516
17517   // Save the previous value of the `_` variable.
17518   var previousUnderscore = root._;
17519
17520   // Save bytes in the minified (but not gzipped) version:
17521   var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
17522
17523   // Create quick reference variables for speed access to core prototypes.
17524   var
17525     push             = ArrayProto.push,
17526     slice            = ArrayProto.slice,
17527     toString         = ObjProto.toString,
17528     hasOwnProperty   = ObjProto.hasOwnProperty;
17529
17530   // All **ECMAScript 5** native function implementations that we hope to use
17531   // are declared here.
17532   var
17533     nativeIsArray      = Array.isArray,
17534     nativeKeys         = Object.keys,
17535     nativeBind         = FuncProto.bind,
17536     nativeCreate       = Object.create;
17537
17538   // Naked function reference for surrogate-prototype-swapping.
17539   var Ctor = function(){};
17540
17541   // Create a safe reference to the Underscore object for use below.
17542   var _ = function(obj) {
17543     if (obj instanceof _) return obj;
17544     if (!(this instanceof _)) return new _(obj);
17545     this._wrapped = obj;
17546   };
17547
17548   // Export the Underscore object for **Node.js**, with
17549   // backwards-compatibility for the old `require()` API. If we're in
17550   // the browser, add `_` as a global object.
17551   if (typeof exports !== 'undefined') {
17552     if (typeof module !== 'undefined' && module.exports) {
17553       exports = module.exports = _;
17554     }
17555     exports._ = _;
17556   } else {
17557     root._ = _;
17558   }
17559
17560   // Current version.
17561   _.VERSION = '1.8.3';
17562
17563   // Internal function that returns an efficient (for current engines) version
17564   // of the passed-in callback, to be repeatedly applied in other Underscore
17565   // functions.
17566   var optimizeCb = function(func, context, argCount) {
17567     if (context === void 0) return func;
17568     switch (argCount == null ? 3 : argCount) {
17569       case 1: return function(value) {
17570         return func.call(context, value);
17571       };
17572       case 2: return function(value, other) {
17573         return func.call(context, value, other);
17574       };
17575       case 3: return function(value, index, collection) {
17576         return func.call(context, value, index, collection);
17577       };
17578       case 4: return function(accumulator, value, index, collection) {
17579         return func.call(context, accumulator, value, index, collection);
17580       };
17581     }
17582     return function() {
17583       return func.apply(context, arguments);
17584     };
17585   };
17586
17587   // A mostly-internal function to generate callbacks that can be applied
17588   // to each element in a collection, returning the desired result — either
17589   // identity, an arbitrary callback, a property matcher, or a property accessor.
17590   var cb = function(value, context, argCount) {
17591     if (value == null) return _.identity;
17592     if (_.isFunction(value)) return optimizeCb(value, context, argCount);
17593     if (_.isObject(value)) return _.matcher(value);
17594     return _.property(value);
17595   };
17596   _.iteratee = function(value, context) {
17597     return cb(value, context, Infinity);
17598   };
17599
17600   // An internal function for creating assigner functions.
17601   var createAssigner = function(keysFunc, undefinedOnly) {
17602     return function(obj) {
17603       var length = arguments.length;
17604       if (length < 2 || obj == null) return obj;
17605       for (var index = 1; index < length; index++) {
17606         var source = arguments[index],
17607             keys = keysFunc(source),
17608             l = keys.length;
17609         for (var i = 0; i < l; i++) {
17610           var key = keys[i];
17611           if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];
17612         }
17613       }
17614       return obj;
17615     };
17616   };
17617
17618   // An internal function for creating a new object that inherits from another.
17619   var baseCreate = function(prototype) {
17620     if (!_.isObject(prototype)) return {};
17621     if (nativeCreate) return nativeCreate(prototype);
17622     Ctor.prototype = prototype;
17623     var result = new Ctor;
17624     Ctor.prototype = null;
17625     return result;
17626   };
17627
17628   var property = function(key) {
17629     return function(obj) {
17630       return obj == null ? void 0 : obj[key];
17631     };
17632   };
17633
17634   // Helper for collection methods to determine whether a collection
17635   // should be iterated as an array or as an object
17636   // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
17637   // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
17638   var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
17639   var getLength = property('length');
17640   var isArrayLike = function(collection) {
17641     var length = getLength(collection);
17642     return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
17643   };
17644
17645   // Collection Functions
17646   // --------------------
17647
17648   // The cornerstone, an `each` implementation, aka `forEach`.
17649   // Handles raw objects in addition to array-likes. Treats all
17650   // sparse array-likes as if they were dense.
17651   _.each = _.forEach = function(obj, iteratee, context) {
17652     iteratee = optimizeCb(iteratee, context);
17653     var i, length;
17654     if (isArrayLike(obj)) {
17655       for (i = 0, length = obj.length; i < length; i++) {
17656         iteratee(obj[i], i, obj);
17657       }
17658     } else {
17659       var keys = _.keys(obj);
17660       for (i = 0, length = keys.length; i < length; i++) {
17661         iteratee(obj[keys[i]], keys[i], obj);
17662       }
17663     }
17664     return obj;
17665   };
17666
17667   // Return the results of applying the iteratee to each element.
17668   _.map = _.collect = function(obj, iteratee, context) {
17669     iteratee = cb(iteratee, context);
17670     var keys = !isArrayLike(obj) && _.keys(obj),
17671         length = (keys || obj).length,
17672         results = Array(length);
17673     for (var index = 0; index < length; index++) {
17674       var currentKey = keys ? keys[index] : index;
17675       results[index] = iteratee(obj[currentKey], currentKey, obj);
17676     }
17677     return results;
17678   };
17679
17680   // Create a reducing function iterating left or right.
17681   function createReduce(dir) {
17682     // Optimized iterator function as using arguments.length
17683     // in the main function will deoptimize the, see #1991.
17684     function iterator(obj, iteratee, memo, keys, index, length) {
17685       for (; index >= 0 && index < length; index += dir) {
17686         var currentKey = keys ? keys[index] : index;
17687         memo = iteratee(memo, obj[currentKey], currentKey, obj);
17688       }
17689       return memo;
17690     }
17691
17692     return function(obj, iteratee, memo, context) {
17693       iteratee = optimizeCb(iteratee, context, 4);
17694       var keys = !isArrayLike(obj) && _.keys(obj),
17695           length = (keys || obj).length,
17696           index = dir > 0 ? 0 : length - 1;
17697       // Determine the initial value if none is provided.
17698       if (arguments.length < 3) {
17699         memo = obj[keys ? keys[index] : index];
17700         index += dir;
17701       }
17702       return iterator(obj, iteratee, memo, keys, index, length);
17703     };
17704   }
17705
17706   // **Reduce** builds up a single result from a list of values, aka `inject`,
17707   // or `foldl`.
17708   _.reduce = _.foldl = _.inject = createReduce(1);
17709
17710   // The right-associative version of reduce, also known as `foldr`.
17711   _.reduceRight = _.foldr = createReduce(-1);
17712
17713   // Return the first value which passes a truth test. Aliased as `detect`.
17714   _.find = _.detect = function(obj, predicate, context) {
17715     var key;
17716     if (isArrayLike(obj)) {
17717       key = _.findIndex(obj, predicate, context);
17718     } else {
17719       key = _.findKey(obj, predicate, context);
17720     }
17721     if (key !== void 0 && key !== -1) return obj[key];
17722   };
17723
17724   // Return all the elements that pass a truth test.
17725   // Aliased as `select`.
17726   _.filter = _.select = function(obj, predicate, context) {
17727     var results = [];
17728     predicate = cb(predicate, context);
17729     _.each(obj, function(value, index, list) {
17730       if (predicate(value, index, list)) results.push(value);
17731     });
17732     return results;
17733   };
17734
17735   // Return all the elements for which a truth test fails.
17736   _.reject = function(obj, predicate, context) {
17737     return _.filter(obj, _.negate(cb(predicate)), context);
17738   };
17739
17740   // Determine whether all of the elements match a truth test.
17741   // Aliased as `all`.
17742   _.every = _.all = function(obj, predicate, context) {
17743     predicate = cb(predicate, context);
17744     var keys = !isArrayLike(obj) && _.keys(obj),
17745         length = (keys || obj).length;
17746     for (var index = 0; index < length; index++) {
17747       var currentKey = keys ? keys[index] : index;
17748       if (!predicate(obj[currentKey], currentKey, obj)) return false;
17749     }
17750     return true;
17751   };
17752
17753   // Determine if at least one element in the object matches a truth test.
17754   // Aliased as `any`.
17755   _.some = _.any = function(obj, predicate, context) {
17756     predicate = cb(predicate, context);
17757     var keys = !isArrayLike(obj) && _.keys(obj),
17758         length = (keys || obj).length;
17759     for (var index = 0; index < length; index++) {
17760       var currentKey = keys ? keys[index] : index;
17761       if (predicate(obj[currentKey], currentKey, obj)) return true;
17762     }
17763     return false;
17764   };
17765
17766   // Determine if the array or object contains a given item (using `===`).
17767   // Aliased as `includes` and `include`.
17768   _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {
17769     if (!isArrayLike(obj)) obj = _.values(obj);
17770     if (typeof fromIndex != 'number' || guard) fromIndex = 0;
17771     return _.indexOf(obj, item, fromIndex) >= 0;
17772   };
17773
17774   // Invoke a method (with arguments) on every item in a collection.
17775   _.invoke = function(obj, method) {
17776     var args = slice.call(arguments, 2);
17777     var isFunc = _.isFunction(method);
17778     return _.map(obj, function(value) {
17779       var func = isFunc ? method : value[method];
17780       return func == null ? func : func.apply(value, args);
17781     });
17782   };
17783
17784   // Convenience version of a common use case of `map`: fetching a property.
17785   _.pluck = function(obj, key) {
17786     return _.map(obj, _.property(key));
17787   };
17788
17789   // Convenience version of a common use case of `filter`: selecting only objects
17790   // containing specific `key:value` pairs.
17791   _.where = function(obj, attrs) {
17792     return _.filter(obj, _.matcher(attrs));
17793   };
17794
17795   // Convenience version of a common use case of `find`: getting the first object
17796   // containing specific `key:value` pairs.
17797   _.findWhere = function(obj, attrs) {
17798     return _.find(obj, _.matcher(attrs));
17799   };
17800
17801   // Return the maximum element (or element-based computation).
17802   _.max = function(obj, iteratee, context) {
17803     var result = -Infinity, lastComputed = -Infinity,
17804         value, computed;
17805     if (iteratee == null && obj != null) {
17806       obj = isArrayLike(obj) ? obj : _.values(obj);
17807       for (var i = 0, length = obj.length; i < length; i++) {
17808         value = obj[i];
17809         if (value > result) {
17810           result = value;
17811         }
17812       }
17813     } else {
17814       iteratee = cb(iteratee, context);
17815       _.each(obj, function(value, index, list) {
17816         computed = iteratee(value, index, list);
17817         if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
17818           result = value;
17819           lastComputed = computed;
17820         }
17821       });
17822     }
17823     return result;
17824   };
17825
17826   // Return the minimum element (or element-based computation).
17827   _.min = function(obj, iteratee, context) {
17828     var result = Infinity, lastComputed = Infinity,
17829         value, computed;
17830     if (iteratee == null && obj != null) {
17831       obj = isArrayLike(obj) ? obj : _.values(obj);
17832       for (var i = 0, length = obj.length; i < length; i++) {
17833         value = obj[i];
17834         if (value < result) {
17835           result = value;
17836         }
17837       }
17838     } else {
17839       iteratee = cb(iteratee, context);
17840       _.each(obj, function(value, index, list) {
17841         computed = iteratee(value, index, list);
17842         if (computed < lastComputed || computed === Infinity && result === Infinity) {
17843           result = value;
17844           lastComputed = computed;
17845         }
17846       });
17847     }
17848     return result;
17849   };
17850
17851   // Shuffle a collection, using the modern version of the
17852   // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
17853   _.shuffle = function(obj) {
17854     var set = isArrayLike(obj) ? obj : _.values(obj);
17855     var length = set.length;
17856     var shuffled = Array(length);
17857     for (var index = 0, rand; index < length; index++) {
17858       rand = _.random(0, index);
17859       if (rand !== index) shuffled[index] = shuffled[rand];
17860       shuffled[rand] = set[index];
17861     }
17862     return shuffled;
17863   };
17864
17865   // Sample **n** random values from a collection.
17866   // If **n** is not specified, returns a single random element.
17867   // The internal `guard` argument allows it to work with `map`.
17868   _.sample = function(obj, n, guard) {
17869     if (n == null || guard) {
17870       if (!isArrayLike(obj)) obj = _.values(obj);
17871       return obj[_.random(obj.length - 1)];
17872     }
17873     return _.shuffle(obj).slice(0, Math.max(0, n));
17874   };
17875
17876   // Sort the object's values by a criterion produced by an iteratee.
17877   _.sortBy = function(obj, iteratee, context) {
17878     iteratee = cb(iteratee, context);
17879     return _.pluck(_.map(obj, function(value, index, list) {
17880       return {
17881         value: value,
17882         index: index,
17883         criteria: iteratee(value, index, list)
17884       };
17885     }).sort(function(left, right) {
17886       var a = left.criteria;
17887       var b = right.criteria;
17888       if (a !== b) {
17889         if (a > b || a === void 0) return 1;
17890         if (a < b || b === void 0) return -1;
17891       }
17892       return left.index - right.index;
17893     }), 'value');
17894   };
17895
17896   // An internal function used for aggregate "group by" operations.
17897   var group = function(behavior) {
17898     return function(obj, iteratee, context) {
17899       var result = {};
17900       iteratee = cb(iteratee, context);
17901       _.each(obj, function(value, index) {
17902         var key = iteratee(value, index, obj);
17903         behavior(result, value, key);
17904       });
17905       return result;
17906     };
17907   };
17908
17909   // Groups the object's values by a criterion. Pass either a string attribute
17910   // to group by, or a function that returns the criterion.
17911   _.groupBy = group(function(result, value, key) {
17912     if (_.has(result, key)) result[key].push(value); else result[key] = [value];
17913   });
17914
17915   // Indexes the object's values by a criterion, similar to `groupBy`, but for
17916   // when you know that your index values will be unique.
17917   _.indexBy = group(function(result, value, key) {
17918     result[key] = value;
17919   });
17920
17921   // Counts instances of an object that group by a certain criterion. Pass
17922   // either a string attribute to count by, or a function that returns the
17923   // criterion.
17924   _.countBy = group(function(result, value, key) {
17925     if (_.has(result, key)) result[key]++; else result[key] = 1;
17926   });
17927
17928   // Safely create a real, live array from anything iterable.
17929   _.toArray = function(obj) {
17930     if (!obj) return [];
17931     if (_.isArray(obj)) return slice.call(obj);
17932     if (isArrayLike(obj)) return _.map(obj, _.identity);
17933     return _.values(obj);
17934   };
17935
17936   // Return the number of elements in an object.
17937   _.size = function(obj) {
17938     if (obj == null) return 0;
17939     return isArrayLike(obj) ? obj.length : _.keys(obj).length;
17940   };
17941
17942   // Split a collection into two arrays: one whose elements all satisfy the given
17943   // predicate, and one whose elements all do not satisfy the predicate.
17944   _.partition = function(obj, predicate, context) {
17945     predicate = cb(predicate, context);
17946     var pass = [], fail = [];
17947     _.each(obj, function(value, key, obj) {
17948       (predicate(value, key, obj) ? pass : fail).push(value);
17949     });
17950     return [pass, fail];
17951   };
17952
17953   // Array Functions
17954   // ---------------
17955
17956   // Get the first element of an array. Passing **n** will return the first N
17957   // values in the array. Aliased as `head` and `take`. The **guard** check
17958   // allows it to work with `_.map`.
17959   _.first = _.head = _.take = function(array, n, guard) {
17960     if (array == null) return void 0;
17961     if (n == null || guard) return array[0];
17962     return _.initial(array, array.length - n);
17963   };
17964
17965   // Returns everything but the last entry of the array. Especially useful on
17966   // the arguments object. Passing **n** will return all the values in
17967   // the array, excluding the last N.
17968   _.initial = function(array, n, guard) {
17969     return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
17970   };
17971
17972   // Get the last element of an array. Passing **n** will return the last N
17973   // values in the array.
17974   _.last = function(array, n, guard) {
17975     if (array == null) return void 0;
17976     if (n == null || guard) return array[array.length - 1];
17977     return _.rest(array, Math.max(0, array.length - n));
17978   };
17979
17980   // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
17981   // Especially useful on the arguments object. Passing an **n** will return
17982   // the rest N values in the array.
17983   _.rest = _.tail = _.drop = function(array, n, guard) {
17984     return slice.call(array, n == null || guard ? 1 : n);
17985   };
17986
17987   // Trim out all falsy values from an array.
17988   _.compact = function(array) {
17989     return _.filter(array, _.identity);
17990   };
17991
17992   // Internal implementation of a recursive `flatten` function.
17993   var flatten = function(input, shallow, strict, startIndex) {
17994     var output = [], idx = 0;
17995     for (var i = startIndex || 0, length = getLength(input); i < length; i++) {
17996       var value = input[i];
17997       if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
17998         //flatten current level of array or arguments object
17999         if (!shallow) value = flatten(value, shallow, strict);
18000         var j = 0, len = value.length;
18001         output.length += len;
18002         while (j < len) {
18003           output[idx++] = value[j++];
18004         }
18005       } else if (!strict) {
18006         output[idx++] = value;
18007       }
18008     }
18009     return output;
18010   };
18011
18012   // Flatten out an array, either recursively (by default), or just one level.
18013   _.flatten = function(array, shallow) {
18014     return flatten(array, shallow, false);
18015   };
18016
18017   // Return a version of the array that does not contain the specified value(s).
18018   _.without = function(array) {
18019     return _.difference(array, slice.call(arguments, 1));
18020   };
18021
18022   // Produce a duplicate-free version of the array. If the array has already
18023   // been sorted, you have the option of using a faster algorithm.
18024   // Aliased as `unique`.
18025   _.uniq = _.unique = function(array, isSorted, iteratee, context) {
18026     if (!_.isBoolean(isSorted)) {
18027       context = iteratee;
18028       iteratee = isSorted;
18029       isSorted = false;
18030     }
18031     if (iteratee != null) iteratee = cb(iteratee, context);
18032     var result = [];
18033     var seen = [];
18034     for (var i = 0, length = getLength(array); i < length; i++) {
18035       var value = array[i],
18036           computed = iteratee ? iteratee(value, i, array) : value;
18037       if (isSorted) {
18038         if (!i || seen !== computed) result.push(value);
18039         seen = computed;
18040       } else if (iteratee) {
18041         if (!_.contains(seen, computed)) {
18042           seen.push(computed);
18043           result.push(value);
18044         }
18045       } else if (!_.contains(result, value)) {
18046         result.push(value);
18047       }
18048     }
18049     return result;
18050   };
18051
18052   // Produce an array that contains the union: each distinct element from all of
18053   // the passed-in arrays.
18054   _.union = function() {
18055     return _.uniq(flatten(arguments, true, true));
18056   };
18057
18058   // Produce an array that contains every item shared between all the
18059   // passed-in arrays.
18060   _.intersection = function(array) {
18061     var result = [];
18062     var argsLength = arguments.length;
18063     for (var i = 0, length = getLength(array); i < length; i++) {
18064       var item = array[i];
18065       if (_.contains(result, item)) continue;
18066       for (var j = 1; j < argsLength; j++) {
18067         if (!_.contains(arguments[j], item)) break;
18068       }
18069       if (j === argsLength) result.push(item);
18070     }
18071     return result;
18072   };
18073
18074   // Take the difference between one array and a number of other arrays.
18075   // Only the elements present in just the first array will remain.
18076   _.difference = function(array) {
18077     var rest = flatten(arguments, true, true, 1);
18078     return _.filter(array, function(value){
18079       return !_.contains(rest, value);
18080     });
18081   };
18082
18083   // Zip together multiple lists into a single array -- elements that share
18084   // an index go together.
18085   _.zip = function() {
18086     return _.unzip(arguments);
18087   };
18088
18089   // Complement of _.zip. Unzip accepts an array of arrays and groups
18090   // each array's elements on shared indices
18091   _.unzip = function(array) {
18092     var length = array && _.max(array, getLength).length || 0;
18093     var result = Array(length);
18094
18095     for (var index = 0; index < length; index++) {
18096       result[index] = _.pluck(array, index);
18097     }
18098     return result;
18099   };
18100
18101   // Converts lists into objects. Pass either a single array of `[key, value]`
18102   // pairs, or two parallel arrays of the same length -- one of keys, and one of
18103   // the corresponding values.
18104   _.object = function(list, values) {
18105     var result = {};
18106     for (var i = 0, length = getLength(list); i < length; i++) {
18107       if (values) {
18108         result[list[i]] = values[i];
18109       } else {
18110         result[list[i][0]] = list[i][1];
18111       }
18112     }
18113     return result;
18114   };
18115
18116   // Generator function to create the findIndex and findLastIndex functions
18117   function createPredicateIndexFinder(dir) {
18118     return function(array, predicate, context) {
18119       predicate = cb(predicate, context);
18120       var length = getLength(array);
18121       var index = dir > 0 ? 0 : length - 1;
18122       for (; index >= 0 && index < length; index += dir) {
18123         if (predicate(array[index], index, array)) return index;
18124       }
18125       return -1;
18126     };
18127   }
18128
18129   // Returns the first index on an array-like that passes a predicate test
18130   _.findIndex = createPredicateIndexFinder(1);
18131   _.findLastIndex = createPredicateIndexFinder(-1);
18132
18133   // Use a comparator function to figure out the smallest index at which
18134   // an object should be inserted so as to maintain order. Uses binary search.
18135   _.sortedIndex = function(array, obj, iteratee, context) {
18136     iteratee = cb(iteratee, context, 1);
18137     var value = iteratee(obj);
18138     var low = 0, high = getLength(array);
18139     while (low < high) {
18140       var mid = Math.floor((low + high) / 2);
18141       if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
18142     }
18143     return low;
18144   };
18145
18146   // Generator function to create the indexOf and lastIndexOf functions
18147   function createIndexFinder(dir, predicateFind, sortedIndex) {
18148     return function(array, item, idx) {
18149       var i = 0, length = getLength(array);
18150       if (typeof idx == 'number') {
18151         if (dir > 0) {
18152             i = idx >= 0 ? idx : Math.max(idx + length, i);
18153         } else {
18154             length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
18155         }
18156       } else if (sortedIndex && idx && length) {
18157         idx = sortedIndex(array, item);
18158         return array[idx] === item ? idx : -1;
18159       }
18160       if (item !== item) {
18161         idx = predicateFind(slice.call(array, i, length), _.isNaN);
18162         return idx >= 0 ? idx + i : -1;
18163       }
18164       for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
18165         if (array[idx] === item) return idx;
18166       }
18167       return -1;
18168     };
18169   }
18170
18171   // Return the position of the first occurrence of an item in an array,
18172   // or -1 if the item is not included in the array.
18173   // If the array is large and already in sort order, pass `true`
18174   // for **isSorted** to use binary search.
18175   _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
18176   _.lastIndexOf = createIndexFinder(-1, _.findLastIndex);
18177
18178   // Generate an integer Array containing an arithmetic progression. A port of
18179   // the native Python `range()` function. See
18180   // [the Python documentation](http://docs.python.org/library/functions.html#range).
18181   _.range = function(start, stop, step) {
18182     if (stop == null) {
18183       stop = start || 0;
18184       start = 0;
18185     }
18186     step = step || 1;
18187
18188     var length = Math.max(Math.ceil((stop - start) / step), 0);
18189     var range = Array(length);
18190
18191     for (var idx = 0; idx < length; idx++, start += step) {
18192       range[idx] = start;
18193     }
18194
18195     return range;
18196   };
18197
18198   // Function (ahem) Functions
18199   // ------------------
18200
18201   // Determines whether to execute a function as a constructor
18202   // or a normal function with the provided arguments
18203   var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {
18204     if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
18205     var self = baseCreate(sourceFunc.prototype);
18206     var result = sourceFunc.apply(self, args);
18207     if (_.isObject(result)) return result;
18208     return self;
18209   };
18210
18211   // Create a function bound to a given object (assigning `this`, and arguments,
18212   // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
18213   // available.
18214   _.bind = function(func, context) {
18215     if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
18216     if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
18217     var args = slice.call(arguments, 2);
18218     var bound = function() {
18219       return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));
18220     };
18221     return bound;
18222   };
18223
18224   // Partially apply a function by creating a version that has had some of its
18225   // arguments pre-filled, without changing its dynamic `this` context. _ acts
18226   // as a placeholder, allowing any combination of arguments to be pre-filled.
18227   _.partial = function(func) {
18228     var boundArgs = slice.call(arguments, 1);
18229     var bound = function() {
18230       var position = 0, length = boundArgs.length;
18231       var args = Array(length);
18232       for (var i = 0; i < length; i++) {
18233         args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];
18234       }
18235       while (position < arguments.length) args.push(arguments[position++]);
18236       return executeBound(func, bound, this, this, args);
18237     };
18238     return bound;
18239   };
18240
18241   // Bind a number of an object's methods to that object. Remaining arguments
18242   // are the method names to be bound. Useful for ensuring that all callbacks
18243   // defined on an object belong to it.
18244   _.bindAll = function(obj) {
18245     var i, length = arguments.length, key;
18246     if (length <= 1) throw new Error('bindAll must be passed function names');
18247     for (i = 1; i < length; i++) {
18248       key = arguments[i];
18249       obj[key] = _.bind(obj[key], obj);
18250     }
18251     return obj;
18252   };
18253
18254   // Memoize an expensive function by storing its results.
18255   _.memoize = function(func, hasher) {
18256     var memoize = function(key) {
18257       var cache = memoize.cache;
18258       var address = '' + (hasher ? hasher.apply(this, arguments) : key);
18259       if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
18260       return cache[address];
18261     };
18262     memoize.cache = {};
18263     return memoize;
18264   };
18265
18266   // Delays a function for the given number of milliseconds, and then calls
18267   // it with the arguments supplied.
18268   _.delay = function(func, wait) {
18269     var args = slice.call(arguments, 2);
18270     return setTimeout(function(){
18271       return func.apply(null, args);
18272     }, wait);
18273   };
18274
18275   // Defers a function, scheduling it to run after the current call stack has
18276   // cleared.
18277   _.defer = _.partial(_.delay, _, 1);
18278
18279   // Returns a function, that, when invoked, will only be triggered at most once
18280   // during a given window of time. Normally, the throttled function will run
18281   // as much as it can, without ever going more than once per `wait` duration;
18282   // but if you'd like to disable the execution on the leading edge, pass
18283   // `{leading: false}`. To disable execution on the trailing edge, ditto.
18284   _.throttle = function(func, wait, options) {
18285     var context, args, result;
18286     var timeout = null;
18287     var previous = 0;
18288     if (!options) options = {};
18289     var later = function() {
18290       previous = options.leading === false ? 0 : _.now();
18291       timeout = null;
18292       result = func.apply(context, args);
18293       if (!timeout) context = args = null;
18294     };
18295     return function() {
18296       var now = _.now();
18297       if (!previous && options.leading === false) previous = now;
18298       var remaining = wait - (now - previous);
18299       context = this;
18300       args = arguments;
18301       if (remaining <= 0 || remaining > wait) {
18302         if (timeout) {
18303           clearTimeout(timeout);
18304           timeout = null;
18305         }
18306         previous = now;
18307         result = func.apply(context, args);
18308         if (!timeout) context = args = null;
18309       } else if (!timeout && options.trailing !== false) {
18310         timeout = setTimeout(later, remaining);
18311       }
18312       return result;
18313     };
18314   };
18315
18316   // Returns a function, that, as long as it continues to be invoked, will not
18317   // be triggered. The function will be called after it stops being called for
18318   // N milliseconds. If `immediate` is passed, trigger the function on the
18319   // leading edge, instead of the trailing.
18320   _.debounce = function(func, wait, immediate) {
18321     var timeout, args, context, timestamp, result;
18322
18323     var later = function() {
18324       var last = _.now() - timestamp;
18325
18326       if (last < wait && last >= 0) {
18327         timeout = setTimeout(later, wait - last);
18328       } else {
18329         timeout = null;
18330         if (!immediate) {
18331           result = func.apply(context, args);
18332           if (!timeout) context = args = null;
18333         }
18334       }
18335     };
18336
18337     return function() {
18338       context = this;
18339       args = arguments;
18340       timestamp = _.now();
18341       var callNow = immediate && !timeout;
18342       if (!timeout) timeout = setTimeout(later, wait);
18343       if (callNow) {
18344         result = func.apply(context, args);
18345         context = args = null;
18346       }
18347
18348       return result;
18349     };
18350   };
18351
18352   // Returns the first function passed as an argument to the second,
18353   // allowing you to adjust arguments, run code before and after, and
18354   // conditionally execute the original function.
18355   _.wrap = function(func, wrapper) {
18356     return _.partial(wrapper, func);
18357   };
18358
18359   // Returns a negated version of the passed-in predicate.
18360   _.negate = function(predicate) {
18361     return function() {
18362       return !predicate.apply(this, arguments);
18363     };
18364   };
18365
18366   // Returns a function that is the composition of a list of functions, each
18367   // consuming the return value of the function that follows.
18368   _.compose = function() {
18369     var args = arguments;
18370     var start = args.length - 1;
18371     return function() {
18372       var i = start;
18373       var result = args[start].apply(this, arguments);
18374       while (i--) result = args[i].call(this, result);
18375       return result;
18376     };
18377   };
18378
18379   // Returns a function that will only be executed on and after the Nth call.
18380   _.after = function(times, func) {
18381     return function() {
18382       if (--times < 1) {
18383         return func.apply(this, arguments);
18384       }
18385     };
18386   };
18387
18388   // Returns a function that will only be executed up to (but not including) the Nth call.
18389   _.before = function(times, func) {
18390     var memo;
18391     return function() {
18392       if (--times > 0) {
18393         memo = func.apply(this, arguments);
18394       }
18395       if (times <= 1) func = null;
18396       return memo;
18397     };
18398   };
18399
18400   // Returns a function that will be executed at most one time, no matter how
18401   // often you call it. Useful for lazy initialization.
18402   _.once = _.partial(_.before, 2);
18403
18404   // Object Functions
18405   // ----------------
18406
18407   // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
18408   var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
18409   var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
18410                       'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
18411
18412   function collectNonEnumProps(obj, keys) {
18413     var nonEnumIdx = nonEnumerableProps.length;
18414     var constructor = obj.constructor;
18415     var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto;
18416
18417     // Constructor is a special case.
18418     var prop = 'constructor';
18419     if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);
18420
18421     while (nonEnumIdx--) {
18422       prop = nonEnumerableProps[nonEnumIdx];
18423       if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
18424         keys.push(prop);
18425       }
18426     }
18427   }
18428
18429   // Retrieve the names of an object's own properties.
18430   // Delegates to **ECMAScript 5**'s native `Object.keys`
18431   _.keys = function(obj) {
18432     if (!_.isObject(obj)) return [];
18433     if (nativeKeys) return nativeKeys(obj);
18434     var keys = [];
18435     for (var key in obj) if (_.has(obj, key)) keys.push(key);
18436     // Ahem, IE < 9.
18437     if (hasEnumBug) collectNonEnumProps(obj, keys);
18438     return keys;
18439   };
18440
18441   // Retrieve all the property names of an object.
18442   _.allKeys = function(obj) {
18443     if (!_.isObject(obj)) return [];
18444     var keys = [];
18445     for (var key in obj) keys.push(key);
18446     // Ahem, IE < 9.
18447     if (hasEnumBug) collectNonEnumProps(obj, keys);
18448     return keys;
18449   };
18450
18451   // Retrieve the values of an object's properties.
18452   _.values = function(obj) {
18453     var keys = _.keys(obj);
18454     var length = keys.length;
18455     var values = Array(length);
18456     for (var i = 0; i < length; i++) {
18457       values[i] = obj[keys[i]];
18458     }
18459     return values;
18460   };
18461
18462   // Returns the results of applying the iteratee to each element of the object
18463   // In contrast to _.map it returns an object
18464   _.mapObject = function(obj, iteratee, context) {
18465     iteratee = cb(iteratee, context);
18466     var keys =  _.keys(obj),
18467           length = keys.length,
18468           results = {},
18469           currentKey;
18470       for (var index = 0; index < length; index++) {
18471         currentKey = keys[index];
18472         results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
18473       }
18474       return results;
18475   };
18476
18477   // Convert an object into a list of `[key, value]` pairs.
18478   _.pairs = function(obj) {
18479     var keys = _.keys(obj);
18480     var length = keys.length;
18481     var pairs = Array(length);
18482     for (var i = 0; i < length; i++) {
18483       pairs[i] = [keys[i], obj[keys[i]]];
18484     }
18485     return pairs;
18486   };
18487
18488   // Invert the keys and values of an object. The values must be serializable.
18489   _.invert = function(obj) {
18490     var result = {};
18491     var keys = _.keys(obj);
18492     for (var i = 0, length = keys.length; i < length; i++) {
18493       result[obj[keys[i]]] = keys[i];
18494     }
18495     return result;
18496   };
18497
18498   // Return a sorted list of the function names available on the object.
18499   // Aliased as `methods`
18500   _.functions = _.methods = function(obj) {
18501     var names = [];
18502     for (var key in obj) {
18503       if (_.isFunction(obj[key])) names.push(key);
18504     }
18505     return names.sort();
18506   };
18507
18508   // Extend a given object with all the properties in passed-in object(s).
18509   _.extend = createAssigner(_.allKeys);
18510
18511   // Assigns a given object with all the own properties in the passed-in object(s)
18512   // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
18513   _.extendOwn = _.assign = createAssigner(_.keys);
18514
18515   // Returns the first key on an object that passes a predicate test
18516   _.findKey = function(obj, predicate, context) {
18517     predicate = cb(predicate, context);
18518     var keys = _.keys(obj), key;
18519     for (var i = 0, length = keys.length; i < length; i++) {
18520       key = keys[i];
18521       if (predicate(obj[key], key, obj)) return key;
18522     }
18523   };
18524
18525   // Return a copy of the object only containing the whitelisted properties.
18526   _.pick = function(object, oiteratee, context) {
18527     var result = {}, obj = object, iteratee, keys;
18528     if (obj == null) return result;
18529     if (_.isFunction(oiteratee)) {
18530       keys = _.allKeys(obj);
18531       iteratee = optimizeCb(oiteratee, context);
18532     } else {
18533       keys = flatten(arguments, false, false, 1);
18534       iteratee = function(value, key, obj) { return key in obj; };
18535       obj = Object(obj);
18536     }
18537     for (var i = 0, length = keys.length; i < length; i++) {
18538       var key = keys[i];
18539       var value = obj[key];
18540       if (iteratee(value, key, obj)) result[key] = value;
18541     }
18542     return result;
18543   };
18544
18545    // Return a copy of the object without the blacklisted properties.
18546   _.omit = function(obj, iteratee, context) {
18547     if (_.isFunction(iteratee)) {
18548       iteratee = _.negate(iteratee);
18549     } else {
18550       var keys = _.map(flatten(arguments, false, false, 1), String);
18551       iteratee = function(value, key) {
18552         return !_.contains(keys, key);
18553       };
18554     }
18555     return _.pick(obj, iteratee, context);
18556   };
18557
18558   // Fill in a given object with default properties.
18559   _.defaults = createAssigner(_.allKeys, true);
18560
18561   // Creates an object that inherits from the given prototype object.
18562   // If additional properties are provided then they will be added to the
18563   // created object.
18564   _.create = function(prototype, props) {
18565     var result = baseCreate(prototype);
18566     if (props) _.extendOwn(result, props);
18567     return result;
18568   };
18569
18570   // Create a (shallow-cloned) duplicate of an object.
18571   _.clone = function(obj) {
18572     if (!_.isObject(obj)) return obj;
18573     return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
18574   };
18575
18576   // Invokes interceptor with the obj, and then returns obj.
18577   // The primary purpose of this method is to "tap into" a method chain, in
18578   // order to perform operations on intermediate results within the chain.
18579   _.tap = function(obj, interceptor) {
18580     interceptor(obj);
18581     return obj;
18582   };
18583
18584   // Returns whether an object has a given set of `key:value` pairs.
18585   _.isMatch = function(object, attrs) {
18586     var keys = _.keys(attrs), length = keys.length;
18587     if (object == null) return !length;
18588     var obj = Object(object);
18589     for (var i = 0; i < length; i++) {
18590       var key = keys[i];
18591       if (attrs[key] !== obj[key] || !(key in obj)) return false;
18592     }
18593     return true;
18594   };
18595
18596
18597   // Internal recursive comparison function for `isEqual`.
18598   var eq = function(a, b, aStack, bStack) {
18599     // Identical objects are equal. `0 === -0`, but they aren't identical.
18600     // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
18601     if (a === b) return a !== 0 || 1 / a === 1 / b;
18602     // A strict comparison is necessary because `null == undefined`.
18603     if (a == null || b == null) return a === b;
18604     // Unwrap any wrapped objects.
18605     if (a instanceof _) a = a._wrapped;
18606     if (b instanceof _) b = b._wrapped;
18607     // Compare `[[Class]]` names.
18608     var className = toString.call(a);
18609     if (className !== toString.call(b)) return false;
18610     switch (className) {
18611       // Strings, numbers, regular expressions, dates, and booleans are compared by value.
18612       case '[object RegExp]':
18613       // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
18614       case '[object String]':
18615         // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
18616         // equivalent to `new String("5")`.
18617         return '' + a === '' + b;
18618       case '[object Number]':
18619         // `NaN`s are equivalent, but non-reflexive.
18620         // Object(NaN) is equivalent to NaN
18621         if (+a !== +a) return +b !== +b;
18622         // An `egal` comparison is performed for other numeric values.
18623         return +a === 0 ? 1 / +a === 1 / b : +a === +b;
18624       case '[object Date]':
18625       case '[object Boolean]':
18626         // Coerce dates and booleans to numeric primitive values. Dates are compared by their
18627         // millisecond representations. Note that invalid dates with millisecond representations
18628         // of `NaN` are not equivalent.
18629         return +a === +b;
18630     }
18631
18632     var areArrays = className === '[object Array]';
18633     if (!areArrays) {
18634       if (typeof a != 'object' || typeof b != 'object') return false;
18635
18636       // Objects with different constructors are not equivalent, but `Object`s or `Array`s
18637       // from different frames are.
18638       var aCtor = a.constructor, bCtor = b.constructor;
18639       if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
18640                                _.isFunction(bCtor) && bCtor instanceof bCtor)
18641                           && ('constructor' in a && 'constructor' in b)) {
18642         return false;
18643       }
18644     }
18645     // Assume equality for cyclic structures. The algorithm for detecting cyclic
18646     // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
18647
18648     // Initializing stack of traversed objects.
18649     // It's done here since we only need them for objects and arrays comparison.
18650     aStack = aStack || [];
18651     bStack = bStack || [];
18652     var length = aStack.length;
18653     while (length--) {
18654       // Linear search. Performance is inversely proportional to the number of
18655       // unique nested structures.
18656       if (aStack[length] === a) return bStack[length] === b;
18657     }
18658
18659     // Add the first object to the stack of traversed objects.
18660     aStack.push(a);
18661     bStack.push(b);
18662
18663     // Recursively compare objects and arrays.
18664     if (areArrays) {
18665       // Compare array lengths to determine if a deep comparison is necessary.
18666       length = a.length;
18667       if (length !== b.length) return false;
18668       // Deep compare the contents, ignoring non-numeric properties.
18669       while (length--) {
18670         if (!eq(a[length], b[length], aStack, bStack)) return false;
18671       }
18672     } else {
18673       // Deep compare objects.
18674       var keys = _.keys(a), key;
18675       length = keys.length;
18676       // Ensure that both objects contain the same number of properties before comparing deep equality.
18677       if (_.keys(b).length !== length) return false;
18678       while (length--) {
18679         // Deep compare each member
18680         key = keys[length];
18681         if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
18682       }
18683     }
18684     // Remove the first object from the stack of traversed objects.
18685     aStack.pop();
18686     bStack.pop();
18687     return true;
18688   };
18689
18690   // Perform a deep comparison to check if two objects are equal.
18691   _.isEqual = function(a, b) {
18692     return eq(a, b);
18693   };
18694
18695   // Is a given array, string, or object empty?
18696   // An "empty" object has no enumerable own-properties.
18697   _.isEmpty = function(obj) {
18698     if (obj == null) return true;
18699     if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
18700     return _.keys(obj).length === 0;
18701   };
18702
18703   // Is a given value a DOM element?
18704   _.isElement = function(obj) {
18705     return !!(obj && obj.nodeType === 1);
18706   };
18707
18708   // Is a given value an array?
18709   // Delegates to ECMA5's native Array.isArray
18710   _.isArray = nativeIsArray || function(obj) {
18711     return toString.call(obj) === '[object Array]';
18712   };
18713
18714   // Is a given variable an object?
18715   _.isObject = function(obj) {
18716     var type = typeof obj;
18717     return type === 'function' || type === 'object' && !!obj;
18718   };
18719
18720   // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.
18721   _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) {
18722     _['is' + name] = function(obj) {
18723       return toString.call(obj) === '[object ' + name + ']';
18724     };
18725   });
18726
18727   // Define a fallback version of the method in browsers (ahem, IE < 9), where
18728   // there isn't any inspectable "Arguments" type.
18729   if (!_.isArguments(arguments)) {
18730     _.isArguments = function(obj) {
18731       return _.has(obj, 'callee');
18732     };
18733   }
18734
18735   // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
18736   // IE 11 (#1621), and in Safari 8 (#1929).
18737   if (typeof /./ != 'function' && typeof Int8Array != 'object') {
18738     _.isFunction = function(obj) {
18739       return typeof obj == 'function' || false;
18740     };
18741   }
18742
18743   // Is a given object a finite number?
18744   _.isFinite = function(obj) {
18745     return isFinite(obj) && !isNaN(parseFloat(obj));
18746   };
18747
18748   // Is the given value `NaN`? (NaN is the only number which does not equal itself).
18749   _.isNaN = function(obj) {
18750     return _.isNumber(obj) && obj !== +obj;
18751   };
18752
18753   // Is a given value a boolean?
18754   _.isBoolean = function(obj) {
18755     return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
18756   };
18757
18758   // Is a given value equal to null?
18759   _.isNull = function(obj) {
18760     return obj === null;
18761   };
18762
18763   // Is a given variable undefined?
18764   _.isUndefined = function(obj) {
18765     return obj === void 0;
18766   };
18767
18768   // Shortcut function for checking if an object has a given property directly
18769   // on itself (in other words, not on a prototype).
18770   _.has = function(obj, key) {
18771     return obj != null && hasOwnProperty.call(obj, key);
18772   };
18773
18774   // Utility Functions
18775   // -----------------
18776
18777   // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
18778   // previous owner. Returns a reference to the Underscore object.
18779   _.noConflict = function() {
18780     root._ = previousUnderscore;
18781     return this;
18782   };
18783
18784   // Keep the identity function around for default iteratees.
18785   _.identity = function(value) {
18786     return value;
18787   };
18788
18789   // Predicate-generating functions. Often useful outside of Underscore.
18790   _.constant = function(value) {
18791     return function() {
18792       return value;
18793     };
18794   };
18795
18796   _.noop = function(){};
18797
18798   _.property = property;
18799
18800   // Generates a function for a given object that returns a given property.
18801   _.propertyOf = function(obj) {
18802     return obj == null ? function(){} : function(key) {
18803       return obj[key];
18804     };
18805   };
18806
18807   // Returns a predicate for checking whether an object has a given set of
18808   // `key:value` pairs.
18809   _.matcher = _.matches = function(attrs) {
18810     attrs = _.extendOwn({}, attrs);
18811     return function(obj) {
18812       return _.isMatch(obj, attrs);
18813     };
18814   };
18815
18816   // Run a function **n** times.
18817   _.times = function(n, iteratee, context) {
18818     var accum = Array(Math.max(0, n));
18819     iteratee = optimizeCb(iteratee, context, 1);
18820     for (var i = 0; i < n; i++) accum[i] = iteratee(i);
18821     return accum;
18822   };
18823
18824   // Return a random integer between min and max (inclusive).
18825   _.random = function(min, max) {
18826     if (max == null) {
18827       max = min;
18828       min = 0;
18829     }
18830     return min + Math.floor(Math.random() * (max - min + 1));
18831   };
18832
18833   // A (possibly faster) way to get the current timestamp as an integer.
18834   _.now = Date.now || function() {
18835     return new Date().getTime();
18836   };
18837
18838    // List of HTML entities for escaping.
18839   var escapeMap = {
18840     '&': '&amp;',
18841     '<': '&lt;',
18842     '>': '&gt;',
18843     '"': '&quot;',
18844     "'": '&#x27;',
18845     '`': '&#x60;'
18846   };
18847   var unescapeMap = _.invert(escapeMap);
18848
18849   // Functions for escaping and unescaping strings to/from HTML interpolation.
18850   var createEscaper = function(map) {
18851     var escaper = function(match) {
18852       return map[match];
18853     };
18854     // Regexes for identifying a key that needs to be escaped
18855     var source = '(?:' + _.keys(map).join('|') + ')';
18856     var testRegexp = RegExp(source);
18857     var replaceRegexp = RegExp(source, 'g');
18858     return function(string) {
18859       string = string == null ? '' : '' + string;
18860       return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
18861     };
18862   };
18863   _.escape = createEscaper(escapeMap);
18864   _.unescape = createEscaper(unescapeMap);
18865
18866   // If the value of the named `property` is a function then invoke it with the
18867   // `object` as context; otherwise, return it.
18868   _.result = function(object, property, fallback) {
18869     var value = object == null ? void 0 : object[property];
18870     if (value === void 0) {
18871       value = fallback;
18872     }
18873     return _.isFunction(value) ? value.call(object) : value;
18874   };
18875
18876   // Generate a unique integer id (unique within the entire client session).
18877   // Useful for temporary DOM ids.
18878   var idCounter = 0;
18879   _.uniqueId = function(prefix) {
18880     var id = ++idCounter + '';
18881     return prefix ? prefix + id : id;
18882   };
18883
18884   // By default, Underscore uses ERB-style template delimiters, change the
18885   // following template settings to use alternative delimiters.
18886   _.templateSettings = {
18887     evaluate    : /<%([\s\S]+?)%>/g,
18888     interpolate : /<%=([\s\S]+?)%>/g,
18889     escape      : /<%-([\s\S]+?)%>/g
18890   };
18891
18892   // When customizing `templateSettings`, if you don't want to define an
18893   // interpolation, evaluation or escaping regex, we need one that is
18894   // guaranteed not to match.
18895   var noMatch = /(.)^/;
18896
18897   // Certain characters need to be escaped so that they can be put into a
18898   // string literal.
18899   var escapes = {
18900     "'":      "'",
18901     '\\':     '\\',
18902     '\r':     'r',
18903     '\n':     'n',
18904     '\u2028': 'u2028',
18905     '\u2029': 'u2029'
18906   };
18907
18908   var escaper = /\\|'|\r|\n|\u2028|\u2029/g;
18909
18910   var escapeChar = function(match) {
18911     return '\\' + escapes[match];
18912   };
18913
18914   // JavaScript micro-templating, similar to John Resig's implementation.
18915   // Underscore templating handles arbitrary delimiters, preserves whitespace,
18916   // and correctly escapes quotes within interpolated code.
18917   // NB: `oldSettings` only exists for backwards compatibility.
18918   _.template = function(text, settings, oldSettings) {
18919     if (!settings && oldSettings) settings = oldSettings;
18920     settings = _.defaults({}, settings, _.templateSettings);
18921
18922     // Combine delimiters into one regular expression via alternation.
18923     var matcher = RegExp([
18924       (settings.escape || noMatch).source,
18925       (settings.interpolate || noMatch).source,
18926       (settings.evaluate || noMatch).source
18927     ].join('|') + '|$', 'g');
18928
18929     // Compile the template source, escaping string literals appropriately.
18930     var index = 0;
18931     var source = "__p+='";
18932     text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
18933       source += text.slice(index, offset).replace(escaper, escapeChar);
18934       index = offset + match.length;
18935
18936       if (escape) {
18937         source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
18938       } else if (interpolate) {
18939         source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
18940       } else if (evaluate) {
18941         source += "';\n" + evaluate + "\n__p+='";
18942       }
18943
18944       // Adobe VMs need the match returned to produce the correct offest.
18945       return match;
18946     });
18947     source += "';\n";
18948
18949     // If a variable is not specified, place data values in local scope.
18950     if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
18951
18952     source = "var __t,__p='',__j=Array.prototype.join," +
18953       "print=function(){__p+=__j.call(arguments,'');};\n" +
18954       source + 'return __p;\n';
18955
18956     try {
18957       var render = new Function(settings.variable || 'obj', '_', source);
18958     } catch (e) {
18959       e.source = source;
18960       throw e;
18961     }
18962
18963     var template = function(data) {
18964       return render.call(this, data, _);
18965     };
18966
18967     // Provide the compiled source as a convenience for precompilation.
18968     var argument = settings.variable || 'obj';
18969     template.source = 'function(' + argument + '){\n' + source + '}';
18970
18971     return template;
18972   };
18973
18974   // Add a "chain" function. Start chaining a wrapped Underscore object.
18975   _.chain = function(obj) {
18976     var instance = _(obj);
18977     instance._chain = true;
18978     return instance;
18979   };
18980
18981   // OOP
18982   // ---------------
18983   // If Underscore is called as a function, it returns a wrapped object that
18984   // can be used OO-style. This wrapper holds altered versions of all the
18985   // underscore functions. Wrapped objects may be chained.
18986
18987   // Helper function to continue chaining intermediate results.
18988   var result = function(instance, obj) {
18989     return instance._chain ? _(obj).chain() : obj;
18990   };
18991
18992   // Add your own custom functions to the Underscore object.
18993   _.mixin = function(obj) {
18994     _.each(_.functions(obj), function(name) {
18995       var func = _[name] = obj[name];
18996       _.prototype[name] = function() {
18997         var args = [this._wrapped];
18998         push.apply(args, arguments);
18999         return result(this, func.apply(_, args));
19000       };
19001     });
19002   };
19003
19004   // Add all of the Underscore functions to the wrapper object.
19005   _.mixin(_);
19006
19007   // Add all mutator Array functions to the wrapper.
19008   _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
19009     var method = ArrayProto[name];
19010     _.prototype[name] = function() {
19011       var obj = this._wrapped;
19012       method.apply(obj, arguments);
19013       if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
19014       return result(this, obj);
19015     };
19016   });
19017
19018   // Add all accessor Array functions to the wrapper.
19019   _.each(['concat', 'join', 'slice'], function(name) {
19020     var method = ArrayProto[name];
19021     _.prototype[name] = function() {
19022       return result(this, method.apply(this._wrapped, arguments));
19023     };
19024   });
19025
19026   // Extracts the result from a wrapped and chained object.
19027   _.prototype.value = function() {
19028     return this._wrapped;
19029   };
19030
19031   // Provide unwrapping proxy for some methods used in engine operations
19032   // such as arithmetic and JSON stringification.
19033   _.prototype.valueOf = _.prototype.toJSON = _.prototype.value;
19034
19035   _.prototype.toString = function() {
19036     return '' + this._wrapped;
19037   };
19038
19039   // AMD registration happens at the end for compatibility with AMD loaders
19040   // that may not enforce next-turn semantics on modules. Even though general
19041   // practice for AMD registration is to be anonymous, underscore registers
19042   // as a named module because, like jQuery, it is a base library that is
19043   // popular enough to be bundled in a third party lib, but not be part of
19044   // an AMD load request. Those cases could generate an error when an
19045   // anonymous define() is called outside of a loader request.
19046   if (typeof define === 'function' && define.amd) {
19047     define('underscore', [], function() {
19048       return _;
19049     });
19050   }
19051 }.call(this));
19052
19053 },{}],244:[function(require,module,exports){
19054 var createElement = require("./vdom/create-element.js")
19055
19056 module.exports = createElement
19057
19058 },{"./vdom/create-element.js":250}],245:[function(require,module,exports){
19059 var diff = require("./vtree/diff.js")
19060
19061 module.exports = diff
19062
19063 },{"./vtree/diff.js":270}],246:[function(require,module,exports){
19064 var h = require("./virtual-hyperscript/index.js")
19065
19066 module.exports = h
19067
19068 },{"./virtual-hyperscript/index.js":257}],247:[function(require,module,exports){
19069 var diff = require("./diff.js")
19070 var patch = require("./patch.js")
19071 var h = require("./h.js")
19072 var create = require("./create-element.js")
19073 var VNode = require('./vnode/vnode.js')
19074 var VText = require('./vnode/vtext.js')
19075
19076 module.exports = {
19077     diff: diff,
19078     patch: patch,
19079     h: h,
19080     create: create,
19081     VNode: VNode,
19082     VText: VText
19083 }
19084
19085 },{"./create-element.js":244,"./diff.js":245,"./h.js":246,"./patch.js":248,"./vnode/vnode.js":266,"./vnode/vtext.js":268}],248:[function(require,module,exports){
19086 var patch = require("./vdom/patch.js")
19087
19088 module.exports = patch
19089
19090 },{"./vdom/patch.js":253}],249:[function(require,module,exports){
19091 var isObject = require("is-object")
19092 var isHook = require("../vnode/is-vhook.js")
19093
19094 module.exports = applyProperties
19095
19096 function applyProperties(node, props, previous) {
19097     for (var propName in props) {
19098         var propValue = props[propName]
19099
19100         if (propValue === undefined) {
19101             removeProperty(node, propName, propValue, previous);
19102         } else if (isHook(propValue)) {
19103             removeProperty(node, propName, propValue, previous)
19104             if (propValue.hook) {
19105                 propValue.hook(node,
19106                     propName,
19107                     previous ? previous[propName] : undefined)
19108             }
19109         } else {
19110             if (isObject(propValue)) {
19111                 patchObject(node, props, previous, propName, propValue);
19112             } else {
19113                 node[propName] = propValue
19114             }
19115         }
19116     }
19117 }
19118
19119 function removeProperty(node, propName, propValue, previous) {
19120     if (previous) {
19121         var previousValue = previous[propName]
19122
19123         if (!isHook(previousValue)) {
19124             if (propName === "attributes") {
19125                 for (var attrName in previousValue) {
19126                     node.removeAttribute(attrName)
19127                 }
19128             } else if (propName === "style") {
19129                 for (var i in previousValue) {
19130                     node.style[i] = ""
19131                 }
19132             } else if (typeof previousValue === "string") {
19133                 node[propName] = ""
19134             } else {
19135                 node[propName] = null
19136             }
19137         } else if (previousValue.unhook) {
19138             previousValue.unhook(node, propName, propValue)
19139         }
19140     }
19141 }
19142
19143 function patchObject(node, props, previous, propName, propValue) {
19144     var previousValue = previous ? previous[propName] : undefined
19145
19146     // Set attributes
19147     if (propName === "attributes") {
19148         for (var attrName in propValue) {
19149             var attrValue = propValue[attrName]
19150
19151             if (attrValue === undefined) {
19152                 node.removeAttribute(attrName)
19153             } else {
19154                 node.setAttribute(attrName, attrValue)
19155             }
19156         }
19157
19158         return
19159     }
19160
19161     if(previousValue && isObject(previousValue) &&
19162         getPrototype(previousValue) !== getPrototype(propValue)) {
19163         node[propName] = propValue
19164         return
19165     }
19166
19167     if (!isObject(node[propName])) {
19168         node[propName] = {}
19169     }
19170
19171     var replacer = propName === "style" ? "" : undefined
19172
19173     for (var k in propValue) {
19174         var value = propValue[k]
19175         node[propName][k] = (value === undefined) ? replacer : value
19176     }
19177 }
19178
19179 function getPrototype(value) {
19180     if (Object.getPrototypeOf) {
19181         return Object.getPrototypeOf(value)
19182     } else if (value.__proto__) {
19183         return value.__proto__
19184     } else if (value.constructor) {
19185         return value.constructor.prototype
19186     }
19187 }
19188
19189 },{"../vnode/is-vhook.js":261,"is-object":20}],250:[function(require,module,exports){
19190 var document = require("global/document")
19191
19192 var applyProperties = require("./apply-properties")
19193
19194 var isVNode = require("../vnode/is-vnode.js")
19195 var isVText = require("../vnode/is-vtext.js")
19196 var isWidget = require("../vnode/is-widget.js")
19197 var handleThunk = require("../vnode/handle-thunk.js")
19198
19199 module.exports = createElement
19200
19201 function createElement(vnode, opts) {
19202     var doc = opts ? opts.document || document : document
19203     var warn = opts ? opts.warn : null
19204
19205     vnode = handleThunk(vnode).a
19206
19207     if (isWidget(vnode)) {
19208         return vnode.init()
19209     } else if (isVText(vnode)) {
19210         return doc.createTextNode(vnode.text)
19211     } else if (!isVNode(vnode)) {
19212         if (warn) {
19213             warn("Item is not a valid virtual dom node", vnode)
19214         }
19215         return null
19216     }
19217
19218     var node = (vnode.namespace === null) ?
19219         doc.createElement(vnode.tagName) :
19220         doc.createElementNS(vnode.namespace, vnode.tagName)
19221
19222     var props = vnode.properties
19223     applyProperties(node, props)
19224
19225     var children = vnode.children
19226
19227     for (var i = 0; i < children.length; i++) {
19228         var childNode = createElement(children[i], opts)
19229         if (childNode) {
19230             node.appendChild(childNode)
19231         }
19232     }
19233
19234     return node
19235 }
19236
19237 },{"../vnode/handle-thunk.js":259,"../vnode/is-vnode.js":262,"../vnode/is-vtext.js":263,"../vnode/is-widget.js":264,"./apply-properties":249,"global/document":16}],251:[function(require,module,exports){
19238 // Maps a virtual DOM tree onto a real DOM tree in an efficient manner.
19239 // We don't want to read all of the DOM nodes in the tree so we use
19240 // the in-order tree indexing to eliminate recursion down certain branches.
19241 // We only recurse into a DOM node if we know that it contains a child of
19242 // interest.
19243
19244 var noChild = {}
19245
19246 module.exports = domIndex
19247
19248 function domIndex(rootNode, tree, indices, nodes) {
19249     if (!indices || indices.length === 0) {
19250         return {}
19251     } else {
19252         indices.sort(ascending)
19253         return recurse(rootNode, tree, indices, nodes, 0)
19254     }
19255 }
19256
19257 function recurse(rootNode, tree, indices, nodes, rootIndex) {
19258     nodes = nodes || {}
19259
19260
19261     if (rootNode) {
19262         if (indexInRange(indices, rootIndex, rootIndex)) {
19263             nodes[rootIndex] = rootNode
19264         }
19265
19266         var vChildren = tree.children
19267
19268         if (vChildren) {
19269
19270             var childNodes = rootNode.childNodes
19271
19272             for (var i = 0; i < tree.children.length; i++) {
19273                 rootIndex += 1
19274
19275                 var vChild = vChildren[i] || noChild
19276                 var nextIndex = rootIndex + (vChild.count || 0)
19277
19278                 // skip recursion down the tree if there are no nodes down here
19279                 if (indexInRange(indices, rootIndex, nextIndex)) {
19280                     recurse(childNodes[i], vChild, indices, nodes, rootIndex)
19281                 }
19282
19283                 rootIndex = nextIndex
19284             }
19285         }
19286     }
19287
19288     return nodes
19289 }
19290
19291 // Binary search for an index in the interval [left, right]
19292 function indexInRange(indices, left, right) {
19293     if (indices.length === 0) {
19294         return false
19295     }
19296
19297     var minIndex = 0
19298     var maxIndex = indices.length - 1
19299     var currentIndex
19300     var currentItem
19301
19302     while (minIndex <= maxIndex) {
19303         currentIndex = ((maxIndex + minIndex) / 2) >> 0
19304         currentItem = indices[currentIndex]
19305
19306         if (minIndex === maxIndex) {
19307             return currentItem >= left && currentItem <= right
19308         } else if (currentItem < left) {
19309             minIndex = currentIndex + 1
19310         } else  if (currentItem > right) {
19311             maxIndex = currentIndex - 1
19312         } else {
19313             return true
19314         }
19315     }
19316
19317     return false;
19318 }
19319
19320 function ascending(a, b) {
19321     return a > b ? 1 : -1
19322 }
19323
19324 },{}],252:[function(require,module,exports){
19325 var applyProperties = require("./apply-properties")
19326
19327 var isWidget = require("../vnode/is-widget.js")
19328 var VPatch = require("../vnode/vpatch.js")
19329
19330 var updateWidget = require("./update-widget")
19331
19332 module.exports = applyPatch
19333
19334 function applyPatch(vpatch, domNode, renderOptions) {
19335     var type = vpatch.type
19336     var vNode = vpatch.vNode
19337     var patch = vpatch.patch
19338
19339     switch (type) {
19340         case VPatch.REMOVE:
19341             return removeNode(domNode, vNode)
19342         case VPatch.INSERT:
19343             return insertNode(domNode, patch, renderOptions)
19344         case VPatch.VTEXT:
19345             return stringPatch(domNode, vNode, patch, renderOptions)
19346         case VPatch.WIDGET:
19347             return widgetPatch(domNode, vNode, patch, renderOptions)
19348         case VPatch.VNODE:
19349             return vNodePatch(domNode, vNode, patch, renderOptions)
19350         case VPatch.ORDER:
19351             reorderChildren(domNode, patch)
19352             return domNode
19353         case VPatch.PROPS:
19354             applyProperties(domNode, patch, vNode.properties)
19355             return domNode
19356         case VPatch.THUNK:
19357             return replaceRoot(domNode,
19358                 renderOptions.patch(domNode, patch, renderOptions))
19359         default:
19360             return domNode
19361     }
19362 }
19363
19364 function removeNode(domNode, vNode) {
19365     var parentNode = domNode.parentNode
19366
19367     if (parentNode) {
19368         parentNode.removeChild(domNode)
19369     }
19370
19371     destroyWidget(domNode, vNode);
19372
19373     return null
19374 }
19375
19376 function insertNode(parentNode, vNode, renderOptions) {
19377     var newNode = renderOptions.render(vNode, renderOptions)
19378
19379     if (parentNode) {
19380         parentNode.appendChild(newNode)
19381     }
19382
19383     return parentNode
19384 }
19385
19386 function stringPatch(domNode, leftVNode, vText, renderOptions) {
19387     var newNode
19388
19389     if (domNode.nodeType === 3) {
19390         domNode.replaceData(0, domNode.length, vText.text)
19391         newNode = domNode
19392     } else {
19393         var parentNode = domNode.parentNode
19394         newNode = renderOptions.render(vText, renderOptions)
19395
19396         if (parentNode && newNode !== domNode) {
19397             parentNode.replaceChild(newNode, domNode)
19398         }
19399     }
19400
19401     return newNode
19402 }
19403
19404 function widgetPatch(domNode, leftVNode, widget, renderOptions) {
19405     var updating = updateWidget(leftVNode, widget)
19406     var newNode
19407
19408     if (updating) {
19409         newNode = widget.update(leftVNode, domNode) || domNode
19410     } else {
19411         newNode = renderOptions.render(widget, renderOptions)
19412     }
19413
19414     var parentNode = domNode.parentNode
19415
19416     if (parentNode && newNode !== domNode) {
19417         parentNode.replaceChild(newNode, domNode)
19418     }
19419
19420     if (!updating) {
19421         destroyWidget(domNode, leftVNode)
19422     }
19423
19424     return newNode
19425 }
19426
19427 function vNodePatch(domNode, leftVNode, vNode, renderOptions) {
19428     var parentNode = domNode.parentNode
19429     var newNode = renderOptions.render(vNode, renderOptions)
19430
19431     if (parentNode && newNode !== domNode) {
19432         parentNode.replaceChild(newNode, domNode)
19433     }
19434
19435     return newNode
19436 }
19437
19438 function destroyWidget(domNode, w) {
19439     if (typeof w.destroy === "function" && isWidget(w)) {
19440         w.destroy(domNode)
19441     }
19442 }
19443
19444 function reorderChildren(domNode, moves) {
19445     var childNodes = domNode.childNodes
19446     var keyMap = {}
19447     var node
19448     var remove
19449     var insert
19450
19451     for (var i = 0; i < moves.removes.length; i++) {
19452         remove = moves.removes[i]
19453         node = childNodes[remove.from]
19454         if (remove.key) {
19455             keyMap[remove.key] = node
19456         }
19457         domNode.removeChild(node)
19458     }
19459
19460     var length = childNodes.length
19461     for (var j = 0; j < moves.inserts.length; j++) {
19462         insert = moves.inserts[j]
19463         node = keyMap[insert.key]
19464         // this is the weirdest bug i've ever seen in webkit
19465         domNode.insertBefore(node, insert.to >= length++ ? null : childNodes[insert.to])
19466     }
19467 }
19468
19469 function replaceRoot(oldRoot, newRoot) {
19470     if (oldRoot && newRoot && oldRoot !== newRoot && oldRoot.parentNode) {
19471         oldRoot.parentNode.replaceChild(newRoot, oldRoot)
19472     }
19473
19474     return newRoot;
19475 }
19476
19477 },{"../vnode/is-widget.js":264,"../vnode/vpatch.js":267,"./apply-properties":249,"./update-widget":254}],253:[function(require,module,exports){
19478 var document = require("global/document")
19479 var isArray = require("x-is-array")
19480
19481 var render = require("./create-element")
19482 var domIndex = require("./dom-index")
19483 var patchOp = require("./patch-op")
19484 module.exports = patch
19485
19486 function patch(rootNode, patches, renderOptions) {
19487     renderOptions = renderOptions || {}
19488     renderOptions.patch = renderOptions.patch && renderOptions.patch !== patch
19489         ? renderOptions.patch
19490         : patchRecursive
19491     renderOptions.render = renderOptions.render || render
19492
19493     return renderOptions.patch(rootNode, patches, renderOptions)
19494 }
19495
19496 function patchRecursive(rootNode, patches, renderOptions) {
19497     var indices = patchIndices(patches)
19498
19499     if (indices.length === 0) {
19500         return rootNode
19501     }
19502
19503     var index = domIndex(rootNode, patches.a, indices)
19504     var ownerDocument = rootNode.ownerDocument
19505
19506     if (!renderOptions.document && ownerDocument !== document) {
19507         renderOptions.document = ownerDocument
19508     }
19509
19510     for (var i = 0; i < indices.length; i++) {
19511         var nodeIndex = indices[i]
19512         rootNode = applyPatch(rootNode,
19513             index[nodeIndex],
19514             patches[nodeIndex],
19515             renderOptions)
19516     }
19517
19518     return rootNode
19519 }
19520
19521 function applyPatch(rootNode, domNode, patchList, renderOptions) {
19522     if (!domNode) {
19523         return rootNode
19524     }
19525
19526     var newNode
19527
19528     if (isArray(patchList)) {
19529         for (var i = 0; i < patchList.length; i++) {
19530             newNode = patchOp(patchList[i], domNode, renderOptions)
19531
19532             if (domNode === rootNode) {
19533                 rootNode = newNode
19534             }
19535         }
19536     } else {
19537         newNode = patchOp(patchList, domNode, renderOptions)
19538
19539         if (domNode === rootNode) {
19540             rootNode = newNode
19541         }
19542     }
19543
19544     return rootNode
19545 }
19546
19547 function patchIndices(patches) {
19548     var indices = []
19549
19550     for (var key in patches) {
19551         if (key !== "a") {
19552             indices.push(Number(key))
19553         }
19554     }
19555
19556     return indices
19557 }
19558
19559 },{"./create-element":250,"./dom-index":251,"./patch-op":252,"global/document":16,"x-is-array":289}],254:[function(require,module,exports){
19560 var isWidget = require("../vnode/is-widget.js")
19561
19562 module.exports = updateWidget
19563
19564 function updateWidget(a, b) {
19565     if (isWidget(a) && isWidget(b)) {
19566         if ("name" in a && "name" in b) {
19567             return a.id === b.id
19568         } else {
19569             return a.init === b.init
19570         }
19571     }
19572
19573     return false
19574 }
19575
19576 },{"../vnode/is-widget.js":264}],255:[function(require,module,exports){
19577 'use strict';
19578
19579 var EvStore = require('ev-store');
19580
19581 module.exports = EvHook;
19582
19583 function EvHook(value) {
19584     if (!(this instanceof EvHook)) {
19585         return new EvHook(value);
19586     }
19587
19588     this.value = value;
19589 }
19590
19591 EvHook.prototype.hook = function (node, propertyName) {
19592     var es = EvStore(node);
19593     var propName = propertyName.substr(3);
19594
19595     es[propName] = this.value;
19596 };
19597
19598 EvHook.prototype.unhook = function(node, propertyName) {
19599     var es = EvStore(node);
19600     var propName = propertyName.substr(3);
19601
19602     es[propName] = undefined;
19603 };
19604
19605 },{"ev-store":9}],256:[function(require,module,exports){
19606 'use strict';
19607
19608 module.exports = SoftSetHook;
19609
19610 function SoftSetHook(value) {
19611     if (!(this instanceof SoftSetHook)) {
19612         return new SoftSetHook(value);
19613     }
19614
19615     this.value = value;
19616 }
19617
19618 SoftSetHook.prototype.hook = function (node, propertyName) {
19619     if (node[propertyName] !== this.value) {
19620         node[propertyName] = this.value;
19621     }
19622 };
19623
19624 },{}],257:[function(require,module,exports){
19625 'use strict';
19626
19627 var isArray = require('x-is-array');
19628
19629 var VNode = require('../vnode/vnode.js');
19630 var VText = require('../vnode/vtext.js');
19631 var isVNode = require('../vnode/is-vnode');
19632 var isVText = require('../vnode/is-vtext');
19633 var isWidget = require('../vnode/is-widget');
19634 var isHook = require('../vnode/is-vhook');
19635 var isVThunk = require('../vnode/is-thunk');
19636
19637 var parseTag = require('./parse-tag.js');
19638 var softSetHook = require('./hooks/soft-set-hook.js');
19639 var evHook = require('./hooks/ev-hook.js');
19640
19641 module.exports = h;
19642
19643 function h(tagName, properties, children) {
19644     var childNodes = [];
19645     var tag, props, key, namespace;
19646
19647     if (!children && isChildren(properties)) {
19648         children = properties;
19649         props = {};
19650     }
19651
19652     props = props || properties || {};
19653     tag = parseTag(tagName, props);
19654
19655     // support keys
19656     if (props.hasOwnProperty('key')) {
19657         key = props.key;
19658         props.key = undefined;
19659     }
19660
19661     // support namespace
19662     if (props.hasOwnProperty('namespace')) {
19663         namespace = props.namespace;
19664         props.namespace = undefined;
19665     }
19666
19667     // fix cursor bug
19668     if (tag === 'INPUT' &&
19669         !namespace &&
19670         props.hasOwnProperty('value') &&
19671         props.value !== undefined &&
19672         !isHook(props.value)
19673     ) {
19674         props.value = softSetHook(props.value);
19675     }
19676
19677     transformProperties(props);
19678
19679     if (children !== undefined && children !== null) {
19680         addChild(children, childNodes, tag, props);
19681     }
19682
19683
19684     return new VNode(tag, props, childNodes, key, namespace);
19685 }
19686
19687 function addChild(c, childNodes, tag, props) {
19688     if (typeof c === 'string') {
19689         childNodes.push(new VText(c));
19690     } else if (typeof c === 'number') {
19691         childNodes.push(new VText(String(c)));
19692     } else if (isChild(c)) {
19693         childNodes.push(c);
19694     } else if (isArray(c)) {
19695         for (var i = 0; i < c.length; i++) {
19696             addChild(c[i], childNodes, tag, props);
19697         }
19698     } else if (c === null || c === undefined) {
19699         return;
19700     } else {
19701         throw UnexpectedVirtualElement({
19702             foreignObject: c,
19703             parentVnode: {
19704                 tagName: tag,
19705                 properties: props
19706             }
19707         });
19708     }
19709 }
19710
19711 function transformProperties(props) {
19712     for (var propName in props) {
19713         if (props.hasOwnProperty(propName)) {
19714             var value = props[propName];
19715
19716             if (isHook(value)) {
19717                 continue;
19718             }
19719
19720             if (propName.substr(0, 3) === 'ev-') {
19721                 // add ev-foo support
19722                 props[propName] = evHook(value);
19723             }
19724         }
19725     }
19726 }
19727
19728 function isChild(x) {
19729     return isVNode(x) || isVText(x) || isWidget(x) || isVThunk(x);
19730 }
19731
19732 function isChildren(x) {
19733     return typeof x === 'string' || isArray(x) || isChild(x);
19734 }
19735
19736 function UnexpectedVirtualElement(data) {
19737     var err = new Error();
19738
19739     err.type = 'virtual-hyperscript.unexpected.virtual-element';
19740     err.message = 'Unexpected virtual child passed to h().\n' +
19741         'Expected a VNode / Vthunk / VWidget / string but:\n' +
19742         'got:\n' +
19743         errorString(data.foreignObject) +
19744         '.\n' +
19745         'The parent vnode is:\n' +
19746         errorString(data.parentVnode)
19747         '\n' +
19748         'Suggested fix: change your `h(..., [ ... ])` callsite.';
19749     err.foreignObject = data.foreignObject;
19750     err.parentVnode = data.parentVnode;
19751
19752     return err;
19753 }
19754
19755 function errorString(obj) {
19756     try {
19757         return JSON.stringify(obj, null, '    ');
19758     } catch (e) {
19759         return String(obj);
19760     }
19761 }
19762
19763 },{"../vnode/is-thunk":260,"../vnode/is-vhook":261,"../vnode/is-vnode":262,"../vnode/is-vtext":263,"../vnode/is-widget":264,"../vnode/vnode.js":266,"../vnode/vtext.js":268,"./hooks/ev-hook.js":255,"./hooks/soft-set-hook.js":256,"./parse-tag.js":258,"x-is-array":289}],258:[function(require,module,exports){
19764 'use strict';
19765
19766 var split = require('browser-split');
19767
19768 var classIdSplit = /([\.#]?[a-zA-Z0-9\u007F-\uFFFF_:-]+)/;
19769 var notClassId = /^\.|#/;
19770
19771 module.exports = parseTag;
19772
19773 function parseTag(tag, props) {
19774     if (!tag) {
19775         return 'DIV';
19776     }
19777
19778     var noId = !(props.hasOwnProperty('id'));
19779
19780     var tagParts = split(tag, classIdSplit);
19781     var tagName = null;
19782
19783     if (notClassId.test(tagParts[1])) {
19784         tagName = 'DIV';
19785     }
19786
19787     var classes, part, type, i;
19788
19789     for (i = 0; i < tagParts.length; i++) {
19790         part = tagParts[i];
19791
19792         if (!part) {
19793             continue;
19794         }
19795
19796         type = part.charAt(0);
19797
19798         if (!tagName) {
19799             tagName = part;
19800         } else if (type === '.') {
19801             classes = classes || [];
19802             classes.push(part.substring(1, part.length));
19803         } else if (type === '#' && noId) {
19804             props.id = part.substring(1, part.length);
19805         }
19806     }
19807
19808     if (classes) {
19809         if (props.className) {
19810             classes.push(props.className);
19811         }
19812
19813         props.className = classes.join(' ');
19814     }
19815
19816     return props.namespace ? tagName : tagName.toUpperCase();
19817 }
19818
19819 },{"browser-split":5}],259:[function(require,module,exports){
19820 var isVNode = require("./is-vnode")
19821 var isVText = require("./is-vtext")
19822 var isWidget = require("./is-widget")
19823 var isThunk = require("./is-thunk")
19824
19825 module.exports = handleThunk
19826
19827 function handleThunk(a, b) {
19828     var renderedA = a
19829     var renderedB = b
19830
19831     if (isThunk(b)) {
19832         renderedB = renderThunk(b, a)
19833     }
19834
19835     if (isThunk(a)) {
19836         renderedA = renderThunk(a, null)
19837     }
19838
19839     return {
19840         a: renderedA,
19841         b: renderedB
19842     }
19843 }
19844
19845 function renderThunk(thunk, previous) {
19846     var renderedThunk = thunk.vnode
19847
19848     if (!renderedThunk) {
19849         renderedThunk = thunk.vnode = thunk.render(previous)
19850     }
19851
19852     if (!(isVNode(renderedThunk) ||
19853             isVText(renderedThunk) ||
19854             isWidget(renderedThunk))) {
19855         throw new Error("thunk did not return a valid node");
19856     }
19857
19858     return renderedThunk
19859 }
19860
19861 },{"./is-thunk":260,"./is-vnode":262,"./is-vtext":263,"./is-widget":264}],260:[function(require,module,exports){
19862 module.exports = isThunk
19863
19864 function isThunk(t) {
19865     return t && t.type === "Thunk"
19866 }
19867
19868 },{}],261:[function(require,module,exports){
19869 module.exports = isHook
19870
19871 function isHook(hook) {
19872     return hook &&
19873       (typeof hook.hook === "function" && !hook.hasOwnProperty("hook") ||
19874        typeof hook.unhook === "function" && !hook.hasOwnProperty("unhook"))
19875 }
19876
19877 },{}],262:[function(require,module,exports){
19878 var version = require("./version")
19879
19880 module.exports = isVirtualNode
19881
19882 function isVirtualNode(x) {
19883     return x && x.type === "VirtualNode" && x.version === version
19884 }
19885
19886 },{"./version":265}],263:[function(require,module,exports){
19887 var version = require("./version")
19888
19889 module.exports = isVirtualText
19890
19891 function isVirtualText(x) {
19892     return x && x.type === "VirtualText" && x.version === version
19893 }
19894
19895 },{"./version":265}],264:[function(require,module,exports){
19896 module.exports = isWidget
19897
19898 function isWidget(w) {
19899     return w && w.type === "Widget"
19900 }
19901
19902 },{}],265:[function(require,module,exports){
19903 module.exports = "2"
19904
19905 },{}],266:[function(require,module,exports){
19906 var version = require("./version")
19907 var isVNode = require("./is-vnode")
19908 var isWidget = require("./is-widget")
19909 var isThunk = require("./is-thunk")
19910 var isVHook = require("./is-vhook")
19911
19912 module.exports = VirtualNode
19913
19914 var noProperties = {}
19915 var noChildren = []
19916
19917 function VirtualNode(tagName, properties, children, key, namespace) {
19918     this.tagName = tagName
19919     this.properties = properties || noProperties
19920     this.children = children || noChildren
19921     this.key = key != null ? String(key) : undefined
19922     this.namespace = (typeof namespace === "string") ? namespace : null
19923
19924     var count = (children && children.length) || 0
19925     var descendants = 0
19926     var hasWidgets = false
19927     var hasThunks = false
19928     var descendantHooks = false
19929     var hooks
19930
19931     for (var propName in properties) {
19932         if (properties.hasOwnProperty(propName)) {
19933             var property = properties[propName]
19934             if (isVHook(property) && property.unhook) {
19935                 if (!hooks) {
19936                     hooks = {}
19937                 }
19938
19939                 hooks[propName] = property
19940             }
19941         }
19942     }
19943
19944     for (var i = 0; i < count; i++) {
19945         var child = children[i]
19946         if (isVNode(child)) {
19947             descendants += child.count || 0
19948
19949             if (!hasWidgets && child.hasWidgets) {
19950                 hasWidgets = true
19951             }
19952
19953             if (!hasThunks && child.hasThunks) {
19954                 hasThunks = true
19955             }
19956
19957             if (!descendantHooks && (child.hooks || child.descendantHooks)) {
19958                 descendantHooks = true
19959             }
19960         } else if (!hasWidgets && isWidget(child)) {
19961             if (typeof child.destroy === "function") {
19962                 hasWidgets = true
19963             }
19964         } else if (!hasThunks && isThunk(child)) {
19965             hasThunks = true;
19966         }
19967     }
19968
19969     this.count = count + descendants
19970     this.hasWidgets = hasWidgets
19971     this.hasThunks = hasThunks
19972     this.hooks = hooks
19973     this.descendantHooks = descendantHooks
19974 }
19975
19976 VirtualNode.prototype.version = version
19977 VirtualNode.prototype.type = "VirtualNode"
19978
19979 },{"./is-thunk":260,"./is-vhook":261,"./is-vnode":262,"./is-widget":264,"./version":265}],267:[function(require,module,exports){
19980 var version = require("./version")
19981
19982 VirtualPatch.NONE = 0
19983 VirtualPatch.VTEXT = 1
19984 VirtualPatch.VNODE = 2
19985 VirtualPatch.WIDGET = 3
19986 VirtualPatch.PROPS = 4
19987 VirtualPatch.ORDER = 5
19988 VirtualPatch.INSERT = 6
19989 VirtualPatch.REMOVE = 7
19990 VirtualPatch.THUNK = 8
19991
19992 module.exports = VirtualPatch
19993
19994 function VirtualPatch(type, vNode, patch) {
19995     this.type = Number(type)
19996     this.vNode = vNode
19997     this.patch = patch
19998 }
19999
20000 VirtualPatch.prototype.version = version
20001 VirtualPatch.prototype.type = "VirtualPatch"
20002
20003 },{"./version":265}],268:[function(require,module,exports){
20004 var version = require("./version")
20005
20006 module.exports = VirtualText
20007
20008 function VirtualText(text) {
20009     this.text = String(text)
20010 }
20011
20012 VirtualText.prototype.version = version
20013 VirtualText.prototype.type = "VirtualText"
20014
20015 },{"./version":265}],269:[function(require,module,exports){
20016 var isObject = require("is-object")
20017 var isHook = require("../vnode/is-vhook")
20018
20019 module.exports = diffProps
20020
20021 function diffProps(a, b) {
20022     var diff
20023
20024     for (var aKey in a) {
20025         if (!(aKey in b)) {
20026             diff = diff || {}
20027             diff[aKey] = undefined
20028         }
20029
20030         var aValue = a[aKey]
20031         var bValue = b[aKey]
20032
20033         if (aValue === bValue) {
20034             continue
20035         } else if (isObject(aValue) && isObject(bValue)) {
20036             if (getPrototype(bValue) !== getPrototype(aValue)) {
20037                 diff = diff || {}
20038                 diff[aKey] = bValue
20039             } else if (isHook(bValue)) {
20040                  diff = diff || {}
20041                  diff[aKey] = bValue
20042             } else {
20043                 var objectDiff = diffProps(aValue, bValue)
20044                 if (objectDiff) {
20045                     diff = diff || {}
20046                     diff[aKey] = objectDiff
20047                 }
20048             }
20049         } else {
20050             diff = diff || {}
20051             diff[aKey] = bValue
20052         }
20053     }
20054
20055     for (var bKey in b) {
20056         if (!(bKey in a)) {
20057             diff = diff || {}
20058             diff[bKey] = b[bKey]
20059         }
20060     }
20061
20062     return diff
20063 }
20064
20065 function getPrototype(value) {
20066   if (Object.getPrototypeOf) {
20067     return Object.getPrototypeOf(value)
20068   } else if (value.__proto__) {
20069     return value.__proto__
20070   } else if (value.constructor) {
20071     return value.constructor.prototype
20072   }
20073 }
20074
20075 },{"../vnode/is-vhook":261,"is-object":20}],270:[function(require,module,exports){
20076 var isArray = require("x-is-array")
20077
20078 var VPatch = require("../vnode/vpatch")
20079 var isVNode = require("../vnode/is-vnode")
20080 var isVText = require("../vnode/is-vtext")
20081 var isWidget = require("../vnode/is-widget")
20082 var isThunk = require("../vnode/is-thunk")
20083 var handleThunk = require("../vnode/handle-thunk")
20084
20085 var diffProps = require("./diff-props")
20086
20087 module.exports = diff
20088
20089 function diff(a, b) {
20090     var patch = { a: a }
20091     walk(a, b, patch, 0)
20092     return patch
20093 }
20094
20095 function walk(a, b, patch, index) {
20096     if (a === b) {
20097         return
20098     }
20099
20100     var apply = patch[index]
20101     var applyClear = false
20102
20103     if (isThunk(a) || isThunk(b)) {
20104         thunks(a, b, patch, index)
20105     } else if (b == null) {
20106
20107         // If a is a widget we will add a remove patch for it
20108         // Otherwise any child widgets/hooks must be destroyed.
20109         // This prevents adding two remove patches for a widget.
20110         if (!isWidget(a)) {
20111             clearState(a, patch, index)
20112             apply = patch[index]
20113         }
20114
20115         apply = appendPatch(apply, new VPatch(VPatch.REMOVE, a, b))
20116     } else if (isVNode(b)) {
20117         if (isVNode(a)) {
20118             if (a.tagName === b.tagName &&
20119                 a.namespace === b.namespace &&
20120                 a.key === b.key) {
20121                 var propsPatch = diffProps(a.properties, b.properties)
20122                 if (propsPatch) {
20123                     apply = appendPatch(apply,
20124                         new VPatch(VPatch.PROPS, a, propsPatch))
20125                 }
20126                 apply = diffChildren(a, b, patch, apply, index)
20127             } else {
20128                 apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
20129                 applyClear = true
20130             }
20131         } else {
20132             apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
20133             applyClear = true
20134         }
20135     } else if (isVText(b)) {
20136         if (!isVText(a)) {
20137             apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
20138             applyClear = true
20139         } else if (a.text !== b.text) {
20140             apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
20141         }
20142     } else if (isWidget(b)) {
20143         if (!isWidget(a)) {
20144             applyClear = true
20145         }
20146
20147         apply = appendPatch(apply, new VPatch(VPatch.WIDGET, a, b))
20148     }
20149
20150     if (apply) {
20151         patch[index] = apply
20152     }
20153
20154     if (applyClear) {
20155         clearState(a, patch, index)
20156     }
20157 }
20158
20159 function diffChildren(a, b, patch, apply, index) {
20160     var aChildren = a.children
20161     var orderedSet = reorder(aChildren, b.children)
20162     var bChildren = orderedSet.children
20163
20164     var aLen = aChildren.length
20165     var bLen = bChildren.length
20166     var len = aLen > bLen ? aLen : bLen
20167
20168     for (var i = 0; i < len; i++) {
20169         var leftNode = aChildren[i]
20170         var rightNode = bChildren[i]
20171         index += 1
20172
20173         if (!leftNode) {
20174             if (rightNode) {
20175                 // Excess nodes in b need to be added
20176                 apply = appendPatch(apply,
20177                     new VPatch(VPatch.INSERT, null, rightNode))
20178             }
20179         } else {
20180             walk(leftNode, rightNode, patch, index)
20181         }
20182
20183         if (isVNode(leftNode) && leftNode.count) {
20184             index += leftNode.count
20185         }
20186     }
20187
20188     if (orderedSet.moves) {
20189         // Reorder nodes last
20190         apply = appendPatch(apply, new VPatch(
20191             VPatch.ORDER,
20192             a,
20193             orderedSet.moves
20194         ))
20195     }
20196
20197     return apply
20198 }
20199
20200 function clearState(vNode, patch, index) {
20201     // TODO: Make this a single walk, not two
20202     unhook(vNode, patch, index)
20203     destroyWidgets(vNode, patch, index)
20204 }
20205
20206 // Patch records for all destroyed widgets must be added because we need
20207 // a DOM node reference for the destroy function
20208 function destroyWidgets(vNode, patch, index) {
20209     if (isWidget(vNode)) {
20210         if (typeof vNode.destroy === "function") {
20211             patch[index] = appendPatch(
20212                 patch[index],
20213                 new VPatch(VPatch.REMOVE, vNode, null)
20214             )
20215         }
20216     } else if (isVNode(vNode) && (vNode.hasWidgets || vNode.hasThunks)) {
20217         var children = vNode.children
20218         var len = children.length
20219         for (var i = 0; i < len; i++) {
20220             var child = children[i]
20221             index += 1
20222
20223             destroyWidgets(child, patch, index)
20224
20225             if (isVNode(child) && child.count) {
20226                 index += child.count
20227             }
20228         }
20229     } else if (isThunk(vNode)) {
20230         thunks(vNode, null, patch, index)
20231     }
20232 }
20233
20234 // Create a sub-patch for thunks
20235 function thunks(a, b, patch, index) {
20236     var nodes = handleThunk(a, b)
20237     var thunkPatch = diff(nodes.a, nodes.b)
20238     if (hasPatches(thunkPatch)) {
20239         patch[index] = new VPatch(VPatch.THUNK, null, thunkPatch)
20240     }
20241 }
20242
20243 function hasPatches(patch) {
20244     for (var index in patch) {
20245         if (index !== "a") {
20246             return true
20247         }
20248     }
20249
20250     return false
20251 }
20252
20253 // Execute hooks when two nodes are identical
20254 function unhook(vNode, patch, index) {
20255     if (isVNode(vNode)) {
20256         if (vNode.hooks) {
20257             patch[index] = appendPatch(
20258                 patch[index],
20259                 new VPatch(
20260                     VPatch.PROPS,
20261                     vNode,
20262                     undefinedKeys(vNode.hooks)
20263                 )
20264             )
20265         }
20266
20267         if (vNode.descendantHooks || vNode.hasThunks) {
20268             var children = vNode.children
20269             var len = children.length
20270             for (var i = 0; i < len; i++) {
20271                 var child = children[i]
20272                 index += 1
20273
20274                 unhook(child, patch, index)
20275
20276                 if (isVNode(child) && child.count) {
20277                     index += child.count
20278                 }
20279             }
20280         }
20281     } else if (isThunk(vNode)) {
20282         thunks(vNode, null, patch, index)
20283     }
20284 }
20285
20286 function undefinedKeys(obj) {
20287     var result = {}
20288
20289     for (var key in obj) {
20290         result[key] = undefined
20291     }
20292
20293     return result
20294 }
20295
20296 // List diff, naive left to right reordering
20297 function reorder(aChildren, bChildren) {
20298     // O(M) time, O(M) memory
20299     var bChildIndex = keyIndex(bChildren)
20300     var bKeys = bChildIndex.keys
20301     var bFree = bChildIndex.free
20302
20303     if (bFree.length === bChildren.length) {
20304         return {
20305             children: bChildren,
20306             moves: null
20307         }
20308     }
20309
20310     // O(N) time, O(N) memory
20311     var aChildIndex = keyIndex(aChildren)
20312     var aKeys = aChildIndex.keys
20313     var aFree = aChildIndex.free
20314
20315     if (aFree.length === aChildren.length) {
20316         return {
20317             children: bChildren,
20318             moves: null
20319         }
20320     }
20321
20322     // O(MAX(N, M)) memory
20323     var newChildren = []
20324
20325     var freeIndex = 0
20326     var freeCount = bFree.length
20327     var deletedItems = 0
20328
20329     // Iterate through a and match a node in b
20330     // O(N) time,
20331     for (var i = 0 ; i < aChildren.length; i++) {
20332         var aItem = aChildren[i]
20333         var itemIndex
20334
20335         if (aItem.key) {
20336             if (bKeys.hasOwnProperty(aItem.key)) {
20337                 // Match up the old keys
20338                 itemIndex = bKeys[aItem.key]
20339                 newChildren.push(bChildren[itemIndex])
20340
20341             } else {
20342                 // Remove old keyed items
20343                 itemIndex = i - deletedItems++
20344                 newChildren.push(null)
20345             }
20346         } else {
20347             // Match the item in a with the next free item in b
20348             if (freeIndex < freeCount) {
20349                 itemIndex = bFree[freeIndex++]
20350                 newChildren.push(bChildren[itemIndex])
20351             } else {
20352                 // There are no free items in b to match with
20353                 // the free items in a, so the extra free nodes
20354                 // are deleted.
20355                 itemIndex = i - deletedItems++
20356                 newChildren.push(null)
20357             }
20358         }
20359     }
20360
20361     var lastFreeIndex = freeIndex >= bFree.length ?
20362         bChildren.length :
20363         bFree[freeIndex]
20364
20365     // Iterate through b and append any new keys
20366     // O(M) time
20367     for (var j = 0; j < bChildren.length; j++) {
20368         var newItem = bChildren[j]
20369
20370         if (newItem.key) {
20371             if (!aKeys.hasOwnProperty(newItem.key)) {
20372                 // Add any new keyed items
20373                 // We are adding new items to the end and then sorting them
20374                 // in place. In future we should insert new items in place.
20375                 newChildren.push(newItem)
20376             }
20377         } else if (j >= lastFreeIndex) {
20378             // Add any leftover non-keyed items
20379             newChildren.push(newItem)
20380         }
20381     }
20382
20383     var simulate = newChildren.slice()
20384     var simulateIndex = 0
20385     var removes = []
20386     var inserts = []
20387     var simulateItem
20388
20389     for (var k = 0; k < bChildren.length;) {
20390         var wantedItem = bChildren[k]
20391         simulateItem = simulate[simulateIndex]
20392
20393         // remove items
20394         while (simulateItem === null && simulate.length) {
20395             removes.push(remove(simulate, simulateIndex, null))
20396             simulateItem = simulate[simulateIndex]
20397         }
20398
20399         if (!simulateItem || simulateItem.key !== wantedItem.key) {
20400             // if we need a key in this position...
20401             if (wantedItem.key) {
20402                 if (simulateItem && simulateItem.key) {
20403                     // if an insert doesn't put this key in place, it needs to move
20404                     if (bKeys[simulateItem.key] !== k + 1) {
20405                         removes.push(remove(simulate, simulateIndex, simulateItem.key))
20406                         simulateItem = simulate[simulateIndex]
20407                         // if the remove didn't put the wanted item in place, we need to insert it
20408                         if (!simulateItem || simulateItem.key !== wantedItem.key) {
20409                             inserts.push({key: wantedItem.key, to: k})
20410                         }
20411                         // items are matching, so skip ahead
20412                         else {
20413                             simulateIndex++
20414                         }
20415                     }
20416                     else {
20417                         inserts.push({key: wantedItem.key, to: k})
20418                     }
20419                 }
20420                 else {
20421                     inserts.push({key: wantedItem.key, to: k})
20422                 }
20423                 k++
20424             }
20425             // a key in simulate has no matching wanted key, remove it
20426             else if (simulateItem && simulateItem.key) {
20427                 removes.push(remove(simulate, simulateIndex, simulateItem.key))
20428             }
20429         }
20430         else {
20431             simulateIndex++
20432             k++
20433         }
20434     }
20435
20436     // remove all the remaining nodes from simulate
20437     while(simulateIndex < simulate.length) {
20438         simulateItem = simulate[simulateIndex]
20439         removes.push(remove(simulate, simulateIndex, simulateItem && simulateItem.key))
20440     }
20441
20442     // If the only moves we have are deletes then we can just
20443     // let the delete patch remove these items.
20444     if (removes.length === deletedItems && !inserts.length) {
20445         return {
20446             children: newChildren,
20447             moves: null
20448         }
20449     }
20450
20451     return {
20452         children: newChildren,
20453         moves: {
20454             removes: removes,
20455             inserts: inserts
20456         }
20457     }
20458 }
20459
20460 function remove(arr, index, key) {
20461     arr.splice(index, 1)
20462
20463     return {
20464         from: index,
20465         key: key
20466     }
20467 }
20468
20469 function keyIndex(children) {
20470     var keys = {}
20471     var free = []
20472     var length = children.length
20473
20474     for (var i = 0; i < length; i++) {
20475         var child = children[i]
20476
20477         if (child.key) {
20478             keys[child.key] = i
20479         } else {
20480             free.push(i)
20481         }
20482     }
20483
20484     return {
20485         keys: keys,     // A hash of key name to index
20486         free: free      // An array of unkeyed item indices
20487     }
20488 }
20489
20490 function appendPatch(apply, patch) {
20491     if (apply) {
20492         if (isArray(apply)) {
20493             apply.push(patch)
20494         } else {
20495             apply = [apply, patch]
20496         }
20497
20498         return apply
20499     } else {
20500         return patch
20501     }
20502 }
20503
20504 },{"../vnode/handle-thunk":259,"../vnode/is-thunk":260,"../vnode/is-vnode":262,"../vnode/is-vtext":263,"../vnode/is-widget":264,"../vnode/vpatch":267,"./diff-props":269,"x-is-array":289}],271:[function(require,module,exports){
20505 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20506 /** @author Brian Cavalier */
20507 /** @author John Hann */
20508
20509 (function(define) { 'use strict';
20510 define(function (require) {
20511
20512         var makePromise = require('./makePromise');
20513         var Scheduler = require('./Scheduler');
20514         var async = require('./env').asap;
20515
20516         return makePromise({
20517                 scheduler: new Scheduler(async)
20518         });
20519
20520 });
20521 })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
20522
20523 },{"./Scheduler":272,"./env":284,"./makePromise":286}],272:[function(require,module,exports){
20524 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20525 /** @author Brian Cavalier */
20526 /** @author John Hann */
20527
20528 (function(define) { 'use strict';
20529 define(function() {
20530
20531         // Credit to Twisol (https://github.com/Twisol) for suggesting
20532         // this type of extensible queue + trampoline approach for next-tick conflation.
20533
20534         /**
20535          * Async task scheduler
20536          * @param {function} async function to schedule a single async function
20537          * @constructor
20538          */
20539         function Scheduler(async) {
20540                 this._async = async;
20541                 this._running = false;
20542
20543                 this._queue = this;
20544                 this._queueLen = 0;
20545                 this._afterQueue = {};
20546                 this._afterQueueLen = 0;
20547
20548                 var self = this;
20549                 this.drain = function() {
20550                         self._drain();
20551                 };
20552         }
20553
20554         /**
20555          * Enqueue a task
20556          * @param {{ run:function }} task
20557          */
20558         Scheduler.prototype.enqueue = function(task) {
20559                 this._queue[this._queueLen++] = task;
20560                 this.run();
20561         };
20562
20563         /**
20564          * Enqueue a task to run after the main task queue
20565          * @param {{ run:function }} task
20566          */
20567         Scheduler.prototype.afterQueue = function(task) {
20568                 this._afterQueue[this._afterQueueLen++] = task;
20569                 this.run();
20570         };
20571
20572         Scheduler.prototype.run = function() {
20573                 if (!this._running) {
20574                         this._running = true;
20575                         this._async(this.drain);
20576                 }
20577         };
20578
20579         /**
20580          * Drain the handler queue entirely, and then the after queue
20581          */
20582         Scheduler.prototype._drain = function() {
20583                 var i = 0;
20584                 for (; i < this._queueLen; ++i) {
20585                         this._queue[i].run();
20586                         this._queue[i] = void 0;
20587                 }
20588
20589                 this._queueLen = 0;
20590                 this._running = false;
20591
20592                 for (i = 0; i < this._afterQueueLen; ++i) {
20593                         this._afterQueue[i].run();
20594                         this._afterQueue[i] = void 0;
20595                 }
20596
20597                 this._afterQueueLen = 0;
20598         };
20599
20600         return Scheduler;
20601
20602 });
20603 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
20604
20605 },{}],273:[function(require,module,exports){
20606 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20607 /** @author Brian Cavalier */
20608 /** @author John Hann */
20609
20610 (function(define) { 'use strict';
20611 define(function() {
20612
20613         /**
20614          * Custom error type for promises rejected by promise.timeout
20615          * @param {string} message
20616          * @constructor
20617          */
20618         function TimeoutError (message) {
20619                 Error.call(this);
20620                 this.message = message;
20621                 this.name = TimeoutError.name;
20622                 if (typeof Error.captureStackTrace === 'function') {
20623                         Error.captureStackTrace(this, TimeoutError);
20624                 }
20625         }
20626
20627         TimeoutError.prototype = Object.create(Error.prototype);
20628         TimeoutError.prototype.constructor = TimeoutError;
20629
20630         return TimeoutError;
20631 });
20632 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
20633 },{}],274:[function(require,module,exports){
20634 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20635 /** @author Brian Cavalier */
20636 /** @author John Hann */
20637
20638 (function(define) { 'use strict';
20639 define(function() {
20640
20641         makeApply.tryCatchResolve = tryCatchResolve;
20642
20643         return makeApply;
20644
20645         function makeApply(Promise, call) {
20646                 if(arguments.length < 2) {
20647                         call = tryCatchResolve;
20648                 }
20649
20650                 return apply;
20651
20652                 function apply(f, thisArg, args) {
20653                         var p = Promise._defer();
20654                         var l = args.length;
20655                         var params = new Array(l);
20656                         callAndResolve({ f:f, thisArg:thisArg, args:args, params:params, i:l-1, call:call }, p._handler);
20657
20658                         return p;
20659                 }
20660
20661                 function callAndResolve(c, h) {
20662                         if(c.i < 0) {
20663                                 return call(c.f, c.thisArg, c.params, h);
20664                         }
20665
20666                         var handler = Promise._handler(c.args[c.i]);
20667                         handler.fold(callAndResolveNext, c, void 0, h);
20668                 }
20669
20670                 function callAndResolveNext(c, x, h) {
20671                         c.params[c.i] = x;
20672                         c.i -= 1;
20673                         callAndResolve(c, h);
20674                 }
20675         }
20676
20677         function tryCatchResolve(f, thisArg, args, resolver) {
20678                 try {
20679                         resolver.resolve(f.apply(thisArg, args));
20680                 } catch(e) {
20681                         resolver.reject(e);
20682                 }
20683         }
20684
20685 });
20686 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
20687
20688
20689
20690 },{}],275:[function(require,module,exports){
20691 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20692 /** @author Brian Cavalier */
20693 /** @author John Hann */
20694
20695 (function(define) { 'use strict';
20696 define(function(require) {
20697
20698         var state = require('../state');
20699         var applier = require('../apply');
20700
20701         return function array(Promise) {
20702
20703                 var applyFold = applier(Promise);
20704                 var toPromise = Promise.resolve;
20705                 var all = Promise.all;
20706
20707                 var ar = Array.prototype.reduce;
20708                 var arr = Array.prototype.reduceRight;
20709                 var slice = Array.prototype.slice;
20710
20711                 // Additional array combinators
20712
20713                 Promise.any = any;
20714                 Promise.some = some;
20715                 Promise.settle = settle;
20716
20717                 Promise.map = map;
20718                 Promise.filter = filter;
20719                 Promise.reduce = reduce;
20720                 Promise.reduceRight = reduceRight;
20721
20722                 /**
20723                  * When this promise fulfills with an array, do
20724                  * onFulfilled.apply(void 0, array)
20725                  * @param {function} onFulfilled function to apply
20726                  * @returns {Promise} promise for the result of applying onFulfilled
20727                  */
20728                 Promise.prototype.spread = function(onFulfilled) {
20729                         return this.then(all).then(function(array) {
20730                                 return onFulfilled.apply(this, array);
20731                         });
20732                 };
20733
20734                 return Promise;
20735
20736                 /**
20737                  * One-winner competitive race.
20738                  * Return a promise that will fulfill when one of the promises
20739                  * in the input array fulfills, or will reject when all promises
20740                  * have rejected.
20741                  * @param {array} promises
20742                  * @returns {Promise} promise for the first fulfilled value
20743                  */
20744                 function any(promises) {
20745                         var p = Promise._defer();
20746                         var resolver = p._handler;
20747                         var l = promises.length>>>0;
20748
20749                         var pending = l;
20750                         var errors = [];
20751
20752                         for (var h, x, i = 0; i < l; ++i) {
20753                                 x = promises[i];
20754                                 if(x === void 0 && !(i in promises)) {
20755                                         --pending;
20756                                         continue;
20757                                 }
20758
20759                                 h = Promise._handler(x);
20760                                 if(h.state() > 0) {
20761                                         resolver.become(h);
20762                                         Promise._visitRemaining(promises, i, h);
20763                                         break;
20764                                 } else {
20765                                         h.visit(resolver, handleFulfill, handleReject);
20766                                 }
20767                         }
20768
20769                         if(pending === 0) {
20770                                 resolver.reject(new RangeError('any(): array must not be empty'));
20771                         }
20772
20773                         return p;
20774
20775                         function handleFulfill(x) {
20776                                 /*jshint validthis:true*/
20777                                 errors = null;
20778                                 this.resolve(x); // this === resolver
20779                         }
20780
20781                         function handleReject(e) {
20782                                 /*jshint validthis:true*/
20783                                 if(this.resolved) { // this === resolver
20784                                         return;
20785                                 }
20786
20787                                 errors.push(e);
20788                                 if(--pending === 0) {
20789                                         this.reject(errors);
20790                                 }
20791                         }
20792                 }
20793
20794                 /**
20795                  * N-winner competitive race
20796                  * Return a promise that will fulfill when n input promises have
20797                  * fulfilled, or will reject when it becomes impossible for n
20798                  * input promises to fulfill (ie when promises.length - n + 1
20799                  * have rejected)
20800                  * @param {array} promises
20801                  * @param {number} n
20802                  * @returns {Promise} promise for the earliest n fulfillment values
20803                  *
20804                  * @deprecated
20805                  */
20806                 function some(promises, n) {
20807                         /*jshint maxcomplexity:7*/
20808                         var p = Promise._defer();
20809                         var resolver = p._handler;
20810
20811                         var results = [];
20812                         var errors = [];
20813
20814                         var l = promises.length>>>0;
20815                         var nFulfill = 0;
20816                         var nReject;
20817                         var x, i; // reused in both for() loops
20818
20819                         // First pass: count actual array items
20820                         for(i=0; i<l; ++i) {
20821                                 x = promises[i];
20822                                 if(x === void 0 && !(i in promises)) {
20823                                         continue;
20824                                 }
20825                                 ++nFulfill;
20826                         }
20827
20828                         // Compute actual goals
20829                         n = Math.max(n, 0);
20830                         nReject = (nFulfill - n + 1);
20831                         nFulfill = Math.min(n, nFulfill);
20832
20833                         if(n > nFulfill) {
20834                                 resolver.reject(new RangeError('some(): array must contain at least '
20835                                 + n + ' item(s), but had ' + nFulfill));
20836                         } else if(nFulfill === 0) {
20837                                 resolver.resolve(results);
20838                         }
20839
20840                         // Second pass: observe each array item, make progress toward goals
20841                         for(i=0; i<l; ++i) {
20842                                 x = promises[i];
20843                                 if(x === void 0 && !(i in promises)) {
20844                                         continue;
20845                                 }
20846
20847                                 Promise._handler(x).visit(resolver, fulfill, reject, resolver.notify);
20848                         }
20849
20850                         return p;
20851
20852                         function fulfill(x) {
20853                                 /*jshint validthis:true*/
20854                                 if(this.resolved) { // this === resolver
20855                                         return;
20856                                 }
20857
20858                                 results.push(x);
20859                                 if(--nFulfill === 0) {
20860                                         errors = null;
20861                                         this.resolve(results);
20862                                 }
20863                         }
20864
20865                         function reject(e) {
20866                                 /*jshint validthis:true*/
20867                                 if(this.resolved) { // this === resolver
20868                                         return;
20869                                 }
20870
20871                                 errors.push(e);
20872                                 if(--nReject === 0) {
20873                                         results = null;
20874                                         this.reject(errors);
20875                                 }
20876                         }
20877                 }
20878
20879                 /**
20880                  * Apply f to the value of each promise in a list of promises
20881                  * and return a new list containing the results.
20882                  * @param {array} promises
20883                  * @param {function(x:*, index:Number):*} f mapping function
20884                  * @returns {Promise}
20885                  */
20886                 function map(promises, f) {
20887                         return Promise._traverse(f, promises);
20888                 }
20889
20890                 /**
20891                  * Filter the provided array of promises using the provided predicate.  Input may
20892                  * contain promises and values
20893                  * @param {Array} promises array of promises and values
20894                  * @param {function(x:*, index:Number):boolean} predicate filtering predicate.
20895                  *  Must return truthy (or promise for truthy) for items to retain.
20896                  * @returns {Promise} promise that will fulfill with an array containing all items
20897                  *  for which predicate returned truthy.
20898                  */
20899                 function filter(promises, predicate) {
20900                         var a = slice.call(promises);
20901                         return Promise._traverse(predicate, a).then(function(keep) {
20902                                 return filterSync(a, keep);
20903                         });
20904                 }
20905
20906                 function filterSync(promises, keep) {
20907                         // Safe because we know all promises have fulfilled if we've made it this far
20908                         var l = keep.length;
20909                         var filtered = new Array(l);
20910                         for(var i=0, j=0; i<l; ++i) {
20911                                 if(keep[i]) {
20912                                         filtered[j++] = Promise._handler(promises[i]).value;
20913                                 }
20914                         }
20915                         filtered.length = j;
20916                         return filtered;
20917
20918                 }
20919
20920                 /**
20921                  * Return a promise that will always fulfill with an array containing
20922                  * the outcome states of all input promises.  The returned promise
20923                  * will never reject.
20924                  * @param {Array} promises
20925                  * @returns {Promise} promise for array of settled state descriptors
20926                  */
20927                 function settle(promises) {
20928                         return all(promises.map(settleOne));
20929                 }
20930
20931                 function settleOne(p) {
20932                         // Optimize the case where we get an already-resolved when.js promise
20933                         //  by extracting its state:
20934                         var handler;
20935                         if (p instanceof Promise) {
20936                                 // This is our own Promise type and we can reach its handler internals:
20937                                 handler = p._handler.join();
20938                         }
20939                         if((handler && handler.state() === 0) || !handler) {
20940                                 // Either still pending, or not a Promise at all:
20941                                 return toPromise(p).then(state.fulfilled, state.rejected);
20942                         }
20943
20944                         // The promise is our own, but it is already resolved. Take a shortcut.
20945                         // Since we're not actually handling the resolution, we need to disable
20946                         // rejection reporting.
20947                         handler._unreport();
20948                         return state.inspect(handler);
20949                 }
20950
20951                 /**
20952                  * Traditional reduce function, similar to `Array.prototype.reduce()`, but
20953                  * input may contain promises and/or values, and reduceFunc
20954                  * may return either a value or a promise, *and* initialValue may
20955                  * be a promise for the starting value.
20956                  * @param {Array|Promise} promises array or promise for an array of anything,
20957                  *      may contain a mix of promises and values.
20958                  * @param {function(accumulated:*, x:*, index:Number):*} f reduce function
20959                  * @returns {Promise} that will resolve to the final reduced value
20960                  */
20961                 function reduce(promises, f /*, initialValue */) {
20962                         return arguments.length > 2 ? ar.call(promises, liftCombine(f), arguments[2])
20963                                         : ar.call(promises, liftCombine(f));
20964                 }
20965
20966                 /**
20967                  * Traditional reduce function, similar to `Array.prototype.reduceRight()`, but
20968                  * input may contain promises and/or values, and reduceFunc
20969                  * may return either a value or a promise, *and* initialValue may
20970                  * be a promise for the starting value.
20971                  * @param {Array|Promise} promises array or promise for an array of anything,
20972                  *      may contain a mix of promises and values.
20973                  * @param {function(accumulated:*, x:*, index:Number):*} f reduce function
20974                  * @returns {Promise} that will resolve to the final reduced value
20975                  */
20976                 function reduceRight(promises, f /*, initialValue */) {
20977                         return arguments.length > 2 ? arr.call(promises, liftCombine(f), arguments[2])
20978                                         : arr.call(promises, liftCombine(f));
20979                 }
20980
20981                 function liftCombine(f) {
20982                         return function(z, x, i) {
20983                                 return applyFold(f, void 0, [z,x,i]);
20984                         };
20985                 }
20986         };
20987
20988 });
20989 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
20990
20991 },{"../apply":274,"../state":287}],276:[function(require,module,exports){
20992 /** @license MIT License (c) copyright 2010-2014 original author or authors */
20993 /** @author Brian Cavalier */
20994 /** @author John Hann */
20995
20996 (function(define) { 'use strict';
20997 define(function() {
20998
20999         return function flow(Promise) {
21000
21001                 var resolve = Promise.resolve;
21002                 var reject = Promise.reject;
21003                 var origCatch = Promise.prototype['catch'];
21004
21005                 /**
21006                  * Handle the ultimate fulfillment value or rejection reason, and assume
21007                  * responsibility for all errors.  If an error propagates out of result
21008                  * or handleFatalError, it will be rethrown to the host, resulting in a
21009                  * loud stack track on most platforms and a crash on some.
21010                  * @param {function?} onResult
21011                  * @param {function?} onError
21012                  * @returns {undefined}
21013                  */
21014                 Promise.prototype.done = function(onResult, onError) {
21015                         this._handler.visit(this._handler.receiver, onResult, onError);
21016                 };
21017
21018                 /**
21019                  * Add Error-type and predicate matching to catch.  Examples:
21020                  * promise.catch(TypeError, handleTypeError)
21021                  *   .catch(predicate, handleMatchedErrors)
21022                  *   .catch(handleRemainingErrors)
21023                  * @param onRejected
21024                  * @returns {*}
21025                  */
21026                 Promise.prototype['catch'] = Promise.prototype.otherwise = function(onRejected) {
21027                         if (arguments.length < 2) {
21028                                 return origCatch.call(this, onRejected);
21029                         }
21030
21031                         if(typeof onRejected !== 'function') {
21032                                 return this.ensure(rejectInvalidPredicate);
21033                         }
21034
21035                         return origCatch.call(this, createCatchFilter(arguments[1], onRejected));
21036                 };
21037
21038                 /**
21039                  * Wraps the provided catch handler, so that it will only be called
21040                  * if the predicate evaluates truthy
21041                  * @param {?function} handler
21042                  * @param {function} predicate
21043                  * @returns {function} conditional catch handler
21044                  */
21045                 function createCatchFilter(handler, predicate) {
21046                         return function(e) {
21047                                 return evaluatePredicate(e, predicate)
21048                                         ? handler.call(this, e)
21049                                         : reject(e);
21050                         };
21051                 }
21052
21053                 /**
21054                  * Ensures that onFulfilledOrRejected will be called regardless of whether
21055                  * this promise is fulfilled or rejected.  onFulfilledOrRejected WILL NOT
21056                  * receive the promises' value or reason.  Any returned value will be disregarded.
21057                  * onFulfilledOrRejected may throw or return a rejected promise to signal
21058                  * an additional error.
21059                  * @param {function} handler handler to be called regardless of
21060                  *  fulfillment or rejection
21061                  * @returns {Promise}
21062                  */
21063                 Promise.prototype['finally'] = Promise.prototype.ensure = function(handler) {
21064                         if(typeof handler !== 'function') {
21065                                 return this;
21066                         }
21067
21068                         return this.then(function(x) {
21069                                 return runSideEffect(handler, this, identity, x);
21070                         }, function(e) {
21071                                 return runSideEffect(handler, this, reject, e);
21072                         });
21073                 };
21074
21075                 function runSideEffect (handler, thisArg, propagate, value) {
21076                         var result = handler.call(thisArg);
21077                         return maybeThenable(result)
21078                                 ? propagateValue(result, propagate, value)
21079                                 : propagate(value);
21080                 }
21081
21082                 function propagateValue (result, propagate, x) {
21083                         return resolve(result).then(function () {
21084                                 return propagate(x);
21085                         });
21086                 }
21087
21088                 /**
21089                  * Recover from a failure by returning a defaultValue.  If defaultValue
21090                  * is a promise, it's fulfillment value will be used.  If defaultValue is
21091                  * a promise that rejects, the returned promise will reject with the
21092                  * same reason.
21093                  * @param {*} defaultValue
21094                  * @returns {Promise} new promise
21095                  */
21096                 Promise.prototype['else'] = Promise.prototype.orElse = function(defaultValue) {
21097                         return this.then(void 0, function() {
21098                                 return defaultValue;
21099                         });
21100                 };
21101
21102                 /**
21103                  * Shortcut for .then(function() { return value; })
21104                  * @param  {*} value
21105                  * @return {Promise} a promise that:
21106                  *  - is fulfilled if value is not a promise, or
21107                  *  - if value is a promise, will fulfill with its value, or reject
21108                  *    with its reason.
21109                  */
21110                 Promise.prototype['yield'] = function(value) {
21111                         return this.then(function() {
21112                                 return value;
21113                         });
21114                 };
21115
21116                 /**
21117                  * Runs a side effect when this promise fulfills, without changing the
21118                  * fulfillment value.
21119                  * @param {function} onFulfilledSideEffect
21120                  * @returns {Promise}
21121                  */
21122                 Promise.prototype.tap = function(onFulfilledSideEffect) {
21123                         return this.then(onFulfilledSideEffect)['yield'](this);
21124                 };
21125
21126                 return Promise;
21127         };
21128
21129         function rejectInvalidPredicate() {
21130                 throw new TypeError('catch predicate must be a function');
21131         }
21132
21133         function evaluatePredicate(e, predicate) {
21134                 return isError(predicate) ? e instanceof predicate : predicate(e);
21135         }
21136
21137         function isError(predicate) {
21138                 return predicate === Error
21139                         || (predicate != null && predicate.prototype instanceof Error);
21140         }
21141
21142         function maybeThenable(x) {
21143                 return (typeof x === 'object' || typeof x === 'function') && x !== null;
21144         }
21145
21146         function identity(x) {
21147                 return x;
21148         }
21149
21150 });
21151 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
21152
21153 },{}],277:[function(require,module,exports){
21154 /** @license MIT License (c) copyright 2010-2014 original author or authors */
21155 /** @author Brian Cavalier */
21156 /** @author John Hann */
21157 /** @author Jeff Escalante */
21158
21159 (function(define) { 'use strict';
21160 define(function() {
21161
21162         return function fold(Promise) {
21163
21164                 Promise.prototype.fold = function(f, z) {
21165                         var promise = this._beget();
21166
21167                         this._handler.fold(function(z, x, to) {
21168                                 Promise._handler(z).fold(function(x, z, to) {
21169                                         to.resolve(f.call(this, z, x));
21170                                 }, x, this, to);
21171                         }, z, promise._handler.receiver, promise._handler);
21172
21173                         return promise;
21174                 };
21175
21176                 return Promise;
21177         };
21178
21179 });
21180 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
21181
21182 },{}],278:[function(require,module,exports){
21183 /** @license MIT License (c) copyright 2010-2014 original author or authors */
21184 /** @author Brian Cavalier */
21185 /** @author John Hann */
21186
21187 (function(define) { 'use strict';
21188 define(function(require) {
21189
21190         var inspect = require('../state').inspect;
21191
21192         return function inspection(Promise) {
21193
21194                 Promise.prototype.inspect = function() {
21195                         return inspect(Promise._handler(this));
21196                 };
21197
21198                 return Promise;
21199         };
21200
21201 });
21202 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
21203
21204 },{"../state":287}],279:[function(require,module,exports){
21205 /** @license MIT License (c) copyright 2010-2014 original author or authors */
21206 /** @author Brian Cavalier */
21207 /** @author John Hann */
21208
21209 (function(define) { 'use strict';
21210 define(function() {
21211
21212         return function generate(Promise) {
21213
21214                 var resolve = Promise.resolve;
21215
21216                 Promise.iterate = iterate;
21217                 Promise.unfold = unfold;
21218
21219                 return Promise;
21220
21221                 /**
21222                  * @deprecated Use github.com/cujojs/most streams and most.iterate
21223                  * Generate a (potentially infinite) stream of promised values:
21224                  * x, f(x), f(f(x)), etc. until condition(x) returns true
21225                  * @param {function} f function to generate a new x from the previous x
21226                  * @param {function} condition function that, given the current x, returns
21227                  *  truthy when the iterate should stop
21228                  * @param {function} handler function to handle the value produced by f
21229                  * @param {*|Promise} x starting value, may be a promise
21230                  * @return {Promise} the result of the last call to f before
21231                  *  condition returns true
21232                  */
21233                 function iterate(f, condition, handler, x) {
21234                         return unfold(function(x) {
21235                                 return [x, f(x)];
21236                         }, condition, handler, x);
21237                 }
21238
21239                 /**
21240                  * @deprecated Use github.com/cujojs/most streams and most.unfold
21241                  * Generate a (potentially infinite) stream of promised values
21242                  * by applying handler(generator(seed)) iteratively until
21243                  * condition(seed) returns true.
21244                  * @param {function} unspool function that generates a [value, newSeed]
21245                  *  given a seed.
21246                  * @param {function} condition function that, given the current seed, returns
21247                  *  truthy when the unfold should stop
21248                  * @param {function} handler function to handle the value produced by unspool
21249                  * @param x {*|Promise} starting value, may be a promise
21250                  * @return {Promise} the result of the last value produced by unspool before
21251                  *  condition returns true
21252                  */
21253                 function unfold(unspool, condition, handler, x) {
21254                         return resolve(x).then(function(seed) {
21255                                 return resolve(condition(seed)).then(function(done) {
21256                                         return done ? seed : resolve(unspool(seed)).spread(next);
21257                                 });
21258                         });
21259
21260                         function next(item, newSeed) {
21261                                 return resolve(handler(item)).then(function() {
21262                                         return unfold(unspool, condition, handler, newSeed);
21263                                 });
21264                         }
21265                 }
21266         };
21267
21268 });
21269 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
21270
21271 },{}],280:[function(require,module,exports){
21272 /** @license MIT License (c) copyright 2010-2014 original author or authors */
21273 /** @author Brian Cavalier */
21274 /** @author John Hann */
21275
21276 (function(define) { 'use strict';
21277 define(function() {
21278
21279         return function progress(Promise) {
21280
21281                 /**
21282                  * @deprecated
21283                  * Register a progress handler for this promise
21284                  * @param {function} onProgress
21285                  * @returns {Promise}
21286                  */
21287                 Promise.prototype.progress = function(onProgress) {
21288                         return this.then(void 0, void 0, onProgress);
21289                 };
21290
21291                 return Promise;
21292         };
21293
21294 });
21295 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
21296
21297 },{}],281:[function(require,module,exports){
21298 /** @license MIT License (c) copyright 2010-2014 original author or authors */
21299 /** @author Brian Cavalier */
21300 /** @author John Hann */
21301
21302 (function(define) { 'use strict';
21303 define(function(require) {
21304
21305         var env = require('../env');
21306         var TimeoutError = require('../TimeoutError');
21307
21308         function setTimeout(f, ms, x, y) {
21309                 return env.setTimer(function() {
21310                         f(x, y, ms);
21311                 }, ms);
21312         }
21313
21314         return function timed(Promise) {
21315                 /**
21316                  * Return a new promise whose fulfillment value is revealed only
21317                  * after ms milliseconds
21318                  * @param {number} ms milliseconds
21319                  * @returns {Promise}
21320                  */
21321                 Promise.prototype.delay = function(ms) {
21322                         var p = this._beget();
21323                         this._handler.fold(handleDelay, ms, void 0, p._handler);
21324                         return p;
21325                 };
21326
21327                 function handleDelay(ms, x, h) {
21328                         setTimeout(resolveDelay, ms, x, h);
21329                 }
21330
21331                 function resolveDelay(x, h) {
21332                         h.resolve(x);
21333                 }
21334
21335                 /**
21336                  * Return a new promise that rejects after ms milliseconds unless
21337                  * this promise fulfills earlier, in which case the returned promise
21338                  * fulfills with the same value.
21339                  * @param {number} ms milliseconds
21340                  * @param {Error|*=} reason optional rejection reason to use, defaults
21341                  *   to a TimeoutError if not provided
21342                  * @returns {Promise}
21343                  */
21344                 Promise.prototype.timeout = function(ms, reason) {
21345                         var p = this._beget();
21346                         var h = p._handler;
21347
21348                         var t = setTimeout(onTimeout, ms, reason, p._handler);
21349
21350                         this._handler.visit(h,
21351                                 function onFulfill(x) {
21352                                         env.clearTimer(t);
21353                                         this.resolve(x); // this = h
21354                                 },
21355                                 function onReject(x) {
21356                                         env.clearTimer(t);
21357                                         this.reject(x); // this = h
21358                                 },
21359                                 h.notify);
21360
21361                         return p;
21362                 };
21363
21364                 function onTimeout(reason, h, ms) {
21365                         var e = typeof reason === 'undefined'
21366                                 ? new TimeoutError('timed out after ' + ms + 'ms')
21367                                 : reason;
21368                         h.reject(e);
21369                 }
21370
21371                 return Promise;
21372         };
21373
21374 });
21375 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
21376
21377 },{"../TimeoutError":273,"../env":284}],282:[function(require,module,exports){
21378 /** @license MIT License (c) copyright 2010-2014 original author or authors */
21379 /** @author Brian Cavalier */
21380 /** @author John Hann */
21381
21382 (function(define) { 'use strict';
21383 define(function(require) {
21384
21385         var setTimer = require('../env').setTimer;
21386         var format = require('../format');
21387
21388         return function unhandledRejection(Promise) {
21389
21390                 var logError = noop;
21391                 var logInfo = noop;
21392                 var localConsole;
21393
21394                 if(typeof console !== 'undefined') {
21395                         // Alias console to prevent things like uglify's drop_console option from
21396                         // removing console.log/error. Unhandled rejections fall into the same
21397                         // category as uncaught exceptions, and build tools shouldn't silence them.
21398                         localConsole = console;
21399                         logError = typeof localConsole.error !== 'undefined'
21400                                 ? function (e) { localConsole.error(e); }
21401                                 : function (e) { localConsole.log(e); };
21402
21403                         logInfo = typeof localConsole.info !== 'undefined'
21404                                 ? function (e) { localConsole.info(e); }
21405                                 : function (e) { localConsole.log(e); };
21406                 }
21407
21408                 Promise.onPotentiallyUnhandledRejection = function(rejection) {
21409                         enqueue(report, rejection);
21410                 };
21411
21412                 Promise.onPotentiallyUnhandledRejectionHandled = function(rejection) {
21413                         enqueue(unreport, rejection);
21414                 };
21415
21416                 Promise.onFatalRejection = function(rejection) {
21417                         enqueue(throwit, rejection.value);
21418                 };
21419
21420                 var tasks = [];
21421                 var reported = [];
21422                 var running = null;
21423
21424                 function report(r) {
21425                         if(!r.handled) {
21426                                 reported.push(r);
21427                                 logError('Potentially unhandled rejection [' + r.id + '] ' + format.formatError(r.value));
21428                         }
21429                 }
21430
21431                 function unreport(r) {
21432                         var i = reported.indexOf(r);
21433                         if(i >= 0) {
21434                                 reported.splice(i, 1);
21435                                 logInfo('Handled previous rejection [' + r.id + '] ' + format.formatObject(r.value));
21436                         }
21437                 }
21438
21439                 function enqueue(f, x) {
21440                         tasks.push(f, x);
21441                         if(running === null) {
21442                                 running = setTimer(flush, 0);
21443                         }
21444                 }
21445
21446                 function flush() {
21447                         running = null;
21448                         while(tasks.length > 0) {
21449                                 tasks.shift()(tasks.shift());
21450                         }
21451                 }
21452
21453                 return Promise;
21454         };
21455
21456         function throwit(e) {
21457                 throw e;
21458         }
21459
21460         function noop() {}
21461
21462 });
21463 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
21464
21465 },{"../env":284,"../format":285}],283:[function(require,module,exports){
21466 /** @license MIT License (c) copyright 2010-2014 original author or authors */
21467 /** @author Brian Cavalier */
21468 /** @author John Hann */
21469
21470 (function(define) { 'use strict';
21471 define(function() {
21472
21473         return function addWith(Promise) {
21474                 /**
21475                  * Returns a promise whose handlers will be called with `this` set to
21476                  * the supplied receiver.  Subsequent promises derived from the
21477                  * returned promise will also have their handlers called with receiver
21478                  * as `this`. Calling `with` with undefined or no arguments will return
21479                  * a promise whose handlers will again be called in the usual Promises/A+
21480                  * way (no `this`) thus safely undoing any previous `with` in the
21481                  * promise chain.
21482                  *
21483                  * WARNING: Promises returned from `with`/`withThis` are NOT Promises/A+
21484                  * compliant, specifically violating 2.2.5 (http://promisesaplus.com/#point-41)
21485                  *
21486                  * @param {object} receiver `this` value for all handlers attached to
21487                  *  the returned promise.
21488                  * @returns {Promise}
21489                  */
21490                 Promise.prototype['with'] = Promise.prototype.withThis = function(receiver) {
21491                         var p = this._beget();
21492                         var child = p._handler;
21493                         child.receiver = receiver;
21494                         this._handler.chain(child, receiver);
21495                         return p;
21496                 };
21497
21498                 return Promise;
21499         };
21500
21501 });
21502 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
21503
21504
21505 },{}],284:[function(require,module,exports){
21506 (function (process){
21507 /** @license MIT License (c) copyright 2010-2014 original author or authors */
21508 /** @author Brian Cavalier */
21509 /** @author John Hann */
21510
21511 /*global process,document,setTimeout,clearTimeout,MutationObserver,WebKitMutationObserver*/
21512 (function(define) { 'use strict';
21513 define(function(require) {
21514         /*jshint maxcomplexity:6*/
21515
21516         // Sniff "best" async scheduling option
21517         // Prefer process.nextTick or MutationObserver, then check for
21518         // setTimeout, and finally vertx, since its the only env that doesn't
21519         // have setTimeout
21520
21521         var MutationObs;
21522         var capturedSetTimeout = typeof setTimeout !== 'undefined' && setTimeout;
21523
21524         // Default env
21525         var setTimer = function(f, ms) { return setTimeout(f, ms); };
21526         var clearTimer = function(t) { return clearTimeout(t); };
21527         var asap = function (f) { return capturedSetTimeout(f, 0); };
21528
21529         // Detect specific env
21530         if (isNode()) { // Node
21531                 asap = function (f) { return process.nextTick(f); };
21532
21533         } else if (MutationObs = hasMutationObserver()) { // Modern browser
21534                 asap = initMutationObserver(MutationObs);
21535
21536         } else if (!capturedSetTimeout) { // vert.x
21537                 var vertxRequire = require;
21538                 var vertx = vertxRequire('vertx');
21539                 setTimer = function (f, ms) { return vertx.setTimer(ms, f); };
21540                 clearTimer = vertx.cancelTimer;
21541                 asap = vertx.runOnLoop || vertx.runOnContext;
21542         }
21543
21544         return {
21545                 setTimer: setTimer,
21546                 clearTimer: clearTimer,
21547                 asap: asap
21548         };
21549
21550         function isNode () {
21551                 return typeof process !== 'undefined' &&
21552                         Object.prototype.toString.call(process) === '[object process]';
21553         }
21554
21555         function hasMutationObserver () {
21556             return (typeof MutationObserver !== 'undefined' && MutationObserver) ||
21557                         (typeof WebKitMutationObserver !== 'undefined' && WebKitMutationObserver);
21558         }
21559
21560         function initMutationObserver(MutationObserver) {
21561                 var scheduled;
21562                 var node = document.createTextNode('');
21563                 var o = new MutationObserver(run);
21564                 o.observe(node, { characterData: true });
21565
21566                 function run() {
21567                         var f = scheduled;
21568                         scheduled = void 0;
21569                         f();
21570                 }
21571
21572                 var i = 0;
21573                 return function (f) {
21574                         scheduled = f;
21575                         node.data = (i ^= 1);
21576                 };
21577         }
21578 });
21579 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
21580
21581 }).call(this,require('_process'))
21582
21583 },{"_process":6}],285:[function(require,module,exports){
21584 /** @license MIT License (c) copyright 2010-2014 original author or authors */
21585 /** @author Brian Cavalier */
21586 /** @author John Hann */
21587
21588 (function(define) { 'use strict';
21589 define(function() {
21590
21591         return {
21592                 formatError: formatError,
21593                 formatObject: formatObject,
21594                 tryStringify: tryStringify
21595         };
21596
21597         /**
21598          * Format an error into a string.  If e is an Error and has a stack property,
21599          * it's returned.  Otherwise, e is formatted using formatObject, with a
21600          * warning added about e not being a proper Error.
21601          * @param {*} e
21602          * @returns {String} formatted string, suitable for output to developers
21603          */
21604         function formatError(e) {
21605                 var s = typeof e === 'object' && e !== null && (e.stack || e.message) ? e.stack || e.message : formatObject(e);
21606                 return e instanceof Error ? s : s + ' (WARNING: non-Error used)';
21607         }
21608
21609         /**
21610          * Format an object, detecting "plain" objects and running them through
21611          * JSON.stringify if possible.
21612          * @param {Object} o
21613          * @returns {string}
21614          */
21615         function formatObject(o) {
21616                 var s = String(o);
21617                 if(s === '[object Object]' && typeof JSON !== 'undefined') {
21618                         s = tryStringify(o, s);
21619                 }
21620                 return s;
21621         }
21622
21623         /**
21624          * Try to return the result of JSON.stringify(x).  If that fails, return
21625          * defaultValue
21626          * @param {*} x
21627          * @param {*} defaultValue
21628          * @returns {String|*} JSON.stringify(x) or defaultValue
21629          */
21630         function tryStringify(x, defaultValue) {
21631                 try {
21632                         return JSON.stringify(x);
21633                 } catch(e) {
21634                         return defaultValue;
21635                 }
21636         }
21637
21638 });
21639 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
21640
21641 },{}],286:[function(require,module,exports){
21642 (function (process){
21643 /** @license MIT License (c) copyright 2010-2014 original author or authors */
21644 /** @author Brian Cavalier */
21645 /** @author John Hann */
21646
21647 (function(define) { 'use strict';
21648 define(function() {
21649
21650         return function makePromise(environment) {
21651
21652                 var tasks = environment.scheduler;
21653                 var emitRejection = initEmitRejection();
21654
21655                 var objectCreate = Object.create ||
21656                         function(proto) {
21657                                 function Child() {}
21658                                 Child.prototype = proto;
21659                                 return new Child();
21660                         };
21661
21662                 /**
21663                  * Create a promise whose fate is determined by resolver
21664                  * @constructor
21665                  * @returns {Promise} promise
21666                  * @name Promise
21667                  */
21668                 function Promise(resolver, handler) {
21669                         this._handler = resolver === Handler ? handler : init(resolver);
21670                 }
21671
21672                 /**
21673                  * Run the supplied resolver
21674                  * @param resolver
21675                  * @returns {Pending}
21676                  */
21677                 function init(resolver) {
21678                         var handler = new Pending();
21679
21680                         try {
21681                                 resolver(promiseResolve, promiseReject, promiseNotify);
21682                         } catch (e) {
21683                                 promiseReject(e);
21684                         }
21685
21686                         return handler;
21687
21688                         /**
21689                          * Transition from pre-resolution state to post-resolution state, notifying
21690                          * all listeners of the ultimate fulfillment or rejection
21691                          * @param {*} x resolution value
21692                          */
21693                         function promiseResolve (x) {
21694                                 handler.resolve(x);
21695                         }
21696                         /**
21697                          * Reject this promise with reason, which will be used verbatim
21698                          * @param {Error|*} reason rejection reason, strongly suggested
21699                          *   to be an Error type
21700                          */
21701                         function promiseReject (reason) {
21702                                 handler.reject(reason);
21703                         }
21704
21705                         /**
21706                          * @deprecated
21707                          * Issue a progress event, notifying all progress listeners
21708                          * @param {*} x progress event payload to pass to all listeners
21709                          */
21710                         function promiseNotify (x) {
21711                                 handler.notify(x);
21712                         }
21713                 }
21714
21715                 // Creation
21716
21717                 Promise.resolve = resolve;
21718                 Promise.reject = reject;
21719                 Promise.never = never;
21720
21721                 Promise._defer = defer;
21722                 Promise._handler = getHandler;
21723
21724                 /**
21725                  * Returns a trusted promise. If x is already a trusted promise, it is
21726                  * returned, otherwise returns a new trusted Promise which follows x.
21727                  * @param  {*} x
21728                  * @return {Promise} promise
21729                  */
21730                 function resolve(x) {
21731                         return isPromise(x) ? x
21732                                 : new Promise(Handler, new Async(getHandler(x)));
21733                 }
21734
21735                 /**
21736                  * Return a reject promise with x as its reason (x is used verbatim)
21737                  * @param {*} x
21738                  * @returns {Promise} rejected promise
21739                  */
21740                 function reject(x) {
21741                         return new Promise(Handler, new Async(new Rejected(x)));
21742                 }
21743
21744                 /**
21745                  * Return a promise that remains pending forever
21746                  * @returns {Promise} forever-pending promise.
21747                  */
21748                 function never() {
21749                         return foreverPendingPromise; // Should be frozen
21750                 }
21751
21752                 /**
21753                  * Creates an internal {promise, resolver} pair
21754                  * @private
21755                  * @returns {Promise}
21756                  */
21757                 function defer() {
21758                         return new Promise(Handler, new Pending());
21759                 }
21760
21761                 // Transformation and flow control
21762
21763                 /**
21764                  * Transform this promise's fulfillment value, returning a new Promise
21765                  * for the transformed result.  If the promise cannot be fulfilled, onRejected
21766                  * is called with the reason.  onProgress *may* be called with updates toward
21767                  * this promise's fulfillment.
21768                  * @param {function=} onFulfilled fulfillment handler
21769                  * @param {function=} onRejected rejection handler
21770                  * @param {function=} onProgress @deprecated progress handler
21771                  * @return {Promise} new promise
21772                  */
21773                 Promise.prototype.then = function(onFulfilled, onRejected, onProgress) {
21774                         var parent = this._handler;
21775                         var state = parent.join().state();
21776
21777                         if ((typeof onFulfilled !== 'function' && state > 0) ||
21778                                 (typeof onRejected !== 'function' && state < 0)) {
21779                                 // Short circuit: value will not change, simply share handler
21780                                 return new this.constructor(Handler, parent);
21781                         }
21782
21783                         var p = this._beget();
21784                         var child = p._handler;
21785
21786                         parent.chain(child, parent.receiver, onFulfilled, onRejected, onProgress);
21787
21788                         return p;
21789                 };
21790
21791                 /**
21792                  * If this promise cannot be fulfilled due to an error, call onRejected to
21793                  * handle the error. Shortcut for .then(undefined, onRejected)
21794                  * @param {function?} onRejected
21795                  * @return {Promise}
21796                  */
21797                 Promise.prototype['catch'] = function(onRejected) {
21798                         return this.then(void 0, onRejected);
21799                 };
21800
21801                 /**
21802                  * Creates a new, pending promise of the same type as this promise
21803                  * @private
21804                  * @returns {Promise}
21805                  */
21806                 Promise.prototype._beget = function() {
21807                         return begetFrom(this._handler, this.constructor);
21808                 };
21809
21810                 function begetFrom(parent, Promise) {
21811                         var child = new Pending(parent.receiver, parent.join().context);
21812                         return new Promise(Handler, child);
21813                 }
21814
21815                 // Array combinators
21816
21817                 Promise.all = all;
21818                 Promise.race = race;
21819                 Promise._traverse = traverse;
21820
21821                 /**
21822                  * Return a promise that will fulfill when all promises in the
21823                  * input array have fulfilled, or will reject when one of the
21824                  * promises rejects.
21825                  * @param {array} promises array of promises
21826                  * @returns {Promise} promise for array of fulfillment values
21827                  */
21828                 function all(promises) {
21829                         return traverseWith(snd, null, promises);
21830                 }
21831
21832                 /**
21833                  * Array<Promise<X>> -> Promise<Array<f(X)>>
21834                  * @private
21835                  * @param {function} f function to apply to each promise's value
21836                  * @param {Array} promises array of promises
21837                  * @returns {Promise} promise for transformed values
21838                  */
21839                 function traverse(f, promises) {
21840                         return traverseWith(tryCatch2, f, promises);
21841                 }
21842
21843                 function traverseWith(tryMap, f, promises) {
21844                         var handler = typeof f === 'function' ? mapAt : settleAt;
21845
21846                         var resolver = new Pending();
21847                         var pending = promises.length >>> 0;
21848                         var results = new Array(pending);
21849
21850                         for (var i = 0, x; i < promises.length && !resolver.resolved; ++i) {
21851                                 x = promises[i];
21852
21853                                 if (x === void 0 && !(i in promises)) {
21854                                         --pending;
21855                                         continue;
21856                                 }
21857
21858                                 traverseAt(promises, handler, i, x, resolver);
21859                         }
21860
21861                         if(pending === 0) {
21862                                 resolver.become(new Fulfilled(results));
21863                         }
21864
21865                         return new Promise(Handler, resolver);
21866
21867                         function mapAt(i, x, resolver) {
21868                                 if(!resolver.resolved) {
21869                                         traverseAt(promises, settleAt, i, tryMap(f, x, i), resolver);
21870                                 }
21871                         }
21872
21873                         function settleAt(i, x, resolver) {
21874                                 results[i] = x;
21875                                 if(--pending === 0) {
21876                                         resolver.become(new Fulfilled(results));
21877                                 }
21878                         }
21879                 }
21880
21881                 function traverseAt(promises, handler, i, x, resolver) {
21882                         if (maybeThenable(x)) {
21883                                 var h = getHandlerMaybeThenable(x);
21884                                 var s = h.state();
21885
21886                                 if (s === 0) {
21887                                         h.fold(handler, i, void 0, resolver);
21888                                 } else if (s > 0) {
21889                                         handler(i, h.value, resolver);
21890                                 } else {
21891                                         resolver.become(h);
21892                                         visitRemaining(promises, i+1, h);
21893                                 }
21894                         } else {
21895                                 handler(i, x, resolver);
21896                         }
21897                 }
21898
21899                 Promise._visitRemaining = visitRemaining;
21900                 function visitRemaining(promises, start, handler) {
21901                         for(var i=start; i<promises.length; ++i) {
21902                                 markAsHandled(getHandler(promises[i]), handler);
21903                         }
21904                 }
21905
21906                 function markAsHandled(h, handler) {
21907                         if(h === handler) {
21908                                 return;
21909                         }
21910
21911                         var s = h.state();
21912                         if(s === 0) {
21913                                 h.visit(h, void 0, h._unreport);
21914                         } else if(s < 0) {
21915                                 h._unreport();
21916                         }
21917                 }
21918
21919                 /**
21920                  * Fulfill-reject competitive race. Return a promise that will settle
21921                  * to the same state as the earliest input promise to settle.
21922                  *
21923                  * WARNING: The ES6 Promise spec requires that race()ing an empty array
21924                  * must return a promise that is pending forever.  This implementation
21925                  * returns a singleton forever-pending promise, the same singleton that is
21926                  * returned by Promise.never(), thus can be checked with ===
21927                  *
21928                  * @param {array} promises array of promises to race
21929                  * @returns {Promise} if input is non-empty, a promise that will settle
21930                  * to the same outcome as the earliest input promise to settle. if empty
21931                  * is empty, returns a promise that will never settle.
21932                  */
21933                 function race(promises) {
21934                         if(typeof promises !== 'object' || promises === null) {
21935                                 return reject(new TypeError('non-iterable passed to race()'));
21936                         }
21937
21938                         // Sigh, race([]) is untestable unless we return *something*
21939                         // that is recognizable without calling .then() on it.
21940                         return promises.length === 0 ? never()
21941                                  : promises.length === 1 ? resolve(promises[0])
21942                                  : runRace(promises);
21943                 }
21944
21945                 function runRace(promises) {
21946                         var resolver = new Pending();
21947                         var i, x, h;
21948                         for(i=0; i<promises.length; ++i) {
21949                                 x = promises[i];
21950                                 if (x === void 0 && !(i in promises)) {
21951                                         continue;
21952                                 }
21953
21954                                 h = getHandler(x);
21955                                 if(h.state() !== 0) {
21956                                         resolver.become(h);
21957                                         visitRemaining(promises, i+1, h);
21958                                         break;
21959                                 } else {
21960                                         h.visit(resolver, resolver.resolve, resolver.reject);
21961                                 }
21962                         }
21963                         return new Promise(Handler, resolver);
21964                 }
21965
21966                 // Promise internals
21967                 // Below this, everything is @private
21968
21969                 /**
21970                  * Get an appropriate handler for x, without checking for cycles
21971                  * @param {*} x
21972                  * @returns {object} handler
21973                  */
21974                 function getHandler(x) {
21975                         if(isPromise(x)) {
21976                                 return x._handler.join();
21977                         }
21978                         return maybeThenable(x) ? getHandlerUntrusted(x) : new Fulfilled(x);
21979                 }
21980
21981                 /**
21982                  * Get a handler for thenable x.
21983                  * NOTE: You must only call this if maybeThenable(x) == true
21984                  * @param {object|function|Promise} x
21985                  * @returns {object} handler
21986                  */
21987                 function getHandlerMaybeThenable(x) {
21988                         return isPromise(x) ? x._handler.join() : getHandlerUntrusted(x);
21989                 }
21990
21991                 /**
21992                  * Get a handler for potentially untrusted thenable x
21993                  * @param {*} x
21994                  * @returns {object} handler
21995                  */
21996                 function getHandlerUntrusted(x) {
21997                         try {
21998                                 var untrustedThen = x.then;
21999                                 return typeof untrustedThen === 'function'
22000                                         ? new Thenable(untrustedThen, x)
22001                                         : new Fulfilled(x);
22002                         } catch(e) {
22003                                 return new Rejected(e);
22004                         }
22005                 }
22006
22007                 /**
22008                  * Handler for a promise that is pending forever
22009                  * @constructor
22010                  */
22011                 function Handler() {}
22012
22013                 Handler.prototype.when
22014                         = Handler.prototype.become
22015                         = Handler.prototype.notify // deprecated
22016                         = Handler.prototype.fail
22017                         = Handler.prototype._unreport
22018                         = Handler.prototype._report
22019                         = noop;
22020
22021                 Handler.prototype._state = 0;
22022
22023                 Handler.prototype.state = function() {
22024                         return this._state;
22025                 };
22026
22027                 /**
22028                  * Recursively collapse handler chain to find the handler
22029                  * nearest to the fully resolved value.
22030                  * @returns {object} handler nearest the fully resolved value
22031                  */
22032                 Handler.prototype.join = function() {
22033                         var h = this;
22034                         while(h.handler !== void 0) {
22035                                 h = h.handler;
22036                         }
22037                         return h;
22038                 };
22039
22040                 Handler.prototype.chain = function(to, receiver, fulfilled, rejected, progress) {
22041                         this.when({
22042                                 resolver: to,
22043                                 receiver: receiver,
22044                                 fulfilled: fulfilled,
22045                                 rejected: rejected,
22046                                 progress: progress
22047                         });
22048                 };
22049
22050                 Handler.prototype.visit = function(receiver, fulfilled, rejected, progress) {
22051                         this.chain(failIfRejected, receiver, fulfilled, rejected, progress);
22052                 };
22053
22054                 Handler.prototype.fold = function(f, z, c, to) {
22055                         this.when(new Fold(f, z, c, to));
22056                 };
22057
22058                 /**
22059                  * Handler that invokes fail() on any handler it becomes
22060                  * @constructor
22061                  */
22062                 function FailIfRejected() {}
22063
22064                 inherit(Handler, FailIfRejected);
22065
22066                 FailIfRejected.prototype.become = function(h) {
22067                         h.fail();
22068                 };
22069
22070                 var failIfRejected = new FailIfRejected();
22071
22072                 /**
22073                  * Handler that manages a queue of consumers waiting on a pending promise
22074                  * @constructor
22075                  */
22076                 function Pending(receiver, inheritedContext) {
22077                         Promise.createContext(this, inheritedContext);
22078
22079                         this.consumers = void 0;
22080                         this.receiver = receiver;
22081                         this.handler = void 0;
22082                         this.resolved = false;
22083                 }
22084
22085                 inherit(Handler, Pending);
22086
22087                 Pending.prototype._state = 0;
22088
22089                 Pending.prototype.resolve = function(x) {
22090                         this.become(getHandler(x));
22091                 };
22092
22093                 Pending.prototype.reject = function(x) {
22094                         if(this.resolved) {
22095                                 return;
22096                         }
22097
22098                         this.become(new Rejected(x));
22099                 };
22100
22101                 Pending.prototype.join = function() {
22102                         if (!this.resolved) {
22103                                 return this;
22104                         }
22105
22106                         var h = this;
22107
22108                         while (h.handler !== void 0) {
22109                                 h = h.handler;
22110                                 if (h === this) {
22111                                         return this.handler = cycle();
22112                                 }
22113                         }
22114
22115                         return h;
22116                 };
22117
22118                 Pending.prototype.run = function() {
22119                         var q = this.consumers;
22120                         var handler = this.handler;
22121                         this.handler = this.handler.join();
22122                         this.consumers = void 0;
22123
22124                         for (var i = 0; i < q.length; ++i) {
22125                                 handler.when(q[i]);
22126                         }
22127                 };
22128
22129                 Pending.prototype.become = function(handler) {
22130                         if(this.resolved) {
22131                                 return;
22132                         }
22133
22134                         this.resolved = true;
22135                         this.handler = handler;
22136                         if(this.consumers !== void 0) {
22137                                 tasks.enqueue(this);
22138                         }
22139
22140                         if(this.context !== void 0) {
22141                                 handler._report(this.context);
22142                         }
22143                 };
22144
22145                 Pending.prototype.when = function(continuation) {
22146                         if(this.resolved) {
22147                                 tasks.enqueue(new ContinuationTask(continuation, this.handler));
22148                         } else {
22149                                 if(this.consumers === void 0) {
22150                                         this.consumers = [continuation];
22151                                 } else {
22152                                         this.consumers.push(continuation);
22153                                 }
22154                         }
22155                 };
22156
22157                 /**
22158                  * @deprecated
22159                  */
22160                 Pending.prototype.notify = function(x) {
22161                         if(!this.resolved) {
22162                                 tasks.enqueue(new ProgressTask(x, this));
22163                         }
22164                 };
22165
22166                 Pending.prototype.fail = function(context) {
22167                         var c = typeof context === 'undefined' ? this.context : context;
22168                         this.resolved && this.handler.join().fail(c);
22169                 };
22170
22171                 Pending.prototype._report = function(context) {
22172                         this.resolved && this.handler.join()._report(context);
22173                 };
22174
22175                 Pending.prototype._unreport = function() {
22176                         this.resolved && this.handler.join()._unreport();
22177                 };
22178
22179                 /**
22180                  * Wrap another handler and force it into a future stack
22181                  * @param {object} handler
22182                  * @constructor
22183                  */
22184                 function Async(handler) {
22185                         this.handler = handler;
22186                 }
22187
22188                 inherit(Handler, Async);
22189
22190                 Async.prototype.when = function(continuation) {
22191                         tasks.enqueue(new ContinuationTask(continuation, this));
22192                 };
22193
22194                 Async.prototype._report = function(context) {
22195                         this.join()._report(context);
22196                 };
22197
22198                 Async.prototype._unreport = function() {
22199                         this.join()._unreport();
22200                 };
22201
22202                 /**
22203                  * Handler that wraps an untrusted thenable and assimilates it in a future stack
22204                  * @param {function} then
22205                  * @param {{then: function}} thenable
22206                  * @constructor
22207                  */
22208                 function Thenable(then, thenable) {
22209                         Pending.call(this);
22210                         tasks.enqueue(new AssimilateTask(then, thenable, this));
22211                 }
22212
22213                 inherit(Pending, Thenable);
22214
22215                 /**
22216                  * Handler for a fulfilled promise
22217                  * @param {*} x fulfillment value
22218                  * @constructor
22219                  */
22220                 function Fulfilled(x) {
22221                         Promise.createContext(this);
22222                         this.value = x;
22223                 }
22224
22225                 inherit(Handler, Fulfilled);
22226
22227                 Fulfilled.prototype._state = 1;
22228
22229                 Fulfilled.prototype.fold = function(f, z, c, to) {
22230                         runContinuation3(f, z, this, c, to);
22231                 };
22232
22233                 Fulfilled.prototype.when = function(cont) {
22234                         runContinuation1(cont.fulfilled, this, cont.receiver, cont.resolver);
22235                 };
22236
22237                 var errorId = 0;
22238
22239                 /**
22240                  * Handler for a rejected promise
22241                  * @param {*} x rejection reason
22242                  * @constructor
22243                  */
22244                 function Rejected(x) {
22245                         Promise.createContext(this);
22246
22247                         this.id = ++errorId;
22248                         this.value = x;
22249                         this.handled = false;
22250                         this.reported = false;
22251
22252                         this._report();
22253                 }
22254
22255                 inherit(Handler, Rejected);
22256
22257                 Rejected.prototype._state = -1;
22258
22259                 Rejected.prototype.fold = function(f, z, c, to) {
22260                         to.become(this);
22261                 };
22262
22263                 Rejected.prototype.when = function(cont) {
22264                         if(typeof cont.rejected === 'function') {
22265                                 this._unreport();
22266                         }
22267                         runContinuation1(cont.rejected, this, cont.receiver, cont.resolver);
22268                 };
22269
22270                 Rejected.prototype._report = function(context) {
22271                         tasks.afterQueue(new ReportTask(this, context));
22272                 };
22273
22274                 Rejected.prototype._unreport = function() {
22275                         if(this.handled) {
22276                                 return;
22277                         }
22278                         this.handled = true;
22279                         tasks.afterQueue(new UnreportTask(this));
22280                 };
22281
22282                 Rejected.prototype.fail = function(context) {
22283                         this.reported = true;
22284                         emitRejection('unhandledRejection', this);
22285                         Promise.onFatalRejection(this, context === void 0 ? this.context : context);
22286                 };
22287
22288                 function ReportTask(rejection, context) {
22289                         this.rejection = rejection;
22290                         this.context = context;
22291                 }
22292
22293                 ReportTask.prototype.run = function() {
22294                         if(!this.rejection.handled && !this.rejection.reported) {
22295                                 this.rejection.reported = true;
22296                                 emitRejection('unhandledRejection', this.rejection) ||
22297                                         Promise.onPotentiallyUnhandledRejection(this.rejection, this.context);
22298                         }
22299                 };
22300
22301                 function UnreportTask(rejection) {
22302                         this.rejection = rejection;
22303                 }
22304
22305                 UnreportTask.prototype.run = function() {
22306                         if(this.rejection.reported) {
22307                                 emitRejection('rejectionHandled', this.rejection) ||
22308                                         Promise.onPotentiallyUnhandledRejectionHandled(this.rejection);
22309                         }
22310                 };
22311
22312                 // Unhandled rejection hooks
22313                 // By default, everything is a noop
22314
22315                 Promise.createContext
22316                         = Promise.enterContext
22317                         = Promise.exitContext
22318                         = Promise.onPotentiallyUnhandledRejection
22319                         = Promise.onPotentiallyUnhandledRejectionHandled
22320                         = Promise.onFatalRejection
22321                         = noop;
22322
22323                 // Errors and singletons
22324
22325                 var foreverPendingHandler = new Handler();
22326                 var foreverPendingPromise = new Promise(Handler, foreverPendingHandler);
22327
22328                 function cycle() {
22329                         return new Rejected(new TypeError('Promise cycle'));
22330                 }
22331
22332                 // Task runners
22333
22334                 /**
22335                  * Run a single consumer
22336                  * @constructor
22337                  */
22338                 function ContinuationTask(continuation, handler) {
22339                         this.continuation = continuation;
22340                         this.handler = handler;
22341                 }
22342
22343                 ContinuationTask.prototype.run = function() {
22344                         this.handler.join().when(this.continuation);
22345                 };
22346
22347                 /**
22348                  * Run a queue of progress handlers
22349                  * @constructor
22350                  */
22351                 function ProgressTask(value, handler) {
22352                         this.handler = handler;
22353                         this.value = value;
22354                 }
22355
22356                 ProgressTask.prototype.run = function() {
22357                         var q = this.handler.consumers;
22358                         if(q === void 0) {
22359                                 return;
22360                         }
22361
22362                         for (var c, i = 0; i < q.length; ++i) {
22363                                 c = q[i];
22364                                 runNotify(c.progress, this.value, this.handler, c.receiver, c.resolver);
22365                         }
22366                 };
22367
22368                 /**
22369                  * Assimilate a thenable, sending it's value to resolver
22370                  * @param {function} then
22371                  * @param {object|function} thenable
22372                  * @param {object} resolver
22373                  * @constructor
22374                  */
22375                 function AssimilateTask(then, thenable, resolver) {
22376                         this._then = then;
22377                         this.thenable = thenable;
22378                         this.resolver = resolver;
22379                 }
22380
22381                 AssimilateTask.prototype.run = function() {
22382                         var h = this.resolver;
22383                         tryAssimilate(this._then, this.thenable, _resolve, _reject, _notify);
22384
22385                         function _resolve(x) { h.resolve(x); }
22386                         function _reject(x)  { h.reject(x); }
22387                         function _notify(x)  { h.notify(x); }
22388                 };
22389
22390                 function tryAssimilate(then, thenable, resolve, reject, notify) {
22391                         try {
22392                                 then.call(thenable, resolve, reject, notify);
22393                         } catch (e) {
22394                                 reject(e);
22395                         }
22396                 }
22397
22398                 /**
22399                  * Fold a handler value with z
22400                  * @constructor
22401                  */
22402                 function Fold(f, z, c, to) {
22403                         this.f = f; this.z = z; this.c = c; this.to = to;
22404                         this.resolver = failIfRejected;
22405                         this.receiver = this;
22406                 }
22407
22408                 Fold.prototype.fulfilled = function(x) {
22409                         this.f.call(this.c, this.z, x, this.to);
22410                 };
22411
22412                 Fold.prototype.rejected = function(x) {
22413                         this.to.reject(x);
22414                 };
22415
22416                 Fold.prototype.progress = function(x) {
22417                         this.to.notify(x);
22418                 };
22419
22420                 // Other helpers
22421
22422                 /**
22423                  * @param {*} x
22424                  * @returns {boolean} true iff x is a trusted Promise
22425                  */
22426                 function isPromise(x) {
22427                         return x instanceof Promise;
22428                 }
22429
22430                 /**
22431                  * Test just enough to rule out primitives, in order to take faster
22432                  * paths in some code
22433                  * @param {*} x
22434                  * @returns {boolean} false iff x is guaranteed *not* to be a thenable
22435                  */
22436                 function maybeThenable(x) {
22437                         return (typeof x === 'object' || typeof x === 'function') && x !== null;
22438                 }
22439
22440                 function runContinuation1(f, h, receiver, next) {
22441                         if(typeof f !== 'function') {
22442                                 return next.become(h);
22443                         }
22444
22445                         Promise.enterContext(h);
22446                         tryCatchReject(f, h.value, receiver, next);
22447                         Promise.exitContext();
22448                 }
22449
22450                 function runContinuation3(f, x, h, receiver, next) {
22451                         if(typeof f !== 'function') {
22452                                 return next.become(h);
22453                         }
22454
22455                         Promise.enterContext(h);
22456                         tryCatchReject3(f, x, h.value, receiver, next);
22457                         Promise.exitContext();
22458                 }
22459
22460                 /**
22461                  * @deprecated
22462                  */
22463                 function runNotify(f, x, h, receiver, next) {
22464                         if(typeof f !== 'function') {
22465                                 return next.notify(x);
22466                         }
22467
22468                         Promise.enterContext(h);
22469                         tryCatchReturn(f, x, receiver, next);
22470                         Promise.exitContext();
22471                 }
22472
22473                 function tryCatch2(f, a, b) {
22474                         try {
22475                                 return f(a, b);
22476                         } catch(e) {
22477                                 return reject(e);
22478                         }
22479                 }
22480
22481                 /**
22482                  * Return f.call(thisArg, x), or if it throws return a rejected promise for
22483                  * the thrown exception
22484                  */
22485                 function tryCatchReject(f, x, thisArg, next) {
22486                         try {
22487                                 next.become(getHandler(f.call(thisArg, x)));
22488                         } catch(e) {
22489                                 next.become(new Rejected(e));
22490                         }
22491                 }
22492
22493                 /**
22494                  * Same as above, but includes the extra argument parameter.
22495                  */
22496                 function tryCatchReject3(f, x, y, thisArg, next) {
22497                         try {
22498                                 f.call(thisArg, x, y, next);
22499                         } catch(e) {
22500                                 next.become(new Rejected(e));
22501                         }
22502                 }
22503
22504                 /**
22505                  * @deprecated
22506                  * Return f.call(thisArg, x), or if it throws, *return* the exception
22507                  */
22508                 function tryCatchReturn(f, x, thisArg, next) {
22509                         try {
22510                                 next.notify(f.call(thisArg, x));
22511                         } catch(e) {
22512                                 next.notify(e);
22513                         }
22514                 }
22515
22516                 function inherit(Parent, Child) {
22517                         Child.prototype = objectCreate(Parent.prototype);
22518                         Child.prototype.constructor = Child;
22519                 }
22520
22521                 function snd(x, y) {
22522                         return y;
22523                 }
22524
22525                 function noop() {}
22526
22527                 function hasCustomEvent() {
22528                         if(typeof CustomEvent === 'function') {
22529                                 try {
22530                                         var ev = new CustomEvent('unhandledRejection');
22531                                         return ev instanceof CustomEvent;
22532                                 } catch (ignoredException) {}
22533                         }
22534                         return false;
22535                 }
22536
22537                 function hasInternetExplorerCustomEvent() {
22538                         if(typeof document !== 'undefined' && typeof document.createEvent === 'function') {
22539                                 try {
22540                                         // Try to create one event to make sure it's supported
22541                                         var ev = document.createEvent('CustomEvent');
22542                                         ev.initCustomEvent('eventType', false, true, {});
22543                                         return true;
22544                                 } catch (ignoredException) {}
22545                         }
22546                         return false;
22547                 }
22548
22549                 function initEmitRejection() {
22550                         /*global process, self, CustomEvent*/
22551                         if(typeof process !== 'undefined' && process !== null
22552                                 && typeof process.emit === 'function') {
22553                                 // Returning falsy here means to call the default
22554                                 // onPotentiallyUnhandledRejection API.  This is safe even in
22555                                 // browserify since process.emit always returns falsy in browserify:
22556                                 // https://github.com/defunctzombie/node-process/blob/master/browser.js#L40-L46
22557                                 return function(type, rejection) {
22558                                         return type === 'unhandledRejection'
22559                                                 ? process.emit(type, rejection.value, rejection)
22560                                                 : process.emit(type, rejection);
22561                                 };
22562                         } else if(typeof self !== 'undefined' && hasCustomEvent()) {
22563                                 return (function (self, CustomEvent) {
22564                                         return function (type, rejection) {
22565                                                 var ev = new CustomEvent(type, {
22566                                                         detail: {
22567                                                                 reason: rejection.value,
22568                                                                 key: rejection
22569                                                         },
22570                                                         bubbles: false,
22571                                                         cancelable: true
22572                                                 });
22573
22574                                                 return !self.dispatchEvent(ev);
22575                                         };
22576                                 }(self, CustomEvent));
22577                         } else if(typeof self !== 'undefined' && hasInternetExplorerCustomEvent()) {
22578                                 return (function(self, document) {
22579                                         return function(type, rejection) {
22580                                                 var ev = document.createEvent('CustomEvent');
22581                                                 ev.initCustomEvent(type, false, true, {
22582                                                         reason: rejection.value,
22583                                                         key: rejection
22584                                                 });
22585
22586                                                 return !self.dispatchEvent(ev);
22587                                         };
22588                                 }(self, document));
22589                         }
22590
22591                         return noop;
22592                 }
22593
22594                 return Promise;
22595         };
22596 });
22597 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
22598
22599 }).call(this,require('_process'))
22600
22601 },{"_process":6}],287:[function(require,module,exports){
22602 /** @license MIT License (c) copyright 2010-2014 original author or authors */
22603 /** @author Brian Cavalier */
22604 /** @author John Hann */
22605
22606 (function(define) { 'use strict';
22607 define(function() {
22608
22609         return {
22610                 pending: toPendingState,
22611                 fulfilled: toFulfilledState,
22612                 rejected: toRejectedState,
22613                 inspect: inspect
22614         };
22615
22616         function toPendingState() {
22617                 return { state: 'pending' };
22618         }
22619
22620         function toRejectedState(e) {
22621                 return { state: 'rejected', reason: e };
22622         }
22623
22624         function toFulfilledState(x) {
22625                 return { state: 'fulfilled', value: x };
22626         }
22627
22628         function inspect(handler) {
22629                 var state = handler.state();
22630                 return state === 0 ? toPendingState()
22631                          : state > 0   ? toFulfilledState(handler.value)
22632                                        : toRejectedState(handler.value);
22633         }
22634
22635 });
22636 }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
22637
22638 },{}],288:[function(require,module,exports){
22639 /** @license MIT License (c) copyright 2010-2014 original author or authors */
22640
22641 /**
22642  * Promises/A+ and when() implementation
22643  * when is part of the cujoJS family of libraries (http://cujojs.com/)
22644  * @author Brian Cavalier
22645  * @author John Hann
22646  */
22647 (function(define) { 'use strict';
22648 define(function (require) {
22649
22650         var timed = require('./lib/decorators/timed');
22651         var array = require('./lib/decorators/array');
22652         var flow = require('./lib/decorators/flow');
22653         var fold = require('./lib/decorators/fold');
22654         var inspect = require('./lib/decorators/inspect');
22655         var generate = require('./lib/decorators/iterate');
22656         var progress = require('./lib/decorators/progress');
22657         var withThis = require('./lib/decorators/with');
22658         var unhandledRejection = require('./lib/decorators/unhandledRejection');
22659         var TimeoutError = require('./lib/TimeoutError');
22660
22661         var Promise = [array, flow, fold, generate, progress,
22662                 inspect, withThis, timed, unhandledRejection]
22663                 .reduce(function(Promise, feature) {
22664                         return feature(Promise);
22665                 }, require('./lib/Promise'));
22666
22667         var apply = require('./lib/apply')(Promise);
22668
22669         // Public API
22670
22671         when.promise     = promise;              // Create a pending promise
22672         when.resolve     = Promise.resolve;      // Create a resolved promise
22673         when.reject      = Promise.reject;       // Create a rejected promise
22674
22675         when.lift        = lift;                 // lift a function to return promises
22676         when['try']      = attempt;              // call a function and return a promise
22677         when.attempt     = attempt;              // alias for when.try
22678
22679         when.iterate     = Promise.iterate;      // DEPRECATED (use cujojs/most streams) Generate a stream of promises
22680         when.unfold      = Promise.unfold;       // DEPRECATED (use cujojs/most streams) Generate a stream of promises
22681
22682         when.join        = join;                 // Join 2 or more promises
22683
22684         when.all         = all;                  // Resolve a list of promises
22685         when.settle      = settle;               // Settle a list of promises
22686
22687         when.any         = lift(Promise.any);    // One-winner race
22688         when.some        = lift(Promise.some);   // Multi-winner race
22689         when.race        = lift(Promise.race);   // First-to-settle race
22690
22691         when.map         = map;                  // Array.map() for promises
22692         when.filter      = filter;               // Array.filter() for promises
22693         when.reduce      = lift(Promise.reduce);       // Array.reduce() for promises
22694         when.reduceRight = lift(Promise.reduceRight);  // Array.reduceRight() for promises
22695
22696         when.isPromiseLike = isPromiseLike;      // Is something promise-like, aka thenable
22697
22698         when.Promise     = Promise;              // Promise constructor
22699         when.defer       = defer;                // Create a {promise, resolve, reject} tuple
22700
22701         // Error types
22702
22703         when.TimeoutError = TimeoutError;
22704
22705         /**
22706          * Get a trusted promise for x, or by transforming x with onFulfilled
22707          *
22708          * @param {*} x
22709          * @param {function?} onFulfilled callback to be called when x is
22710          *   successfully fulfilled.  If promiseOrValue is an immediate value, callback
22711          *   will be invoked immediately.
22712          * @param {function?} onRejected callback to be called when x is
22713          *   rejected.
22714          * @param {function?} onProgress callback to be called when progress updates
22715          *   are issued for x. @deprecated
22716          * @returns {Promise} a new promise that will fulfill with the return
22717          *   value of callback or errback or the completion value of promiseOrValue if
22718          *   callback and/or errback is not supplied.
22719          */
22720         function when(x, onFulfilled, onRejected, onProgress) {
22721                 var p = Promise.resolve(x);
22722                 if (arguments.length < 2) {
22723                         return p;
22724                 }
22725
22726                 return p.then(onFulfilled, onRejected, onProgress);
22727         }
22728
22729         /**
22730          * Creates a new promise whose fate is determined by resolver.
22731          * @param {function} resolver function(resolve, reject, notify)
22732          * @returns {Promise} promise whose fate is determine by resolver
22733          */
22734         function promise(resolver) {
22735                 return new Promise(resolver);
22736         }
22737
22738         /**
22739          * Lift the supplied function, creating a version of f that returns
22740          * promises, and accepts promises as arguments.
22741          * @param {function} f
22742          * @returns {Function} version of f that returns promises
22743          */
22744         function lift(f) {
22745                 return function() {
22746                         for(var i=0, l=arguments.length, a=new Array(l); i<l; ++i) {
22747                                 a[i] = arguments[i];
22748                         }
22749                         return apply(f, this, a);
22750                 };
22751         }
22752
22753         /**
22754          * Call f in a future turn, with the supplied args, and return a promise
22755          * for the result.
22756          * @param {function} f
22757          * @returns {Promise}
22758          */
22759         function attempt(f /*, args... */) {
22760                 /*jshint validthis:true */
22761                 for(var i=0, l=arguments.length-1, a=new Array(l); i<l; ++i) {
22762                         a[i] = arguments[i+1];
22763                 }
22764                 return apply(f, this, a);
22765         }
22766
22767         /**
22768          * Creates a {promise, resolver} pair, either or both of which
22769          * may be given out safely to consumers.
22770          * @return {{promise: Promise, resolve: function, reject: function, notify: function}}
22771          */
22772         function defer() {
22773                 return new Deferred();
22774         }
22775
22776         function Deferred() {
22777                 var p = Promise._defer();
22778
22779                 function resolve(x) { p._handler.resolve(x); }
22780                 function reject(x) { p._handler.reject(x); }
22781                 function notify(x) { p._handler.notify(x); }
22782
22783                 this.promise = p;
22784                 this.resolve = resolve;
22785                 this.reject = reject;
22786                 this.notify = notify;
22787                 this.resolver = { resolve: resolve, reject: reject, notify: notify };
22788         }
22789
22790         /**
22791          * Determines if x is promise-like, i.e. a thenable object
22792          * NOTE: Will return true for *any thenable object*, and isn't truly
22793          * safe, since it may attempt to access the `then` property of x (i.e.
22794          *  clever/malicious getters may do weird things)
22795          * @param {*} x anything
22796          * @returns {boolean} true if x is promise-like
22797          */
22798         function isPromiseLike(x) {
22799                 return x && typeof x.then === 'function';
22800         }
22801
22802         /**
22803          * Return a promise that will resolve only once all the supplied arguments
22804          * have resolved. The resolution value of the returned promise will be an array
22805          * containing the resolution values of each of the arguments.
22806          * @param {...*} arguments may be a mix of promises and values
22807          * @returns {Promise}
22808          */
22809         function join(/* ...promises */) {
22810                 return Promise.all(arguments);
22811         }
22812
22813         /**
22814          * Return a promise that will fulfill once all input promises have
22815          * fulfilled, or reject when any one input promise rejects.
22816          * @param {array|Promise} promises array (or promise for an array) of promises
22817          * @returns {Promise}
22818          */
22819         function all(promises) {
22820                 return when(promises, Promise.all);
22821         }
22822
22823         /**
22824          * Return a promise that will always fulfill with an array containing
22825          * the outcome states of all input promises.  The returned promise
22826          * will only reject if `promises` itself is a rejected promise.
22827          * @param {array|Promise} promises array (or promise for an array) of promises
22828          * @returns {Promise} promise for array of settled state descriptors
22829          */
22830         function settle(promises) {
22831                 return when(promises, Promise.settle);
22832         }
22833
22834         /**
22835          * Promise-aware array map function, similar to `Array.prototype.map()`,
22836          * but input array may contain promises or values.
22837          * @param {Array|Promise} promises array of anything, may contain promises and values
22838          * @param {function(x:*, index:Number):*} mapFunc map function which may
22839          *  return a promise or value
22840          * @returns {Promise} promise that will fulfill with an array of mapped values
22841          *  or reject if any input promise rejects.
22842          */
22843         function map(promises, mapFunc) {
22844                 return when(promises, function(promises) {
22845                         return Promise.map(promises, mapFunc);
22846                 });
22847         }
22848
22849         /**
22850          * Filter the provided array of promises using the provided predicate.  Input may
22851          * contain promises and values
22852          * @param {Array|Promise} promises array of promises and values
22853          * @param {function(x:*, index:Number):boolean} predicate filtering predicate.
22854          *  Must return truthy (or promise for truthy) for items to retain.
22855          * @returns {Promise} promise that will fulfill with an array containing all items
22856          *  for which predicate returned truthy.
22857          */
22858         function filter(promises, predicate) {
22859                 return when(promises, function(promises) {
22860                         return Promise.filter(promises, predicate);
22861                 });
22862         }
22863
22864         return when;
22865 });
22866 })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
22867
22868 },{"./lib/Promise":271,"./lib/TimeoutError":273,"./lib/apply":274,"./lib/decorators/array":275,"./lib/decorators/flow":276,"./lib/decorators/fold":277,"./lib/decorators/inspect":278,"./lib/decorators/iterate":279,"./lib/decorators/progress":280,"./lib/decorators/timed":281,"./lib/decorators/unhandledRejection":282,"./lib/decorators/with":283}],289:[function(require,module,exports){
22869 var nativeIsArray = Array.isArray
22870 var toString = Object.prototype.toString
22871
22872 module.exports = nativeIsArray || isArray
22873
22874 function isArray(obj) {
22875     return toString.call(obj) === "[object Array]"
22876 }
22877
22878 },{}],290:[function(require,module,exports){
22879 "use strict";
22880 Object.defineProperty(exports, "__esModule", { value: true });
22881 var APIv3_1 = require("./api/APIv3");
22882 exports.APIv3 = APIv3_1.APIv3;
22883 var ModelCreator_1 = require("./api/ModelCreator");
22884 exports.ModelCreator = ModelCreator_1.ModelCreator;
22885
22886 },{"./api/APIv3":303,"./api/ModelCreator":304}],291:[function(require,module,exports){
22887 "use strict";
22888 function __export(m) {
22889     for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
22890 }
22891 Object.defineProperty(exports, "__esModule", { value: true });
22892 var Component_1 = require("./component/Component");
22893 exports.Component = Component_1.Component;
22894 var ComponentService_1 = require("./component/ComponentService");
22895 exports.ComponentService = ComponentService_1.ComponentService;
22896 var HandlerBase_1 = require("./component/utils/HandlerBase");
22897 exports.HandlerBase = HandlerBase_1.HandlerBase;
22898 var AttributionComponent_1 = require("./component/AttributionComponent");
22899 exports.AttributionComponent = AttributionComponent_1.AttributionComponent;
22900 var BackgroundComponent_1 = require("./component/BackgroundComponent");
22901 exports.BackgroundComponent = BackgroundComponent_1.BackgroundComponent;
22902 var BearingComponent_1 = require("./component/BearingComponent");
22903 exports.BearingComponent = BearingComponent_1.BearingComponent;
22904 var CacheComponent_1 = require("./component/CacheComponent");
22905 exports.CacheComponent = CacheComponent_1.CacheComponent;
22906 var CoverComponent_1 = require("./component/CoverComponent");
22907 exports.CoverComponent = CoverComponent_1.CoverComponent;
22908 var DebugComponent_1 = require("./component/DebugComponent");
22909 exports.DebugComponent = DebugComponent_1.DebugComponent;
22910 var DirectionComponent_1 = require("./component/direction/DirectionComponent");
22911 exports.DirectionComponent = DirectionComponent_1.DirectionComponent;
22912 var DirectionDOMCalculator_1 = require("./component/direction/DirectionDOMCalculator");
22913 exports.DirectionDOMCalculator = DirectionDOMCalculator_1.DirectionDOMCalculator;
22914 var DirectionDOMRenderer_1 = require("./component/direction/DirectionDOMRenderer");
22915 exports.DirectionDOMRenderer = DirectionDOMRenderer_1.DirectionDOMRenderer;
22916 var ImageComponent_1 = require("./component/ImageComponent");
22917 exports.ImageComponent = ImageComponent_1.ImageComponent;
22918 var KeyboardComponent_1 = require("./component/keyboard/KeyboardComponent");
22919 exports.KeyboardComponent = KeyboardComponent_1.KeyboardComponent;
22920 var KeyPlayHandler_1 = require("./component/keyboard/KeyPlayHandler");
22921 exports.KeyPlayHandler = KeyPlayHandler_1.KeyPlayHandler;
22922 var KeyZoomHandler_1 = require("./component/keyboard/KeyZoomHandler");
22923 exports.KeyZoomHandler = KeyZoomHandler_1.KeyZoomHandler;
22924 var KeySequenceNavigationHandler_1 = require("./component/keyboard/KeySequenceNavigationHandler");
22925 exports.KeySequenceNavigationHandler = KeySequenceNavigationHandler_1.KeySequenceNavigationHandler;
22926 var KeySpatialNavigationHandler_1 = require("./component/keyboard/KeySpatialNavigationHandler");
22927 exports.KeySpatialNavigationHandler = KeySpatialNavigationHandler_1.KeySpatialNavigationHandler;
22928 var LoadingComponent_1 = require("./component/LoadingComponent");
22929 exports.LoadingComponent = LoadingComponent_1.LoadingComponent;
22930 var Marker_1 = require("./component/marker/marker/Marker");
22931 exports.Marker = Marker_1.Marker;
22932 var MarkerComponent_1 = require("./component/marker/MarkerComponent");
22933 exports.MarkerComponent = MarkerComponent_1.MarkerComponent;
22934 var MarkerScene_1 = require("./component/marker/MarkerScene");
22935 exports.MarkerScene = MarkerScene_1.MarkerScene;
22936 var MarkerSet_1 = require("./component/marker/MarkerSet");
22937 exports.MarkerSet = MarkerSet_1.MarkerSet;
22938 var MouseComponent_1 = require("./component/mouse/MouseComponent");
22939 exports.MouseComponent = MouseComponent_1.MouseComponent;
22940 var BounceHandler_1 = require("./component/mouse/BounceHandler");
22941 exports.BounceHandler = BounceHandler_1.BounceHandler;
22942 var DragPanHandler_1 = require("./component/mouse/DragPanHandler");
22943 exports.DragPanHandler = DragPanHandler_1.DragPanHandler;
22944 var DoubleClickZoomHandler_1 = require("./component/mouse/DoubleClickZoomHandler");
22945 exports.DoubleClickZoomHandler = DoubleClickZoomHandler_1.DoubleClickZoomHandler;
22946 var ScrollZoomHandler_1 = require("./component/mouse/ScrollZoomHandler");
22947 exports.ScrollZoomHandler = ScrollZoomHandler_1.ScrollZoomHandler;
22948 var TouchZoomHandler_1 = require("./component/mouse/TouchZoomHandler");
22949 exports.TouchZoomHandler = TouchZoomHandler_1.TouchZoomHandler;
22950 var Popup_1 = require("./component/popup/popup/Popup");
22951 exports.Popup = Popup_1.Popup;
22952 var PopupComponent_1 = require("./component/popup/PopupComponent");
22953 exports.PopupComponent = PopupComponent_1.PopupComponent;
22954 var NavigationComponent_1 = require("./component/NavigationComponent");
22955 exports.NavigationComponent = NavigationComponent_1.NavigationComponent;
22956 var RouteComponent_1 = require("./component/RouteComponent");
22957 exports.RouteComponent = RouteComponent_1.RouteComponent;
22958 var SequenceComponent_1 = require("./component/sequence/SequenceComponent");
22959 exports.SequenceComponent = SequenceComponent_1.SequenceComponent;
22960 var SequenceDOMRenderer_1 = require("./component/sequence/SequenceDOMRenderer");
22961 exports.SequenceDOMRenderer = SequenceDOMRenderer_1.SequenceDOMRenderer;
22962 var SequenceMode_1 = require("./component/sequence/SequenceMode");
22963 exports.SequenceMode = SequenceMode_1.SequenceMode;
22964 var ImagePlaneComponent_1 = require("./component/imageplane/ImagePlaneComponent");
22965 exports.ImagePlaneComponent = ImagePlaneComponent_1.ImagePlaneComponent;
22966 var ImagePlaneFactory_1 = require("./component/imageplane/ImagePlaneFactory");
22967 exports.ImagePlaneFactory = ImagePlaneFactory_1.ImagePlaneFactory;
22968 var ImagePlaneGLRenderer_1 = require("./component/imageplane/ImagePlaneGLRenderer");
22969 exports.ImagePlaneGLRenderer = ImagePlaneGLRenderer_1.ImagePlaneGLRenderer;
22970 var ImagePlaneScene_1 = require("./component/imageplane/ImagePlaneScene");
22971 exports.ImagePlaneScene = ImagePlaneScene_1.ImagePlaneScene;
22972 var ImagePlaneShaders_1 = require("./component/imageplane/ImagePlaneShaders");
22973 exports.ImagePlaneShaders = ImagePlaneShaders_1.ImagePlaneShaders;
22974 var SimpleMarker_1 = require("./component/marker/marker/SimpleMarker");
22975 exports.SimpleMarker = SimpleMarker_1.SimpleMarker;
22976 var CircleMarker_1 = require("./component/marker/marker/CircleMarker");
22977 exports.CircleMarker = CircleMarker_1.CircleMarker;
22978 var SliderComponent_1 = require("./component/imageplane/SliderComponent");
22979 exports.SliderComponent = SliderComponent_1.SliderComponent;
22980 var StatsComponent_1 = require("./component/StatsComponent");
22981 exports.StatsComponent = StatsComponent_1.StatsComponent;
22982 var TagHandlerBase_1 = require("./component/tag/handlers/TagHandlerBase");
22983 exports.TagHandlerBase = TagHandlerBase_1.TagHandlerBase;
22984 var CreateHandlerBase_1 = require("./component/tag/handlers/CreateHandlerBase");
22985 exports.CreateHandlerBase = CreateHandlerBase_1.CreateHandlerBase;
22986 var CreatePointHandler_1 = require("./component/tag/handlers/CreatePointHandler");
22987 exports.CreatePointHandler = CreatePointHandler_1.CreatePointHandler;
22988 var CreateVertexHandler_1 = require("./component/tag/handlers/CreateVertexHandler");
22989 exports.CreateVertexHandler = CreateVertexHandler_1.CreateVertexHandler;
22990 var CreatePolygonHandler_1 = require("./component/tag/handlers/CreatePolygonHandler");
22991 exports.CreatePolygonHandler = CreatePolygonHandler_1.CreatePolygonHandler;
22992 var CreateRectHandler_1 = require("./component/tag/handlers/CreateRectHandler");
22993 exports.CreateRectHandler = CreateRectHandler_1.CreateRectHandler;
22994 var CreateRectDragHandler_1 = require("./component/tag/handlers/CreateRectDragHandler");
22995 exports.CreateRectDragHandler = CreateRectDragHandler_1.CreateRectDragHandler;
22996 var EditVertexHandler_1 = require("./component/tag/handlers/EditVertexHandler");
22997 exports.EditVertexHandler = EditVertexHandler_1.EditVertexHandler;
22998 var Tag_1 = require("./component/tag/tag/Tag");
22999 exports.Tag = Tag_1.Tag;
23000 var OutlineTag_1 = require("./component/tag/tag/OutlineTag");
23001 exports.OutlineTag = OutlineTag_1.OutlineTag;
23002 var RenderTag_1 = require("./component/tag/tag/RenderTag");
23003 exports.RenderTag = RenderTag_1.RenderTag;
23004 var OutlineRenderTag_1 = require("./component/tag/tag/OutlineRenderTag");
23005 exports.OutlineRenderTag = OutlineRenderTag_1.OutlineRenderTag;
23006 var OutlineCreateTag_1 = require("./component/tag/tag/OutlineCreateTag");
23007 exports.OutlineCreateTag = OutlineCreateTag_1.OutlineCreateTag;
23008 var SpotTag_1 = require("./component/tag/tag/SpotTag");
23009 exports.SpotTag = SpotTag_1.SpotTag;
23010 var SpotRenderTag_1 = require("./component/tag/tag/SpotRenderTag");
23011 exports.SpotRenderTag = SpotRenderTag_1.SpotRenderTag;
23012 var TagComponent_1 = require("./component/tag/TagComponent");
23013 exports.TagComponent = TagComponent_1.TagComponent;
23014 var TagCreator_1 = require("./component/tag/TagCreator");
23015 exports.TagCreator = TagCreator_1.TagCreator;
23016 var TagDOMRenderer_1 = require("./component/tag/TagDOMRenderer");
23017 exports.TagDOMRenderer = TagDOMRenderer_1.TagDOMRenderer;
23018 var TagMode_1 = require("./component/tag/TagMode");
23019 exports.TagMode = TagMode_1.TagMode;
23020 var TagOperation_1 = require("./component/tag/TagOperation");
23021 exports.TagOperation = TagOperation_1.TagOperation;
23022 var TagScene_1 = require("./component/tag/TagScene");
23023 exports.TagScene = TagScene_1.TagScene;
23024 var TagSet_1 = require("./component/tag/TagSet");
23025 exports.TagSet = TagSet_1.TagSet;
23026 var Geometry_1 = require("./component/tag/geometry/Geometry");
23027 exports.Geometry = Geometry_1.Geometry;
23028 var VertexGeometry_1 = require("./component/tag/geometry/VertexGeometry");
23029 exports.VertexGeometry = VertexGeometry_1.VertexGeometry;
23030 var RectGeometry_1 = require("./component/tag/geometry/RectGeometry");
23031 exports.RectGeometry = RectGeometry_1.RectGeometry;
23032 var PointGeometry_1 = require("./component/tag/geometry/PointGeometry");
23033 exports.PointGeometry = PointGeometry_1.PointGeometry;
23034 var PolygonGeometry_1 = require("./component/tag/geometry/PolygonGeometry");
23035 exports.PolygonGeometry = PolygonGeometry_1.PolygonGeometry;
23036 var GeometryTagError_1 = require("./component/tag/error/GeometryTagError");
23037 exports.GeometryTagError = GeometryTagError_1.GeometryTagError;
23038 __export(require("./component/interfaces/interfaces"));
23039
23040 },{"./component/AttributionComponent":305,"./component/BackgroundComponent":306,"./component/BearingComponent":307,"./component/CacheComponent":308,"./component/Component":309,"./component/ComponentService":310,"./component/CoverComponent":311,"./component/DebugComponent":312,"./component/ImageComponent":313,"./component/LoadingComponent":314,"./component/NavigationComponent":315,"./component/RouteComponent":316,"./component/StatsComponent":317,"./component/direction/DirectionComponent":318,"./component/direction/DirectionDOMCalculator":319,"./component/direction/DirectionDOMRenderer":320,"./component/imageplane/ImagePlaneComponent":321,"./component/imageplane/ImagePlaneFactory":322,"./component/imageplane/ImagePlaneGLRenderer":323,"./component/imageplane/ImagePlaneScene":324,"./component/imageplane/ImagePlaneShaders":325,"./component/imageplane/SliderComponent":326,"./component/interfaces/interfaces":328,"./component/keyboard/KeyPlayHandler":329,"./component/keyboard/KeySequenceNavigationHandler":330,"./component/keyboard/KeySpatialNavigationHandler":331,"./component/keyboard/KeyZoomHandler":332,"./component/keyboard/KeyboardComponent":333,"./component/marker/MarkerComponent":335,"./component/marker/MarkerScene":336,"./component/marker/MarkerSet":337,"./component/marker/marker/CircleMarker":338,"./component/marker/marker/Marker":339,"./component/marker/marker/SimpleMarker":340,"./component/mouse/BounceHandler":341,"./component/mouse/DoubleClickZoomHandler":342,"./component/mouse/DragPanHandler":343,"./component/mouse/MouseComponent":344,"./component/mouse/ScrollZoomHandler":345,"./component/mouse/TouchZoomHandler":346,"./component/popup/PopupComponent":348,"./component/popup/popup/Popup":349,"./component/sequence/SequenceComponent":350,"./component/sequence/SequenceDOMRenderer":351,"./component/sequence/SequenceMode":352,"./component/tag/TagComponent":354,"./component/tag/TagCreator":355,"./component/tag/TagDOMRenderer":356,"./component/tag/TagMode":357,"./component/tag/TagOperation":358,"./component/tag/TagScene":359,"./component/tag/TagSet":360,"./component/tag/error/GeometryTagError":361,"./component/tag/geometry/Geometry":362,"./component/tag/geometry/PointGeometry":363,"./component/tag/geometry/PolygonGeometry":364,"./component/tag/geometry/RectGeometry":365,"./component/tag/geometry/VertexGeometry":366,"./component/tag/handlers/CreateHandlerBase":367,"./component/tag/handlers/CreatePointHandler":368,"./component/tag/handlers/CreatePolygonHandler":369,"./component/tag/handlers/CreateRectDragHandler":370,"./component/tag/handlers/CreateRectHandler":371,"./component/tag/handlers/CreateVertexHandler":372,"./component/tag/handlers/EditVertexHandler":373,"./component/tag/handlers/TagHandlerBase":374,"./component/tag/tag/OutlineCreateTag":375,"./component/tag/tag/OutlineRenderTag":376,"./component/tag/tag/OutlineTag":377,"./component/tag/tag/RenderTag":378,"./component/tag/tag/SpotRenderTag":379,"./component/tag/tag/SpotTag":380,"./component/tag/tag/Tag":381,"./component/utils/HandlerBase":382}],292:[function(require,module,exports){
23041 "use strict";
23042 Object.defineProperty(exports, "__esModule", { value: true });
23043 var EdgeDirection_1 = require("./graph/edge/EdgeDirection");
23044 exports.EdgeDirection = EdgeDirection_1.EdgeDirection;
23045 var EdgeCalculatorSettings_1 = require("./graph/edge/EdgeCalculatorSettings");
23046 exports.EdgeCalculatorSettings = EdgeCalculatorSettings_1.EdgeCalculatorSettings;
23047 var EdgeCalculatorDirections_1 = require("./graph/edge/EdgeCalculatorDirections");
23048 exports.EdgeCalculatorDirections = EdgeCalculatorDirections_1.EdgeCalculatorDirections;
23049 var EdgeCalculatorCoefficients_1 = require("./graph/edge/EdgeCalculatorCoefficients");
23050 exports.EdgeCalculatorCoefficients = EdgeCalculatorCoefficients_1.EdgeCalculatorCoefficients;
23051 var EdgeCalculator_1 = require("./graph/edge/EdgeCalculator");
23052 exports.EdgeCalculator = EdgeCalculator_1.EdgeCalculator;
23053
23054 },{"./graph/edge/EdgeCalculator":402,"./graph/edge/EdgeCalculatorCoefficients":403,"./graph/edge/EdgeCalculatorDirections":404,"./graph/edge/EdgeCalculatorSettings":405,"./graph/edge/EdgeDirection":406}],293:[function(require,module,exports){
23055 "use strict";
23056 Object.defineProperty(exports, "__esModule", { value: true });
23057 var AbortMapillaryError_1 = require("./error/AbortMapillaryError");
23058 exports.AbortMapillaryError = AbortMapillaryError_1.AbortMapillaryError;
23059 var ArgumentMapillaryError_1 = require("./error/ArgumentMapillaryError");
23060 exports.ArgumentMapillaryError = ArgumentMapillaryError_1.ArgumentMapillaryError;
23061 var GraphMapillaryError_1 = require("./error/GraphMapillaryError");
23062 exports.GraphMapillaryError = GraphMapillaryError_1.GraphMapillaryError;
23063 var MapillaryError_1 = require("./error/MapillaryError");
23064 exports.MapillaryError = MapillaryError_1.MapillaryError;
23065
23066 },{"./error/AbortMapillaryError":383,"./error/ArgumentMapillaryError":384,"./error/GraphMapillaryError":385,"./error/MapillaryError":386}],294:[function(require,module,exports){
23067 "use strict";
23068 Object.defineProperty(exports, "__esModule", { value: true });
23069 var Camera_1 = require("./geo/Camera");
23070 exports.Camera = Camera_1.Camera;
23071 var GeoCoords_1 = require("./geo/GeoCoords");
23072 exports.GeoCoords = GeoCoords_1.GeoCoords;
23073 var ViewportCoords_1 = require("./geo/ViewportCoords");
23074 exports.ViewportCoords = ViewportCoords_1.ViewportCoords;
23075 var Spatial_1 = require("./geo/Spatial");
23076 exports.Spatial = Spatial_1.Spatial;
23077 var Transform_1 = require("./geo/Transform");
23078 exports.Transform = Transform_1.Transform;
23079
23080 },{"./geo/Camera":387,"./geo/GeoCoords":388,"./geo/Spatial":389,"./geo/Transform":390,"./geo/ViewportCoords":391}],295:[function(require,module,exports){
23081 "use strict";
23082 Object.defineProperty(exports, "__esModule", { value: true });
23083 var FilterCreator_1 = require("./graph/FilterCreator");
23084 exports.FilterCreator = FilterCreator_1.FilterCreator;
23085 var Graph_1 = require("./graph/Graph");
23086 exports.Graph = Graph_1.Graph;
23087 var GraphCalculator_1 = require("./graph/GraphCalculator");
23088 exports.GraphCalculator = GraphCalculator_1.GraphCalculator;
23089 var GraphMode_1 = require("./graph/GraphMode");
23090 exports.GraphMode = GraphMode_1.GraphMode;
23091 var GraphService_1 = require("./graph/GraphService");
23092 exports.GraphService = GraphService_1.GraphService;
23093 var ImageLoadingService_1 = require("./graph/ImageLoadingService");
23094 exports.ImageLoadingService = ImageLoadingService_1.ImageLoadingService;
23095 var MeshReader_1 = require("./graph/MeshReader");
23096 exports.MeshReader = MeshReader_1.MeshReader;
23097 var Node_1 = require("./graph/Node");
23098 exports.Node = Node_1.Node;
23099 var NodeCache_1 = require("./graph/NodeCache");
23100 exports.NodeCache = NodeCache_1.NodeCache;
23101 var Sequence_1 = require("./graph/Sequence");
23102 exports.Sequence = Sequence_1.Sequence;
23103
23104 },{"./graph/FilterCreator":392,"./graph/Graph":393,"./graph/GraphCalculator":394,"./graph/GraphMode":395,"./graph/GraphService":396,"./graph/ImageLoadingService":397,"./graph/MeshReader":398,"./graph/Node":399,"./graph/NodeCache":400,"./graph/Sequence":401}],296:[function(require,module,exports){
23105 "use strict";
23106 /**
23107  * MapillaryJS is a WebGL JavaScript library for exploring street level imagery
23108  * @name Mapillary
23109  */
23110 function __export(m) {
23111     for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
23112 }
23113 Object.defineProperty(exports, "__esModule", { value: true });
23114 __export(require("./Support"));
23115 var Edge_1 = require("./Edge");
23116 exports.EdgeDirection = Edge_1.EdgeDirection;
23117 var Render_1 = require("./Render");
23118 exports.RenderMode = Render_1.RenderMode;
23119 var State_1 = require("./State");
23120 exports.TransitionMode = State_1.TransitionMode;
23121 var Viewer_1 = require("./Viewer");
23122 exports.Alignment = Viewer_1.Alignment;
23123 exports.ImageSize = Viewer_1.ImageSize;
23124 exports.Viewer = Viewer_1.Viewer;
23125 var TagComponent = require("./component/tag/Tag");
23126 exports.TagComponent = TagComponent;
23127 var MarkerComponent = require("./component/marker/Marker");
23128 exports.MarkerComponent = MarkerComponent;
23129 var PopupComponent = require("./component/popup/Popup");
23130 exports.PopupComponent = PopupComponent;
23131
23132 },{"./Edge":292,"./Render":297,"./State":298,"./Support":299,"./Viewer":302,"./component/marker/Marker":334,"./component/popup/Popup":347,"./component/tag/Tag":353}],297:[function(require,module,exports){
23133 "use strict";
23134 Object.defineProperty(exports, "__esModule", { value: true });
23135 var DOMRenderer_1 = require("./render/DOMRenderer");
23136 exports.DOMRenderer = DOMRenderer_1.DOMRenderer;
23137 var GLRenderer_1 = require("./render/GLRenderer");
23138 exports.GLRenderer = GLRenderer_1.GLRenderer;
23139 var GLRenderStage_1 = require("./render/GLRenderStage");
23140 exports.GLRenderStage = GLRenderStage_1.GLRenderStage;
23141 var RenderCamera_1 = require("./render/RenderCamera");
23142 exports.RenderCamera = RenderCamera_1.RenderCamera;
23143 var RenderMode_1 = require("./render/RenderMode");
23144 exports.RenderMode = RenderMode_1.RenderMode;
23145 var RenderService_1 = require("./render/RenderService");
23146 exports.RenderService = RenderService_1.RenderService;
23147
23148 },{"./render/DOMRenderer":407,"./render/GLRenderStage":408,"./render/GLRenderer":409,"./render/RenderCamera":410,"./render/RenderMode":411,"./render/RenderService":412}],298:[function(require,module,exports){
23149 "use strict";
23150 Object.defineProperty(exports, "__esModule", { value: true });
23151 var State_1 = require("./state/State");
23152 exports.State = State_1.State;
23153 var StateBase_1 = require("./state/states/StateBase");
23154 exports.StateBase = StateBase_1.StateBase;
23155 var StateContext_1 = require("./state/StateContext");
23156 exports.StateContext = StateContext_1.StateContext;
23157 var StateService_1 = require("./state/StateService");
23158 exports.StateService = StateService_1.StateService;
23159 var TransitionMode_1 = require("./state/TransitionMode");
23160 exports.TransitionMode = TransitionMode_1.TransitionMode;
23161 var TraversingState_1 = require("./state/states/TraversingState");
23162 exports.TraversingState = TraversingState_1.TraversingState;
23163 var WaitingState_1 = require("./state/states/WaitingState");
23164 exports.WaitingState = WaitingState_1.WaitingState;
23165
23166 },{"./state/State":413,"./state/StateContext":414,"./state/StateService":415,"./state/TransitionMode":416,"./state/states/StateBase":417,"./state/states/TraversingState":418,"./state/states/WaitingState":419}],299:[function(require,module,exports){
23167 "use strict";
23168 Object.defineProperty(exports, "__esModule", { value: true });
23169 var support = require("./utils/Support");
23170 /**
23171  * Test whether the current browser supports the full
23172  * functionality of MapillaryJS.
23173  *
23174  * @description The full functionality includes WebGL rendering.
23175  *
23176  * @return {boolean}
23177  *
23178  * @example `var supported = Mapillary.isSupported();`
23179  */
23180 function isSupported() {
23181     return isFallbackSupported() &&
23182         support.isWebGLSupportedCached();
23183 }
23184 exports.isSupported = isSupported;
23185 /**
23186  * Test whether the current browser supports the fallback
23187  * functionality of MapillaryJS.
23188  *
23189  * @description The fallback functionality does not include WebGL
23190  * rendering, only 2D canvas rendering.
23191  *
23192  * @return {boolean}
23193  *
23194  * @example `var fallbackSupported = Mapillary.isFallbackSupported();`
23195  */
23196 function isFallbackSupported() {
23197     return support.isBrowser() &&
23198         support.isArraySupported() &&
23199         support.isFunctionSupported() &&
23200         support.isJSONSupported() &&
23201         support.isObjectSupported();
23202 }
23203 exports.isFallbackSupported = isFallbackSupported;
23204
23205 },{"./utils/Support":427}],300:[function(require,module,exports){
23206 "use strict";
23207 Object.defineProperty(exports, "__esModule", { value: true });
23208 var ImageTileLoader_1 = require("./tiles/ImageTileLoader");
23209 exports.ImageTileLoader = ImageTileLoader_1.ImageTileLoader;
23210 var ImageTileStore_1 = require("./tiles/ImageTileStore");
23211 exports.ImageTileStore = ImageTileStore_1.ImageTileStore;
23212 var TextureProvider_1 = require("./tiles/TextureProvider");
23213 exports.TextureProvider = TextureProvider_1.TextureProvider;
23214 var RegionOfInterestCalculator_1 = require("./tiles/RegionOfInterestCalculator");
23215 exports.RegionOfInterestCalculator = RegionOfInterestCalculator_1.RegionOfInterestCalculator;
23216
23217 },{"./tiles/ImageTileLoader":420,"./tiles/ImageTileStore":421,"./tiles/RegionOfInterestCalculator":422,"./tiles/TextureProvider":423}],301:[function(require,module,exports){
23218 "use strict";
23219 function __export(m) {
23220     for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
23221 }
23222 Object.defineProperty(exports, "__esModule", { value: true });
23223 var DOM_1 = require("./utils/DOM");
23224 exports.DOM = DOM_1.DOM;
23225 var EventEmitter_1 = require("./utils/EventEmitter");
23226 exports.EventEmitter = EventEmitter_1.EventEmitter;
23227 var Settings_1 = require("./utils/Settings");
23228 exports.Settings = Settings_1.Settings;
23229 __export(require("./utils/Support"));
23230 var Urls_1 = require("./utils/Urls");
23231 exports.Urls = Urls_1.Urls;
23232
23233 },{"./utils/DOM":424,"./utils/EventEmitter":425,"./utils/Settings":426,"./utils/Support":427,"./utils/Urls":428}],302:[function(require,module,exports){
23234 "use strict";
23235 Object.defineProperty(exports, "__esModule", { value: true });
23236 var Alignment_1 = require("./viewer/Alignment");
23237 exports.Alignment = Alignment_1.Alignment;
23238 var CacheService_1 = require("./viewer/CacheService");
23239 exports.CacheService = CacheService_1.CacheService;
23240 var ComponentController_1 = require("./viewer/ComponentController");
23241 exports.ComponentController = ComponentController_1.ComponentController;
23242 var Container_1 = require("./viewer/Container");
23243 exports.Container = Container_1.Container;
23244 var Observer_1 = require("./viewer/Observer");
23245 exports.Observer = Observer_1.Observer;
23246 var ImageSize_1 = require("./viewer/ImageSize");
23247 exports.ImageSize = ImageSize_1.ImageSize;
23248 var KeyboardService_1 = require("./viewer/KeyboardService");
23249 exports.KeyboardService = KeyboardService_1.KeyboardService;
23250 var LoadingService_1 = require("./viewer/LoadingService");
23251 exports.LoadingService = LoadingService_1.LoadingService;
23252 var MouseService_1 = require("./viewer/MouseService");
23253 exports.MouseService = MouseService_1.MouseService;
23254 var Navigator_1 = require("./viewer/Navigator");
23255 exports.Navigator = Navigator_1.Navigator;
23256 var PlayService_1 = require("./viewer/PlayService");
23257 exports.PlayService = PlayService_1.PlayService;
23258 var Projection_1 = require("./viewer/Projection");
23259 exports.Projection = Projection_1.Projection;
23260 var SpriteService_1 = require("./viewer/SpriteService");
23261 exports.SpriteService = SpriteService_1.SpriteService;
23262 var TouchService_1 = require("./viewer/TouchService");
23263 exports.TouchService = TouchService_1.TouchService;
23264 var Viewer_1 = require("./viewer/Viewer");
23265 exports.Viewer = Viewer_1.Viewer;
23266
23267 },{"./viewer/Alignment":429,"./viewer/CacheService":430,"./viewer/ComponentController":431,"./viewer/Container":432,"./viewer/ImageSize":433,"./viewer/KeyboardService":434,"./viewer/LoadingService":435,"./viewer/MouseService":436,"./viewer/Navigator":437,"./viewer/Observer":438,"./viewer/PlayService":439,"./viewer/Projection":440,"./viewer/SpriteService":441,"./viewer/TouchService":442,"./viewer/Viewer":443}],303:[function(require,module,exports){
23268 "use strict";
23269 /// <reference path="../../typings/index.d.ts" />
23270 Object.defineProperty(exports, "__esModule", { value: true });
23271 var Observable_1 = require("rxjs/Observable");
23272 require("rxjs/add/observable/defer");
23273 require("rxjs/add/observable/fromPromise");
23274 require("rxjs/add/operator/catch");
23275 require("rxjs/add/operator/map");
23276 var API_1 = require("../API");
23277 /**
23278  * @class APIv3
23279  *
23280  * @classdesc Provides methods for access of API v3.
23281  */
23282 var APIv3 = /** @class */ (function () {
23283     /**
23284      * Create a new api v3 instance.
23285      *
23286      * @param {number} clientId - Client id for API requests.
23287      * @param {number} [token] - Optional bearer token for API requests of
23288      * protected resources.
23289      * @param {ModelCreator} [creator] - Optional model creator instance.
23290      */
23291     function APIv3(clientId, token, creator) {
23292         this._clientId = clientId;
23293         this._modelCreator = creator != null ? creator : new API_1.ModelCreator();
23294         this._model = this._modelCreator.createModel(clientId, token);
23295         this._pageCount = 999;
23296         this._pathImageByKey = "imageByKey";
23297         this._pathImageCloseTo = "imageCloseTo";
23298         this._pathImagesByH = "imagesByH";
23299         this._pathImageViewAdd = "imageViewAdd";
23300         this._pathSequenceByKey = "sequenceByKey";
23301         this._pathSequenceViewAdd = "sequenceViewAdd";
23302         this._propertiesCore = [
23303             "cl",
23304             "l",
23305             "sequence_key",
23306         ];
23307         this._propertiesFill = [
23308             "captured_at",
23309             "captured_with_camera_uuid",
23310             "user",
23311             "organization_key",
23312             "private",
23313             "project",
23314         ];
23315         this._propertiesKey = [
23316             "key",
23317         ];
23318         this._propertiesSequence = [
23319             "keys",
23320         ];
23321         this._propertiesSpatial = [
23322             "atomic_scale",
23323             "ca",
23324             "calt",
23325             "cca",
23326             "cfocal",
23327             "gpano",
23328             "height",
23329             "merge_cc",
23330             "merge_version",
23331             "c_rotation",
23332             "orientation",
23333             "width",
23334         ];
23335         this._propertiesUser = [
23336             "username",
23337         ];
23338     }
23339     APIv3.prototype.imageByKeyFill$ = function (keys) {
23340         return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
23341             this._pathImageByKey,
23342             keys,
23343             this._propertiesKey
23344                 .concat(this._propertiesFill)
23345                 .concat(this._propertiesSpatial),
23346             this._propertiesKey
23347                 .concat(this._propertiesUser)
23348         ]))
23349             .map(function (value) {
23350             if (!value) {
23351                 throw new Error("Images (" + keys.join(", ") + ") could not be found.");
23352             }
23353             return value.json.imageByKey;
23354         }), this._pathImageByKey, keys);
23355     };
23356     APIv3.prototype.imageByKeyFull$ = function (keys) {
23357         return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
23358             this._pathImageByKey,
23359             keys,
23360             this._propertiesKey
23361                 .concat(this._propertiesCore)
23362                 .concat(this._propertiesFill)
23363                 .concat(this._propertiesSpatial),
23364             this._propertiesKey
23365                 .concat(this._propertiesUser)
23366         ]))
23367             .map(function (value) {
23368             if (!value) {
23369                 throw new Error("Images (" + keys.join(", ") + ") could not be found.");
23370             }
23371             return value.json.imageByKey;
23372         }), this._pathImageByKey, keys);
23373     };
23374     APIv3.prototype.imageCloseTo$ = function (lat, lon) {
23375         var lonLat = lon + ":" + lat;
23376         return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
23377             this._pathImageCloseTo,
23378             [lonLat],
23379             this._propertiesKey
23380                 .concat(this._propertiesCore)
23381                 .concat(this._propertiesFill)
23382                 .concat(this._propertiesSpatial),
23383             this._propertiesKey
23384                 .concat(this._propertiesUser)
23385         ]))
23386             .map(function (value) {
23387             return value != null ? value.json.imageCloseTo[lonLat] : null;
23388         }), this._pathImageCloseTo, [lonLat]);
23389     };
23390     APIv3.prototype.imagesByH$ = function (hs) {
23391         var _this = this;
23392         return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
23393             this._pathImagesByH,
23394             hs,
23395             { from: 0, to: this._pageCount },
23396             this._propertiesKey
23397                 .concat(this._propertiesCore)
23398         ]))
23399             .map(function (value) {
23400             if (!value) {
23401                 value = { json: { imagesByH: {} } };
23402                 for (var _i = 0, hs_1 = hs; _i < hs_1.length; _i++) {
23403                     var h = hs_1[_i];
23404                     value.json.imagesByH[h] = {};
23405                     for (var i = 0; i <= _this._pageCount; i++) {
23406                         value.json.imagesByH[h][i] = null;
23407                     }
23408                 }
23409             }
23410             return value.json.imagesByH;
23411         }), this._pathImagesByH, hs);
23412     };
23413     APIv3.prototype.imageViewAdd$ = function (keys) {
23414         return this._catchInvalidateCall$(this._wrapPromise$(this._model.call([this._pathImageViewAdd], [keys])), this._pathImageViewAdd, keys);
23415     };
23416     APIv3.prototype.invalidateImageByKey = function (keys) {
23417         this._invalidateGet(this._pathImageByKey, keys);
23418     };
23419     APIv3.prototype.invalidateImagesByH = function (hs) {
23420         this._invalidateGet(this._pathImagesByH, hs);
23421     };
23422     APIv3.prototype.invalidateSequenceByKey = function (sKeys) {
23423         this._invalidateGet(this._pathSequenceByKey, sKeys);
23424     };
23425     APIv3.prototype.setToken = function (token) {
23426         this._model.invalidate([]);
23427         this._model = null;
23428         this._model = this._modelCreator.createModel(this._clientId, token);
23429     };
23430     APIv3.prototype.sequenceByKey$ = function (sequenceKeys) {
23431         return this._catchInvalidateGet$(this._wrapPromise$(this._model.get([
23432             this._pathSequenceByKey,
23433             sequenceKeys,
23434             this._propertiesKey
23435                 .concat(this._propertiesSequence)
23436         ]))
23437             .map(function (value) {
23438             if (!value) {
23439                 value = { json: { sequenceByKey: {} } };
23440             }
23441             for (var _i = 0, sequenceKeys_1 = sequenceKeys; _i < sequenceKeys_1.length; _i++) {
23442                 var sequenceKey = sequenceKeys_1[_i];
23443                 if (!(sequenceKey in value.json.sequenceByKey)) {
23444                     console.warn("Sequence data missing (" + sequenceKey + ")");
23445                     value.json.sequenceByKey[sequenceKey] = { key: sequenceKey, keys: [] };
23446                 }
23447             }
23448             return value.json.sequenceByKey;
23449         }), this._pathSequenceByKey, sequenceKeys);
23450     };
23451     APIv3.prototype.sequenceViewAdd$ = function (sequenceKeys) {
23452         return this._catchInvalidateCall$(this._wrapPromise$(this._model.call([this._pathSequenceViewAdd], [sequenceKeys])), this._pathSequenceViewAdd, sequenceKeys);
23453     };
23454     Object.defineProperty(APIv3.prototype, "clientId", {
23455         get: function () {
23456             return this._clientId;
23457         },
23458         enumerable: true,
23459         configurable: true
23460     });
23461     APIv3.prototype._catchInvalidateGet$ = function (observable, path, paths) {
23462         var _this = this;
23463         return observable
23464             .catch(function (error) {
23465             _this._invalidateGet(path, paths);
23466             throw error;
23467         });
23468     };
23469     APIv3.prototype._catchInvalidateCall$ = function (observable, path, paths) {
23470         var _this = this;
23471         return observable
23472             .catch(function (error) {
23473             _this._invalidateCall(path, paths);
23474             throw error;
23475         });
23476     };
23477     APIv3.prototype._invalidateGet = function (path, paths) {
23478         this._model.invalidate([path, paths]);
23479     };
23480     APIv3.prototype._invalidateCall = function (path, paths) {
23481         this._model.invalidate([path], [paths]);
23482     };
23483     APIv3.prototype._wrapPromise$ = function (promise) {
23484         return Observable_1.Observable.defer(function () { return Observable_1.Observable.fromPromise(promise); });
23485     };
23486     return APIv3;
23487 }());
23488 exports.APIv3 = APIv3;
23489 exports.default = APIv3;
23490
23491 },{"../API":290,"rxjs/Observable":29,"rxjs/add/observable/defer":40,"rxjs/add/observable/fromPromise":44,"rxjs/add/operator/catch":54,"rxjs/add/operator/map":67}],304:[function(require,module,exports){
23492 "use strict";
23493 /// <reference path="../../typings/index.d.ts" />
23494 Object.defineProperty(exports, "__esModule", { value: true });
23495 var falcor = require("falcor");
23496 var HttpDataSource = require("falcor-http-datasource");
23497 var Utils_1 = require("../Utils");
23498 /**
23499  * @class ModelCreator
23500  *
23501  * @classdesc Creates API models.
23502  */
23503 var ModelCreator = /** @class */ (function () {
23504     function ModelCreator() {
23505     }
23506     /**
23507      * Creates a Falcor model.
23508      *
23509      * @description Max cache size will be set to 16 MB. Authorization
23510      * header will be added if bearer token is supplied.
23511      *
23512      * @param {number} clientId - Client id for API requests.
23513      * @param {number} [token] - Optional bearer token for API requests of
23514      * protected resources.
23515      * @returns {falcor.Model} Falcor model for HTTP requests.
23516      */
23517     ModelCreator.prototype.createModel = function (clientId, token) {
23518         var configuration = {
23519             crossDomain: true,
23520             withCredentials: false,
23521         };
23522         if (token != null) {
23523             configuration.headers = { "Authorization": "Bearer " + token };
23524         }
23525         return new falcor.Model({
23526             maxSize: 16 * 1024 * 1024,
23527             source: new HttpDataSource(Utils_1.Urls.falcorModel(clientId), configuration),
23528         });
23529     };
23530     return ModelCreator;
23531 }());
23532 exports.ModelCreator = ModelCreator;
23533 exports.default = ModelCreator;
23534
23535 },{"../Utils":301,"falcor":15,"falcor-http-datasource":10}],305:[function(require,module,exports){
23536 "use strict";
23537 /// <reference path="../../typings/index.d.ts" />
23538 var __extends = (this && this.__extends) || (function () {
23539     var extendStatics = Object.setPrototypeOf ||
23540         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23541         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23542     return function (d, b) {
23543         extendStatics(d, b);
23544         function __() { this.constructor = d; }
23545         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23546     };
23547 })();
23548 Object.defineProperty(exports, "__esModule", { value: true });
23549 var vd = require("virtual-dom");
23550 var Component_1 = require("../Component");
23551 var Utils_1 = require("../Utils");
23552 var AttributionComponent = /** @class */ (function (_super) {
23553     __extends(AttributionComponent, _super);
23554     function AttributionComponent(name, container, navigator) {
23555         return _super.call(this, name, container, navigator) || this;
23556     }
23557     AttributionComponent.prototype._activate = function () {
23558         var _this = this;
23559         this._disposable = this._navigator.stateService.currentNode$
23560             .map(function (node) {
23561             return { name: _this._name, vnode: _this._getAttributionNode(node.username, node.key) };
23562         })
23563             .subscribe(this._container.domRenderer.render$);
23564     };
23565     AttributionComponent.prototype._deactivate = function () {
23566         this._disposable.unsubscribe();
23567     };
23568     AttributionComponent.prototype._getDefaultConfiguration = function () {
23569         return {};
23570     };
23571     AttributionComponent.prototype._getAttributionNode = function (username, key) {
23572         return vd.h("div.Attribution", {}, [
23573             vd.h("a", { href: Utils_1.Urls.exporeUser(username),
23574                 target: "_blank",
23575                 textContent: "@" + username,
23576             }, []),
23577             vd.h("span", { textContent: "|" }, []),
23578             vd.h("a", { href: Utils_1.Urls.exporeImage(key),
23579                 target: "_blank",
23580                 textContent: "mapillary.com",
23581             }, []),
23582         ]);
23583     };
23584     AttributionComponent.componentName = "attribution";
23585     return AttributionComponent;
23586 }(Component_1.Component));
23587 exports.AttributionComponent = AttributionComponent;
23588 Component_1.ComponentService.register(AttributionComponent);
23589 exports.default = AttributionComponent;
23590
23591 },{"../Component":291,"../Utils":301,"virtual-dom":247}],306:[function(require,module,exports){
23592 "use strict";
23593 /// <reference path="../../typings/index.d.ts" />
23594 var __extends = (this && this.__extends) || (function () {
23595     var extendStatics = Object.setPrototypeOf ||
23596         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23597         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23598     return function (d, b) {
23599         extendStatics(d, b);
23600         function __() { this.constructor = d; }
23601         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23602     };
23603 })();
23604 Object.defineProperty(exports, "__esModule", { value: true });
23605 var vd = require("virtual-dom");
23606 var Component_1 = require("../Component");
23607 var BackgroundComponent = /** @class */ (function (_super) {
23608     __extends(BackgroundComponent, _super);
23609     function BackgroundComponent(name, container, navigator) {
23610         return _super.call(this, name, container, navigator) || this;
23611     }
23612     BackgroundComponent.prototype._activate = function () {
23613         this._container.domRenderer.render$
23614             .next({ name: this._name, vnode: this._getBackgroundNode("The viewer can't display the given image.") });
23615     };
23616     BackgroundComponent.prototype._deactivate = function () {
23617         return;
23618     };
23619     BackgroundComponent.prototype._getDefaultConfiguration = function () {
23620         return {};
23621     };
23622     BackgroundComponent.prototype._getBackgroundNode = function (notice) {
23623         // todo: add condition for when to display the DOM node
23624         return vd.h("div.BackgroundWrapper", {}, [
23625             vd.h("p", { textContent: notice }, []),
23626         ]);
23627     };
23628     BackgroundComponent.componentName = "background";
23629     return BackgroundComponent;
23630 }(Component_1.Component));
23631 exports.BackgroundComponent = BackgroundComponent;
23632 Component_1.ComponentService.register(BackgroundComponent);
23633 exports.default = BackgroundComponent;
23634
23635 },{"../Component":291,"virtual-dom":247}],307:[function(require,module,exports){
23636 "use strict";
23637 /// <reference path="../../typings/index.d.ts" />
23638 var __extends = (this && this.__extends) || (function () {
23639     var extendStatics = Object.setPrototypeOf ||
23640         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23641         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23642     return function (d, b) {
23643         extendStatics(d, b);
23644         function __() { this.constructor = d; }
23645         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23646     };
23647 })();
23648 Object.defineProperty(exports, "__esModule", { value: true });
23649 var vd = require("virtual-dom");
23650 var Observable_1 = require("rxjs/Observable");
23651 var Component_1 = require("../Component");
23652 var Geo_1 = require("../Geo");
23653 var BearingComponent = /** @class */ (function (_super) {
23654     __extends(BearingComponent, _super);
23655     function BearingComponent(name, container, navigator) {
23656         var _this = _super.call(this, name, container, navigator) || this;
23657         _this._spatial = new Geo_1.Spatial();
23658         _this._svgNamespace = "http://www.w3.org/2000/svg";
23659         _this._distinctThreshold = Math.PI / 90;
23660         return _this;
23661     }
23662     BearingComponent.prototype._activate = function () {
23663         var _this = this;
23664         var nodeBearingFov$ = this._navigator.stateService.currentState$
23665             .distinctUntilChanged(undefined, function (frame) {
23666             return frame.state.currentNode.key;
23667         })
23668             .map(function (frame) {
23669             var node = frame.state.currentNode;
23670             var transform = frame.state.currentTransform;
23671             if (node.pano) {
23672                 var panoHFov = 2 * Math.PI * node.gpano.CroppedAreaImageWidthPixels / node.gpano.FullPanoWidthPixels;
23673                 return [_this._spatial.degToRad(node.ca), panoHFov];
23674             }
23675             var size = Math.max(transform.basicWidth, transform.basicHeight);
23676             if (size <= 0) {
23677                 console.warn("Original image size (" + transform.basicWidth + ", " + transform.basicHeight + ") is invalid (" + node.key + ". " +
23678                     "Not showing available fov.");
23679             }
23680             var hFov = size > 0 ?
23681                 2 * Math.atan(0.5 * transform.basicWidth / (size * transform.focal)) :
23682                 0;
23683             return [_this._spatial.degToRad(node.ca), hFov];
23684         })
23685             .distinctUntilChanged(function (a1, a2) {
23686             return Math.abs(a2[0] - a1[0]) < _this._distinctThreshold &&
23687                 Math.abs(a2[1] - a1[1]) < _this._distinctThreshold;
23688         });
23689         var cameraBearingFov$ = this._container.renderService.renderCamera$
23690             .map(function (rc) {
23691             var vFov = _this._spatial.degToRad(rc.perspective.fov);
23692             var hFov = rc.perspective.aspect === Number.POSITIVE_INFINITY ?
23693                 Math.PI :
23694                 Math.atan(rc.perspective.aspect * Math.tan(0.5 * vFov)) * 2;
23695             return [_this._spatial.azimuthalToBearing(rc.rotation.phi), hFov];
23696         })
23697             .distinctUntilChanged(function (a1, a2) {
23698             return Math.abs(a2[0] - a1[0]) < _this._distinctThreshold &&
23699                 Math.abs(a2[1] - a1[1]) < _this._distinctThreshold;
23700         });
23701         this._renderSubscription = Observable_1.Observable
23702             .combineLatest(nodeBearingFov$, cameraBearingFov$)
23703             .map(function (args) {
23704             var background = vd.h("div.BearingIndicatorBackground", { oncontextmenu: function (event) { event.preventDefault(); } }, [
23705                 vd.h("div.BearingIndicatorBackgroundRectangle", {}, []),
23706                 vd.h("div.BearingIndicatorBackgroundCircle", {}, []),
23707             ]);
23708             var north = vd.h("div.BearingIndicatorNorth", {}, []);
23709             var nodeSector = _this._createCircleSector(args[0][0], args[0][1], "#000");
23710             var cameraSector = _this._createCircleSector(args[1][0], args[1][1], "#fff");
23711             var compass = _this._createCircleSectorCompass(nodeSector, cameraSector);
23712             return {
23713                 name: _this._name,
23714                 vnode: vd.h("div.BearingIndicator", {}, [
23715                     background,
23716                     north,
23717                     compass,
23718                 ]),
23719             };
23720         })
23721             .subscribe(this._container.domRenderer.render$);
23722     };
23723     BearingComponent.prototype._deactivate = function () {
23724         this._renderSubscription.unsubscribe();
23725     };
23726     BearingComponent.prototype._getDefaultConfiguration = function () {
23727         return {};
23728     };
23729     BearingComponent.prototype._createCircleSectorCompass = function (nodeSector, cameraSector) {
23730         var group = vd.h("g", {
23731             attributes: { transform: "translate(1,1)" },
23732             namespace: this._svgNamespace,
23733         }, [nodeSector, cameraSector]);
23734         var centerCircle = vd.h("circle", {
23735             attributes: {
23736                 cx: "1",
23737                 cy: "1",
23738                 fill: "#abb1b9",
23739                 r: "0.291667",
23740                 stroke: "#000",
23741                 "stroke-width": "0.0833333",
23742             },
23743             namespace: this._svgNamespace,
23744         }, []);
23745         var svg = vd.h("svg", {
23746             attributes: { viewBox: "0 0 2 2" },
23747             namespace: this._svgNamespace,
23748             style: {
23749                 bottom: "4px",
23750                 height: "48px",
23751                 left: "4px",
23752                 position: "absolute",
23753                 width: "48px",
23754             },
23755         }, [group, centerCircle]);
23756         return svg;
23757     };
23758     BearingComponent.prototype._createCircleSector = function (bearing, fov, fill) {
23759         if (fov > 2 * Math.PI - Math.PI / 90) {
23760             return vd.h("circle", {
23761                 attributes: { cx: "0", cy: "0", fill: fill, r: "1" },
23762                 namespace: this._svgNamespace,
23763             }, []);
23764         }
23765         var arcStart = bearing - fov / 2 - Math.PI / 2;
23766         var arcEnd = arcStart + fov;
23767         var startX = Math.cos(arcStart);
23768         var startY = Math.sin(arcStart);
23769         var endX = Math.cos(arcEnd);
23770         var endY = Math.sin(arcEnd);
23771         var largeArc = fov >= Math.PI ? 1 : 0;
23772         var description = "M 0 0 " + startX + " " + startY + " A 1 1 0 " + largeArc + " 1 " + endX + " " + endY;
23773         return vd.h("path", {
23774             attributes: { d: description, fill: fill },
23775             namespace: this._svgNamespace,
23776         }, []);
23777     };
23778     BearingComponent.componentName = "bearing";
23779     return BearingComponent;
23780 }(Component_1.Component));
23781 exports.BearingComponent = BearingComponent;
23782 Component_1.ComponentService.register(BearingComponent);
23783 exports.default = BearingComponent;
23784
23785 },{"../Component":291,"../Geo":294,"rxjs/Observable":29,"virtual-dom":247}],308:[function(require,module,exports){
23786 "use strict";
23787 var __extends = (this && this.__extends) || (function () {
23788     var extendStatics = Object.setPrototypeOf ||
23789         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23790         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23791     return function (d, b) {
23792         extendStatics(d, b);
23793         function __() { this.constructor = d; }
23794         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23795     };
23796 })();
23797 Object.defineProperty(exports, "__esModule", { value: true });
23798 var Observable_1 = require("rxjs/Observable");
23799 require("rxjs/add/observable/combineLatest");
23800 require("rxjs/add/observable/from");
23801 require("rxjs/add/observable/merge");
23802 require("rxjs/add/observable/of");
23803 require("rxjs/add/observable/zip");
23804 require("rxjs/add/operator/catch");
23805 require("rxjs/add/operator/combineLatest");
23806 require("rxjs/add/operator/distinct");
23807 require("rxjs/add/operator/expand");
23808 require("rxjs/add/operator/filter");
23809 require("rxjs/add/operator/map");
23810 require("rxjs/add/operator/merge");
23811 require("rxjs/add/operator/mergeMap");
23812 require("rxjs/add/operator/mergeAll");
23813 require("rxjs/add/operator/skip");
23814 require("rxjs/add/operator/switchMap");
23815 var Edge_1 = require("../Edge");
23816 var Component_1 = require("../Component");
23817 var CacheComponent = /** @class */ (function (_super) {
23818     __extends(CacheComponent, _super);
23819     function CacheComponent(name, container, navigator) {
23820         return _super.call(this, name, container, navigator) || this;
23821     }
23822     /**
23823      * Set the cache depth.
23824      *
23825      * Configures the cache depth. The cache depth can be different for
23826      * different edge direction types.
23827      *
23828      * @param {ICacheDepth} depth - Cache depth structure.
23829      */
23830     CacheComponent.prototype.setDepth = function (depth) {
23831         this.configure({ depth: depth });
23832     };
23833     CacheComponent.prototype._activate = function () {
23834         var _this = this;
23835         this._sequenceSubscription = Observable_1.Observable
23836             .combineLatest(this._navigator.stateService.currentNode$
23837             .switchMap(function (node) {
23838             return node.sequenceEdges$;
23839         })
23840             .filter(function (status) {
23841             return status.cached;
23842         }), this._configuration$)
23843             .switchMap(function (nc) {
23844             var status = nc[0];
23845             var configuration = nc[1];
23846             var sequenceDepth = Math.max(0, Math.min(4, configuration.depth.sequence));
23847             var next$ = _this._cache$(status.edges, Edge_1.EdgeDirection.Next, sequenceDepth);
23848             var prev$ = _this._cache$(status.edges, Edge_1.EdgeDirection.Prev, sequenceDepth);
23849             return Observable_1.Observable
23850                 .merge(next$, prev$)
23851                 .catch(function (error, caught) {
23852                 console.error("Failed to cache sequence edges.", error);
23853                 return Observable_1.Observable.empty();
23854             });
23855         })
23856             .subscribe(function () { });
23857         this._spatialSubscription = this._navigator.stateService.currentNode$
23858             .switchMap(function (node) {
23859             return Observable_1.Observable
23860                 .combineLatest(Observable_1.Observable.of(node), node.spatialEdges$
23861                 .filter(function (status) {
23862                 return status.cached;
23863             }));
23864         })
23865             .combineLatest(this._configuration$, function (ns, configuration) {
23866             return [ns[0], ns[1], configuration];
23867         })
23868             .switchMap(function (args) {
23869             var node = args[0];
23870             var edges = args[1].edges;
23871             var depth = args[2].depth;
23872             var panoDepth = Math.max(0, Math.min(2, depth.pano));
23873             var stepDepth = node.pano ? 0 : Math.max(0, Math.min(3, depth.step));
23874             var turnDepth = node.pano ? 0 : Math.max(0, Math.min(1, depth.turn));
23875             var pano$ = _this._cache$(edges, Edge_1.EdgeDirection.Pano, panoDepth);
23876             var forward$ = _this._cache$(edges, Edge_1.EdgeDirection.StepForward, stepDepth);
23877             var backward$ = _this._cache$(edges, Edge_1.EdgeDirection.StepBackward, stepDepth);
23878             var left$ = _this._cache$(edges, Edge_1.EdgeDirection.StepLeft, stepDepth);
23879             var right$ = _this._cache$(edges, Edge_1.EdgeDirection.StepRight, stepDepth);
23880             var turnLeft$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnLeft, turnDepth);
23881             var turnRight$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnRight, turnDepth);
23882             var turnU$ = _this._cache$(edges, Edge_1.EdgeDirection.TurnU, turnDepth);
23883             return Observable_1.Observable
23884                 .merge(forward$, backward$, left$, right$, pano$, turnLeft$, turnRight$, turnU$)
23885                 .catch(function (error, caught) {
23886                 console.error("Failed to cache spatial edges.", error);
23887                 return Observable_1.Observable.empty();
23888             });
23889         })
23890             .subscribe(function () { });
23891     };
23892     CacheComponent.prototype._deactivate = function () {
23893         this._sequenceSubscription.unsubscribe();
23894         this._spatialSubscription.unsubscribe();
23895     };
23896     CacheComponent.prototype._getDefaultConfiguration = function () {
23897         return { depth: { pano: 1, sequence: 2, step: 1, turn: 0 } };
23898     };
23899     CacheComponent.prototype._cache$ = function (edges, direction, depth) {
23900         var _this = this;
23901         return Observable_1.Observable
23902             .zip(Observable_1.Observable.of(edges), Observable_1.Observable.of(depth))
23903             .expand(function (ed) {
23904             var es = ed[0];
23905             var d = ed[1];
23906             var edgesDepths$ = [];
23907             if (d > 0) {
23908                 for (var _i = 0, es_1 = es; _i < es_1.length; _i++) {
23909                     var edge = es_1[_i];
23910                     if (edge.data.direction === direction) {
23911                         edgesDepths$.push(Observable_1.Observable
23912                             .zip(_this._navigator.graphService.cacheNode$(edge.to)
23913                             .mergeMap(function (n) {
23914                             return _this._nodeToEdges$(n, direction);
23915                         }), Observable_1.Observable.of(d - 1)));
23916                     }
23917                 }
23918             }
23919             return Observable_1.Observable
23920                 .from(edgesDepths$)
23921                 .mergeAll();
23922         })
23923             .skip(1);
23924     };
23925     CacheComponent.prototype._nodeToEdges$ = function (node, direction) {
23926         return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
23927             node.sequenceEdges$ :
23928             node.spatialEdges$)
23929             .first(function (status) {
23930             return status.cached;
23931         })
23932             .map(function (status) {
23933             return status.edges;
23934         });
23935     };
23936     CacheComponent.componentName = "cache";
23937     return CacheComponent;
23938 }(Component_1.Component));
23939 exports.CacheComponent = CacheComponent;
23940 Component_1.ComponentService.register(CacheComponent);
23941 exports.default = CacheComponent;
23942
23943 },{"../Component":291,"../Edge":292,"rxjs/Observable":29,"rxjs/add/observable/combineLatest":38,"rxjs/add/observable/from":42,"rxjs/add/observable/merge":45,"rxjs/add/observable/of":46,"rxjs/add/observable/zip":49,"rxjs/add/operator/catch":54,"rxjs/add/operator/combineLatest":55,"rxjs/add/operator/distinct":59,"rxjs/add/operator/expand":62,"rxjs/add/operator/filter":63,"rxjs/add/operator/map":67,"rxjs/add/operator/merge":68,"rxjs/add/operator/mergeAll":69,"rxjs/add/operator/mergeMap":70,"rxjs/add/operator/skip":80,"rxjs/add/operator/switchMap":84}],309:[function(require,module,exports){
23944 "use strict";
23945 var __extends = (this && this.__extends) || (function () {
23946     var extendStatics = Object.setPrototypeOf ||
23947         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23948         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
23949     return function (d, b) {
23950         extendStatics(d, b);
23951         function __() { this.constructor = d; }
23952         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
23953     };
23954 })();
23955 Object.defineProperty(exports, "__esModule", { value: true });
23956 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
23957 var Subject_1 = require("rxjs/Subject");
23958 require("rxjs/add/operator/publishReplay");
23959 require("rxjs/add/operator/scan");
23960 require("rxjs/add/operator/startWith");
23961 var Utils_1 = require("../Utils");
23962 var Component = /** @class */ (function (_super) {
23963     __extends(Component, _super);
23964     function Component(name, container, navigator) {
23965         var _this = _super.call(this) || this;
23966         _this._activated$ = new BehaviorSubject_1.BehaviorSubject(false);
23967         _this._configurationSubject$ = new Subject_1.Subject();
23968         _this._activated = false;
23969         _this._container = container;
23970         _this._name = name;
23971         _this._navigator = navigator;
23972         _this._configuration$ =
23973             _this._configurationSubject$
23974                 .startWith(_this.defaultConfiguration)
23975                 .scan(function (conf, newConf) {
23976                 for (var key in newConf) {
23977                     if (newConf.hasOwnProperty(key)) {
23978                         conf[key] = newConf[key];
23979                     }
23980                 }
23981                 return conf;
23982             })
23983                 .publishReplay(1)
23984                 .refCount();
23985         _this._configuration$.subscribe(function () { });
23986         return _this;
23987     }
23988     Object.defineProperty(Component.prototype, "activated", {
23989         get: function () {
23990             return this._activated;
23991         },
23992         enumerable: true,
23993         configurable: true
23994     });
23995     Object.defineProperty(Component.prototype, "activated$", {
23996         get: function () {
23997             return this._activated$;
23998         },
23999         enumerable: true,
24000         configurable: true
24001     });
24002     Object.defineProperty(Component.prototype, "defaultConfiguration", {
24003         /**
24004          * Get default configuration.
24005          *
24006          * @returns {TConfiguration} Default configuration for component.
24007          */
24008         get: function () {
24009             return this._getDefaultConfiguration();
24010         },
24011         enumerable: true,
24012         configurable: true
24013     });
24014     Object.defineProperty(Component.prototype, "configuration$", {
24015         get: function () {
24016             return this._configuration$;
24017         },
24018         enumerable: true,
24019         configurable: true
24020     });
24021     Object.defineProperty(Component.prototype, "name", {
24022         get: function () {
24023             return this._name;
24024         },
24025         enumerable: true,
24026         configurable: true
24027     });
24028     Component.prototype.activate = function (conf) {
24029         if (this._activated) {
24030             return;
24031         }
24032         if (conf !== undefined) {
24033             this._configurationSubject$.next(conf);
24034         }
24035         this._activated = true;
24036         this._activate();
24037         this._activated$.next(true);
24038     };
24039     Component.prototype.configure = function (conf) {
24040         this._configurationSubject$.next(conf);
24041     };
24042     Component.prototype.deactivate = function () {
24043         if (!this._activated) {
24044             return;
24045         }
24046         this._activated = false;
24047         this._deactivate();
24048         this._container.domRenderer.clear(this._name);
24049         this._container.glRenderer.clear(this._name);
24050         this._activated$.next(false);
24051     };
24052     /**
24053      * Detect the viewer's new width and height and resize the component's
24054      * rendered elements accordingly if applicable.
24055      */
24056     Component.prototype.resize = function () { return; };
24057     /**
24058      * Component name. Used when interacting with component through the Viewer's API.
24059      */
24060     Component.componentName = "not_worthy";
24061     return Component;
24062 }(Utils_1.EventEmitter));
24063 exports.Component = Component;
24064 exports.default = Component;
24065
24066 },{"../Utils":301,"rxjs/BehaviorSubject":26,"rxjs/Subject":34,"rxjs/add/operator/publishReplay":74,"rxjs/add/operator/scan":78,"rxjs/add/operator/startWith":83}],310:[function(require,module,exports){
24067 "use strict";
24068 /// <reference path="../../typings/index.d.ts" />
24069 Object.defineProperty(exports, "__esModule", { value: true });
24070 var _ = require("underscore");
24071 var Error_1 = require("../Error");
24072 var ComponentService = /** @class */ (function () {
24073     function ComponentService(container, navigator) {
24074         this._components = {};
24075         for (var _i = 0, _a = _.values(ComponentService.registeredComponents); _i < _a.length; _i++) {
24076             var component = _a[_i];
24077             this._components[component.componentName] = {
24078                 active: false,
24079                 component: new component(component.componentName, container, navigator),
24080             };
24081         }
24082         this._coverComponent = new ComponentService.registeredCoverComponent("cover", container, navigator);
24083         this._coverComponent.activate();
24084         this._coverActivated = true;
24085     }
24086     ComponentService.register = function (component) {
24087         if (ComponentService.registeredComponents[component.componentName] === undefined) {
24088             ComponentService.registeredComponents[component.componentName] = component;
24089         }
24090     };
24091     ComponentService.registerCover = function (coverComponent) {
24092         ComponentService.registeredCoverComponent = coverComponent;
24093     };
24094     Object.defineProperty(ComponentService.prototype, "coverActivated", {
24095         get: function () {
24096             return this._coverActivated;
24097         },
24098         enumerable: true,
24099         configurable: true
24100     });
24101     ComponentService.prototype.activateCover = function () {
24102         if (this._coverActivated) {
24103             return;
24104         }
24105         this._coverActivated = true;
24106         for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
24107             var component = _a[_i];
24108             if (component.active) {
24109                 component.component.deactivate();
24110             }
24111         }
24112         return;
24113     };
24114     ComponentService.prototype.deactivateCover = function () {
24115         if (!this._coverActivated) {
24116             return;
24117         }
24118         this._coverActivated = false;
24119         for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
24120             var component = _a[_i];
24121             if (component.active) {
24122                 component.component.activate();
24123             }
24124         }
24125         return;
24126     };
24127     ComponentService.prototype.activate = function (name) {
24128         this._checkName(name);
24129         this._components[name].active = true;
24130         if (!this._coverActivated) {
24131             this.get(name).activate();
24132         }
24133     };
24134     ComponentService.prototype.configure = function (name, conf) {
24135         this._checkName(name);
24136         this.get(name).configure(conf);
24137     };
24138     ComponentService.prototype.deactivate = function (name) {
24139         this._checkName(name);
24140         this._components[name].active = false;
24141         if (!this._coverActivated) {
24142             this.get(name).deactivate();
24143         }
24144     };
24145     ComponentService.prototype.resize = function () {
24146         for (var _i = 0, _a = _.values(this._components); _i < _a.length; _i++) {
24147             var component = _a[_i];
24148             component.component.resize();
24149         }
24150     };
24151     ComponentService.prototype.get = function (name) {
24152         return this._components[name].component;
24153     };
24154     ComponentService.prototype.getCover = function () {
24155         return this._coverComponent;
24156     };
24157     ComponentService.prototype._checkName = function (name) {
24158         if (!(name in this._components)) {
24159             throw new Error_1.ArgumentMapillaryError("Component does not exist: " + name);
24160         }
24161     };
24162     ComponentService.registeredComponents = {};
24163     return ComponentService;
24164 }());
24165 exports.ComponentService = ComponentService;
24166 exports.default = ComponentService;
24167
24168 },{"../Error":293,"underscore":243}],311:[function(require,module,exports){
24169 "use strict";
24170 /// <reference path="../../typings/index.d.ts" />
24171 var __extends = (this && this.__extends) || (function () {
24172     var extendStatics = Object.setPrototypeOf ||
24173         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24174         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24175     return function (d, b) {
24176         extendStatics(d, b);
24177         function __() { this.constructor = d; }
24178         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24179     };
24180 })();
24181 Object.defineProperty(exports, "__esModule", { value: true });
24182 var vd = require("virtual-dom");
24183 require("rxjs/add/operator/filter");
24184 require("rxjs/add/operator/map");
24185 require("rxjs/add/operator/withLatestFrom");
24186 var Component_1 = require("../Component");
24187 var Utils_1 = require("../Utils");
24188 var Viewer_1 = require("../Viewer");
24189 var CoverComponent = /** @class */ (function (_super) {
24190     __extends(CoverComponent, _super);
24191     function CoverComponent(name, container, navigator) {
24192         return _super.call(this, name, container, navigator) || this;
24193     }
24194     CoverComponent.prototype._activate = function () {
24195         var _this = this;
24196         this._keyDisposable = this._navigator.stateService.currentNode$
24197             .withLatestFrom(this._configuration$, function (node, configuration) {
24198             return [node, configuration];
24199         })
24200             .filter(function (_a) {
24201             var node = _a[0], configuration = _a[1];
24202             return node.key !== configuration.key;
24203         })
24204             .map(function (_a) {
24205             var node = _a[0], configuration = _a[1];
24206             return node;
24207         })
24208             .map(function (node) {
24209             return { key: node.key, src: node.image.src };
24210         })
24211             .subscribe(this._configurationSubject$);
24212         this._disposable = this._configuration$
24213             .map(function (conf) {
24214             if (!conf.key) {
24215                 return { name: _this._name, vnode: vd.h("div", []) };
24216             }
24217             if (conf.state === Component_1.CoverState.Hidden) {
24218                 return { name: _this._name, vnode: vd.h("div.Cover.CoverDone", [_this._getCoverBackgroundVNode(conf)]) };
24219             }
24220             return { name: _this._name, vnode: _this._getCoverButtonVNode(conf) };
24221         })
24222             .subscribe(this._container.domRenderer.render$);
24223     };
24224     CoverComponent.prototype._deactivate = function () {
24225         this._disposable.unsubscribe();
24226         this._keyDisposable.unsubscribe();
24227     };
24228     CoverComponent.prototype._getDefaultConfiguration = function () {
24229         return { state: Component_1.CoverState.Visible };
24230     };
24231     CoverComponent.prototype._getCoverButtonVNode = function (conf) {
24232         var _this = this;
24233         var cover = conf.state === Component_1.CoverState.Loading ? "div.Cover.CoverLoading" : "div.Cover";
24234         return vd.h(cover, [
24235             this._getCoverBackgroundVNode(conf),
24236             vd.h("button.CoverButton", { onclick: function () { _this.configure({ state: Component_1.CoverState.Loading }); } }, ["Explore"]),
24237             vd.h("a.CoverLogo", { href: Utils_1.Urls.explore, target: "_blank" }, []),
24238         ]);
24239     };
24240     CoverComponent.prototype._getCoverBackgroundVNode = function (conf) {
24241         var url = conf.src != null ?
24242             conf.src : Utils_1.Urls.thumbnail(conf.key, Viewer_1.ImageSize.Size640);
24243         var properties = { style: { backgroundImage: "url(" + url + ")" } };
24244         var children = [];
24245         if (conf.state === Component_1.CoverState.Loading) {
24246             children.push(vd.h("div.Spinner", {}, []));
24247         }
24248         children.push(vd.h("div.CoverBackgroundGradient", {}, []));
24249         return vd.h("div.CoverBackground", properties, children);
24250     };
24251     CoverComponent.componentName = "cover";
24252     return CoverComponent;
24253 }(Component_1.Component));
24254 exports.CoverComponent = CoverComponent;
24255 Component_1.ComponentService.registerCover(CoverComponent);
24256 exports.default = CoverComponent;
24257
24258 },{"../Component":291,"../Utils":301,"../Viewer":302,"rxjs/add/operator/filter":63,"rxjs/add/operator/map":67,"rxjs/add/operator/withLatestFrom":90,"virtual-dom":247}],312:[function(require,module,exports){
24259 "use strict";
24260 /// <reference path="../../typings/index.d.ts" />
24261 var __extends = (this && this.__extends) || (function () {
24262     var extendStatics = Object.setPrototypeOf ||
24263         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24264         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24265     return function (d, b) {
24266         extendStatics(d, b);
24267         function __() { this.constructor = d; }
24268         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24269     };
24270 })();
24271 Object.defineProperty(exports, "__esModule", { value: true });
24272 var _ = require("underscore");
24273 var vd = require("virtual-dom");
24274 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
24275 require("rxjs/add/operator/combineLatest");
24276 var Component_1 = require("../Component");
24277 var DebugComponent = /** @class */ (function (_super) {
24278     __extends(DebugComponent, _super);
24279     function DebugComponent() {
24280         var _this = _super !== null && _super.apply(this, arguments) || this;
24281         _this._open$ = new BehaviorSubject_1.BehaviorSubject(false);
24282         return _this;
24283     }
24284     DebugComponent.prototype._activate = function () {
24285         var _this = this;
24286         this._disposable = this._navigator.stateService.currentState$
24287             .combineLatest(this._open$, this._navigator.imageLoadingService.loadstatus$, function (frame, open, loadStatus) {
24288             return { name: _this._name, vnode: _this._getDebugVNode(open, _this._getDebugInfo(frame, loadStatus)) };
24289         })
24290             .subscribe(this._container.domRenderer.render$);
24291     };
24292     DebugComponent.prototype._deactivate = function () {
24293         this._disposable.unsubscribe();
24294     };
24295     DebugComponent.prototype._getDefaultConfiguration = function () {
24296         return {};
24297     };
24298     DebugComponent.prototype._getDebugInfo = function (frame, loadStatus) {
24299         var ret = [];
24300         ret.push(vd.h("h2", "Node"));
24301         if (frame.state.currentNode) {
24302             ret.push(vd.h("p", "currentNode: " + frame.state.currentNode.key));
24303         }
24304         if (frame.state.previousNode) {
24305             ret.push(vd.h("p", "previousNode: " + frame.state.previousNode.key));
24306         }
24307         ret.push(vd.h("h2", "Loading"));
24308         var total = 0;
24309         var loaded = 0;
24310         var loading = 0;
24311         for (var _i = 0, _a = _.values(loadStatus); _i < _a.length; _i++) {
24312             var loadStat = _a[_i];
24313             total += loadStat.loaded;
24314             if (loadStat.loaded !== loadStat.total) {
24315                 loading++;
24316             }
24317             else {
24318                 loaded++;
24319             }
24320         }
24321         ret.push(vd.h("p", "Loaded Images: " + loaded));
24322         ret.push(vd.h("p", "Loading Images: " + loading));
24323         ret.push(vd.h("p", "Total bytes loaded: " + total));
24324         ret.push(vd.h("h2", "Camera"));
24325         ret.push(vd.h("p", "camera.position.x: " + frame.state.camera.position.x));
24326         ret.push(vd.h("p", "camera.position.y: " + frame.state.camera.position.y));
24327         ret.push(vd.h("p", "camera.position.z: " + frame.state.camera.position.z));
24328         ret.push(vd.h("p", "camera.lookat.x: " + frame.state.camera.lookat.x));
24329         ret.push(vd.h("p", "camera.lookat.y: " + frame.state.camera.lookat.y));
24330         ret.push(vd.h("p", "camera.lookat.z: " + frame.state.camera.lookat.z));
24331         ret.push(vd.h("p", "camera.up.x: " + frame.state.camera.up.x));
24332         ret.push(vd.h("p", "camera.up.y: " + frame.state.camera.up.y));
24333         ret.push(vd.h("p", "camera.up.z: " + frame.state.camera.up.z));
24334         return ret;
24335     };
24336     DebugComponent.prototype._getDebugVNode = function (open, info) {
24337         if (open) {
24338             return vd.h("div.Debug", {}, [
24339                 vd.h("h2", {}, ["Debug"]),
24340                 this._getDebugVNodeButton(open),
24341                 vd.h("pre", {}, info),
24342             ]);
24343         }
24344         else {
24345             return this._getDebugVNodeButton(open);
24346         }
24347     };
24348     DebugComponent.prototype._getDebugVNodeButton = function (open) {
24349         var buttonText = open ? "Disable Debug" : "D";
24350         var buttonCssClass = open ? "" : ".DebugButtonFixed";
24351         if (open) {
24352             return vd.h("button.DebugButton" + buttonCssClass, { onclick: this._closeDebugElement.bind(this) }, [buttonText]);
24353         }
24354         else {
24355             return vd.h("button.DebugButton" + buttonCssClass, { onclick: this._openDebugElement.bind(this) }, [buttonText]);
24356         }
24357     };
24358     DebugComponent.prototype._closeDebugElement = function (open) {
24359         this._open$.next(false);
24360     };
24361     DebugComponent.prototype._openDebugElement = function () {
24362         this._open$.next(true);
24363     };
24364     DebugComponent.componentName = "debug";
24365     return DebugComponent;
24366 }(Component_1.Component));
24367 exports.DebugComponent = DebugComponent;
24368 Component_1.ComponentService.register(DebugComponent);
24369 exports.default = DebugComponent;
24370
24371 },{"../Component":291,"rxjs/BehaviorSubject":26,"rxjs/add/operator/combineLatest":55,"underscore":243,"virtual-dom":247}],313:[function(require,module,exports){
24372 "use strict";
24373 /// <reference path="../../typings/index.d.ts" />
24374 var __extends = (this && this.__extends) || (function () {
24375     var extendStatics = Object.setPrototypeOf ||
24376         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24377         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24378     return function (d, b) {
24379         extendStatics(d, b);
24380         function __() { this.constructor = d; }
24381         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24382     };
24383 })();
24384 Object.defineProperty(exports, "__esModule", { value: true });
24385 var vd = require("virtual-dom");
24386 var Observable_1 = require("rxjs/Observable");
24387 require("rxjs/add/operator/combineLatest");
24388 var Component_1 = require("../Component");
24389 var Utils_1 = require("../Utils");
24390 var ImageComponent = /** @class */ (function (_super) {
24391     __extends(ImageComponent, _super);
24392     function ImageComponent(name, container, navigator, dom) {
24393         var _this = _super.call(this, name, container, navigator) || this;
24394         _this._canvasId = container.id + "-" + _this._name;
24395         _this._dom = !!dom ? dom : new Utils_1.DOM();
24396         return _this;
24397     }
24398     ImageComponent.prototype._activate = function () {
24399         var _this = this;
24400         var canvasSize$ = this._container.domRenderer.element$
24401             .map(function (element) {
24402             return _this._dom.document.getElementById(_this._canvasId);
24403         })
24404             .filter(function (canvas) {
24405             return !!canvas;
24406         })
24407             .map(function (canvas) {
24408             var adaptableDomRenderer = canvas.parentElement;
24409             var width = adaptableDomRenderer.offsetWidth;
24410             var height = adaptableDomRenderer.offsetHeight;
24411             return [canvas, { height: height, width: width }];
24412         })
24413             .distinctUntilChanged(function (s1, s2) {
24414             return s1.height === s2.height && s1.width === s2.width;
24415         }, function (_a) {
24416             var canvas = _a[0], size = _a[1];
24417             return size;
24418         });
24419         this.drawSubscription = Observable_1.Observable
24420             .combineLatest(canvasSize$, this._navigator.stateService.currentNode$)
24421             .subscribe(function (_a) {
24422             var _b = _a[0], canvas = _b[0], size = _b[1], node = _a[1];
24423             canvas.width = size.width;
24424             canvas.height = size.height;
24425             canvas
24426                 .getContext("2d")
24427                 .drawImage(node.image, 0, 0, size.width, size.height);
24428         });
24429         this._container.domRenderer.renderAdaptive$.next({ name: this._name, vnode: vd.h("canvas#" + this._canvasId, []) });
24430     };
24431     ImageComponent.prototype._deactivate = function () {
24432         this.drawSubscription.unsubscribe();
24433     };
24434     ImageComponent.prototype._getDefaultConfiguration = function () {
24435         return {};
24436     };
24437     ImageComponent.componentName = "image";
24438     return ImageComponent;
24439 }(Component_1.Component));
24440 exports.ImageComponent = ImageComponent;
24441 Component_1.ComponentService.register(ImageComponent);
24442 exports.default = ImageComponent;
24443
24444 },{"../Component":291,"../Utils":301,"rxjs/Observable":29,"rxjs/add/operator/combineLatest":55,"virtual-dom":247}],314:[function(require,module,exports){
24445 "use strict";
24446 /// <reference path="../../typings/index.d.ts" />
24447 var __extends = (this && this.__extends) || (function () {
24448     var extendStatics = Object.setPrototypeOf ||
24449         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24450         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24451     return function (d, b) {
24452         extendStatics(d, b);
24453         function __() { this.constructor = d; }
24454         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24455     };
24456 })();
24457 Object.defineProperty(exports, "__esModule", { value: true });
24458 var _ = require("underscore");
24459 var vd = require("virtual-dom");
24460 var Observable_1 = require("rxjs/Observable");
24461 require("rxjs/add/operator/combineLatest");
24462 var Component_1 = require("../Component");
24463 var LoadingComponent = /** @class */ (function (_super) {
24464     __extends(LoadingComponent, _super);
24465     function LoadingComponent(name, container, navigator) {
24466         return _super.call(this, name, container, navigator) || this;
24467     }
24468     LoadingComponent.prototype._activate = function () {
24469         var _this = this;
24470         this._loadingSubscription = this._navigator.loadingService.loading$
24471             .switchMap(function (loading) {
24472             return loading ?
24473                 _this._navigator.imageLoadingService.loadstatus$ :
24474                 Observable_1.Observable.of({});
24475         })
24476             .map(function (loadStatus) {
24477             var total = 0;
24478             var loaded = 0;
24479             for (var _i = 0, _a = _.values(loadStatus); _i < _a.length; _i++) {
24480                 var loadStat = _a[_i];
24481                 if (loadStat.loaded !== loadStat.total) {
24482                     loaded += loadStat.loaded;
24483                     total += loadStat.total;
24484                 }
24485             }
24486             var percentage = 100;
24487             if (total !== 0) {
24488                 percentage = (loaded / total) * 100;
24489             }
24490             return { name: _this._name, vnode: _this._getBarVNode(percentage) };
24491         })
24492             .subscribe(this._container.domRenderer.render$);
24493     };
24494     LoadingComponent.prototype._deactivate = function () {
24495         this._loadingSubscription.unsubscribe();
24496     };
24497     LoadingComponent.prototype._getDefaultConfiguration = function () {
24498         return {};
24499     };
24500     LoadingComponent.prototype._getBarVNode = function (percentage) {
24501         var loadingBarStyle = {};
24502         var loadingContainerStyle = {};
24503         if (percentage !== 100) {
24504             loadingBarStyle.width = percentage.toFixed(0) + "%";
24505             loadingBarStyle.opacity = "1";
24506         }
24507         else {
24508             loadingBarStyle.width = "100%";
24509             loadingBarStyle.opacity = "0";
24510         }
24511         return vd.h("div.Loading", { style: loadingContainerStyle }, [vd.h("div.LoadingBar", { style: loadingBarStyle }, [])]);
24512     };
24513     LoadingComponent.componentName = "loading";
24514     return LoadingComponent;
24515 }(Component_1.Component));
24516 exports.LoadingComponent = LoadingComponent;
24517 Component_1.ComponentService.register(LoadingComponent);
24518 exports.default = LoadingComponent;
24519
24520 },{"../Component":291,"rxjs/Observable":29,"rxjs/add/operator/combineLatest":55,"underscore":243,"virtual-dom":247}],315:[function(require,module,exports){
24521 "use strict";
24522 /// <reference path="../../typings/index.d.ts" />
24523 var __extends = (this && this.__extends) || (function () {
24524     var extendStatics = Object.setPrototypeOf ||
24525         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24526         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24527     return function (d, b) {
24528         extendStatics(d, b);
24529         function __() { this.constructor = d; }
24530         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24531     };
24532 })();
24533 Object.defineProperty(exports, "__esModule", { value: true });
24534 var vd = require("virtual-dom");
24535 var Observable_1 = require("rxjs/Observable");
24536 require("rxjs/add/operator/map");
24537 require("rxjs/add/operator/first");
24538 var Edge_1 = require("../Edge");
24539 var Error_1 = require("../Error");
24540 var Component_1 = require("../Component");
24541 /**
24542  * @class NavigationComponent
24543  *
24544  * @classdesc Fallback navigation component for environments without WebGL support.
24545  *
24546  * Replaces the functionality in the Direction and Sequence components.
24547  */
24548 var NavigationComponent = /** @class */ (function (_super) {
24549     __extends(NavigationComponent, _super);
24550     function NavigationComponent(name, container, navigator) {
24551         var _this = _super.call(this, name, container, navigator) || this;
24552         _this._seqNames = {};
24553         _this._seqNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.Prev]] = "Prev";
24554         _this._seqNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.Next]] = "Next";
24555         _this._spaTopNames = {};
24556         _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.TurnLeft]] = "Turnleft";
24557         _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepLeft]] = "Left";
24558         _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepForward]] = "Forward";
24559         _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepRight]] = "Right";
24560         _this._spaTopNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.TurnRight]] = "Turnright";
24561         _this._spaBottomNames = {};
24562         _this._spaBottomNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.TurnU]] = "Turnaround";
24563         _this._spaBottomNames[Edge_1.EdgeDirection[Edge_1.EdgeDirection.StepBackward]] = "Backward";
24564         return _this;
24565     }
24566     NavigationComponent.prototype._activate = function () {
24567         var _this = this;
24568         this._renderSubscription = Observable_1.Observable
24569             .combineLatest(this._navigator.stateService.currentNode$, this._configuration$)
24570             .switchMap(function (_a) {
24571             var node = _a[0], configuration = _a[1];
24572             var sequenceEdges$ = configuration.sequence ?
24573                 node.sequenceEdges$
24574                     .map(function (status) {
24575                     return status.edges
24576                         .map(function (edge) {
24577                         return edge.data.direction;
24578                     });
24579                 }) :
24580                 Observable_1.Observable.of([]);
24581             var spatialEdges$ = !node.pano && configuration.spatial ?
24582                 node.spatialEdges$
24583                     .map(function (status) {
24584                     return status.edges
24585                         .map(function (edge) {
24586                         return edge.data.direction;
24587                     });
24588                 }) :
24589                 Observable_1.Observable.of([]);
24590             return Observable_1.Observable
24591                 .combineLatest(sequenceEdges$, spatialEdges$)
24592                 .map(function (_a) {
24593                 var seq = _a[0], spa = _a[1];
24594                 return seq.concat(spa);
24595             });
24596         })
24597             .map(function (edgeDirections) {
24598             var seqs = _this._createArrowRow(_this._seqNames, edgeDirections);
24599             var spaTops = _this._createArrowRow(_this._spaTopNames, edgeDirections);
24600             var spaBottoms = _this._createArrowRow(_this._spaBottomNames, edgeDirections);
24601             var seqContainer = vd.h("div.NavigationSequence", seqs);
24602             var spaTopContainer = vd.h("div.NavigationSpatialTop", spaTops);
24603             var spaBottomContainer = vd.h("div.NavigationSpatialBottom", spaBottoms);
24604             var spaContainer = vd.h("div.NavigationSpatial", [spaTopContainer, spaBottomContainer]);
24605             return { name: _this._name, vnode: vd.h("div.NavigationContainer", [seqContainer, spaContainer]) };
24606         })
24607             .subscribe(this._container.domRenderer.render$);
24608     };
24609     NavigationComponent.prototype._deactivate = function () {
24610         this._renderSubscription.unsubscribe();
24611     };
24612     NavigationComponent.prototype._getDefaultConfiguration = function () {
24613         return { sequence: true, spatial: true };
24614     };
24615     NavigationComponent.prototype._createArrowRow = function (arrowNames, edgeDirections) {
24616         var arrows = [];
24617         for (var arrowName in arrowNames) {
24618             if (!(arrowNames.hasOwnProperty(arrowName))) {
24619                 continue;
24620             }
24621             var direction = Edge_1.EdgeDirection[arrowName];
24622             if (edgeDirections.indexOf(direction) !== -1) {
24623                 arrows.push(this._createVNode(direction, arrowNames[arrowName], "visible"));
24624             }
24625             else {
24626                 arrows.push(this._createVNode(direction, arrowNames[arrowName], "hidden"));
24627             }
24628         }
24629         return arrows;
24630     };
24631     NavigationComponent.prototype._createVNode = function (direction, name, visibility) {
24632         var _this = this;
24633         return vd.h("span.Direction.Direction" + name, {
24634             onclick: function (ev) {
24635                 _this._navigator.moveDir$(direction)
24636                     .subscribe(undefined, function (error) {
24637                     if (!(error instanceof Error_1.AbortMapillaryError)) {
24638                         console.error(error);
24639                     }
24640                 });
24641             },
24642             style: {
24643                 visibility: visibility,
24644             },
24645         }, []);
24646     };
24647     NavigationComponent.componentName = "navigation";
24648     return NavigationComponent;
24649 }(Component_1.Component));
24650 exports.NavigationComponent = NavigationComponent;
24651 Component_1.ComponentService.register(NavigationComponent);
24652 exports.default = NavigationComponent;
24653
24654 },{"../Component":291,"../Edge":292,"../Error":293,"rxjs/Observable":29,"rxjs/add/operator/first":65,"rxjs/add/operator/map":67,"virtual-dom":247}],316:[function(require,module,exports){
24655 "use strict";
24656 /// <reference path="../../typings/index.d.ts" />
24657 var __extends = (this && this.__extends) || (function () {
24658     var extendStatics = Object.setPrototypeOf ||
24659         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24660         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24661     return function (d, b) {
24662         extendStatics(d, b);
24663         function __() { this.constructor = d; }
24664         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24665     };
24666 })();
24667 Object.defineProperty(exports, "__esModule", { value: true });
24668 var _ = require("underscore");
24669 var vd = require("virtual-dom");
24670 var Observable_1 = require("rxjs/Observable");
24671 require("rxjs/add/observable/fromPromise");
24672 require("rxjs/add/observable/of");
24673 require("rxjs/add/operator/combineLatest");
24674 require("rxjs/add/operator/distinct");
24675 require("rxjs/add/operator/distinctUntilChanged");
24676 require("rxjs/add/operator/filter");
24677 require("rxjs/add/operator/map");
24678 require("rxjs/add/operator/mergeMap");
24679 require("rxjs/add/operator/pluck");
24680 require("rxjs/add/operator/scan");
24681 var Component_1 = require("../Component");
24682 var DescriptionState = /** @class */ (function () {
24683     function DescriptionState() {
24684     }
24685     return DescriptionState;
24686 }());
24687 var RouteState = /** @class */ (function () {
24688     function RouteState() {
24689     }
24690     return RouteState;
24691 }());
24692 var RouteTrack = /** @class */ (function () {
24693     function RouteTrack() {
24694         this.nodeInstructions = [];
24695         this.nodeInstructionsOrdered = [];
24696     }
24697     return RouteTrack;
24698 }());
24699 var RouteComponent = /** @class */ (function (_super) {
24700     __extends(RouteComponent, _super);
24701     function RouteComponent(name, container, navigator) {
24702         return _super.call(this, name, container, navigator) || this;
24703     }
24704     RouteComponent.prototype._activate = function () {
24705         var _this = this;
24706         var _slowedStream$;
24707         _slowedStream$ = this._navigator.stateService.currentState$.filter(function (frame) {
24708             return (frame.id % 2) === 0;
24709         }).filter(function (frame) {
24710             return frame.state.nodesAhead < 15;
24711         }).distinctUntilChanged(undefined, function (frame) {
24712             return frame.state.lastNode.key;
24713         });
24714         var _routeTrack$;
24715         _routeTrack$ = this.configuration$.mergeMap(function (conf) {
24716             return Observable_1.Observable.from(conf.paths);
24717         }).distinct(function (p) {
24718             return p.sequenceKey;
24719         }).mergeMap(function (path) {
24720             return _this._navigator.apiV3.sequenceByKey$([path.sequenceKey])
24721                 .map(function (sequenceByKey) {
24722                 return sequenceByKey[path.sequenceKey];
24723             });
24724         }).combineLatest(this.configuration$, function (sequence, conf) {
24725             var i = 0;
24726             var instructionPlaces = [];
24727             for (var _i = 0, _a = conf.paths; _i < _a.length; _i++) {
24728                 var path = _a[_i];
24729                 if (path.sequenceKey === sequence.key) {
24730                     var nodeInstructions = [];
24731                     var saveKey = false;
24732                     for (var _b = 0, _c = sequence.keys; _b < _c.length; _b++) {
24733                         var key = _c[_b];
24734                         if (path.startKey === key) {
24735                             saveKey = true;
24736                         }
24737                         if (saveKey) {
24738                             var description = null;
24739                             for (var _d = 0, _e = path.infoKeys; _d < _e.length; _d++) {
24740                                 var infoKey = _e[_d];
24741                                 if (infoKey.key === key) {
24742                                     description = infoKey.description;
24743                                 }
24744                             }
24745                             nodeInstructions.push({ description: description, key: key });
24746                         }
24747                         if (path.stopKey === key) {
24748                             saveKey = false;
24749                         }
24750                     }
24751                     instructionPlaces.push({ nodeInstructions: nodeInstructions, place: i });
24752                 }
24753                 i++;
24754             }
24755             return instructionPlaces;
24756         }).scan(function (routeTrack, instructionPlaces) {
24757             for (var _i = 0, instructionPlaces_1 = instructionPlaces; _i < instructionPlaces_1.length; _i++) {
24758                 var instructionPlace = instructionPlaces_1[_i];
24759                 routeTrack.nodeInstructionsOrdered[instructionPlace.place] = instructionPlace.nodeInstructions;
24760             }
24761             routeTrack.nodeInstructions = _.flatten(routeTrack.nodeInstructionsOrdered);
24762             return routeTrack;
24763         }, new RouteTrack());
24764         this._disposable = _slowedStream$
24765             .combineLatest(_routeTrack$, this.configuration$, function (frame, routeTrack, conf) {
24766             return { conf: conf, frame: frame, routeTrack: routeTrack };
24767         }).scan(function (routeState, rtAndFrame) {
24768             if (rtAndFrame.conf.playing === undefined || rtAndFrame.conf.playing) {
24769                 routeState.routeTrack = rtAndFrame.routeTrack;
24770                 routeState.currentNode = rtAndFrame.frame.state.currentNode;
24771                 routeState.lastNode = rtAndFrame.frame.state.lastNode;
24772                 routeState.playing = true;
24773             }
24774             else {
24775                 _this._navigator.stateService.cutNodes();
24776                 routeState.playing = false;
24777             }
24778             return routeState;
24779         }, new RouteState())
24780             .filter(function (routeState) {
24781             return routeState.playing;
24782         }).filter(function (routeState) {
24783             for (var _i = 0, _a = routeState.routeTrack.nodeInstructions; _i < _a.length; _i++) {
24784                 var nodeInstruction = _a[_i];
24785                 if (!nodeInstruction) {
24786                     continue;
24787                 }
24788                 if (nodeInstruction.key === routeState.lastNode.key) {
24789                     return true;
24790                 }
24791             }
24792             return false;
24793         }).distinctUntilChanged(undefined, function (routeState) {
24794             return routeState.lastNode.key;
24795         }).mergeMap(function (routeState) {
24796             var i = 0;
24797             for (var _i = 0, _a = routeState.routeTrack.nodeInstructions; _i < _a.length; _i++) {
24798                 var nodeInstruction = _a[_i];
24799                 if (nodeInstruction.key === routeState.lastNode.key) {
24800                     break;
24801                 }
24802                 i++;
24803             }
24804             var nextInstruction = routeState.routeTrack.nodeInstructions[i + 1];
24805             if (!nextInstruction) {
24806                 return Observable_1.Observable.of(null);
24807             }
24808             return _this._navigator.graphService.cacheNode$(nextInstruction.key);
24809         }).combineLatest(this.configuration$, function (node, conf) {
24810             return { conf: conf, node: node };
24811         }).filter(function (cAN) {
24812             return cAN.node !== null && cAN.conf.playing;
24813         }).pluck("node").subscribe(this._navigator.stateService.appendNode$);
24814         this._disposableDescription = this._navigator.stateService.currentNode$
24815             .combineLatest(_routeTrack$, this.configuration$, function (node, routeTrack, conf) {
24816             if (conf.playing !== undefined && !conf.playing) {
24817                 return "quit";
24818             }
24819             var description = null;
24820             for (var _i = 0, _a = routeTrack.nodeInstructions; _i < _a.length; _i++) {
24821                 var nodeInstruction = _a[_i];
24822                 if (nodeInstruction.key === node.key) {
24823                     description = nodeInstruction.description;
24824                     break;
24825                 }
24826             }
24827             return description;
24828         }).scan(function (descriptionState, description) {
24829             if (description !== descriptionState.description && description !== null) {
24830                 descriptionState.description = description;
24831                 descriptionState.showsLeft = 6;
24832             }
24833             else {
24834                 descriptionState.showsLeft--;
24835             }
24836             if (description === "quit") {
24837                 descriptionState.description = null;
24838             }
24839             return descriptionState;
24840         }, new DescriptionState()).map(function (descriptionState) {
24841             if (descriptionState.showsLeft > 0 && descriptionState.description) {
24842                 return { name: _this._name, vnode: _this._getRouteAnnotationNode(descriptionState.description) };
24843             }
24844             else {
24845                 return { name: _this._name, vnode: vd.h("div", []) };
24846             }
24847         }).subscribe(this._container.domRenderer.render$);
24848     };
24849     RouteComponent.prototype._deactivate = function () {
24850         this._disposable.unsubscribe();
24851         this._disposableDescription.unsubscribe();
24852     };
24853     RouteComponent.prototype._getDefaultConfiguration = function () {
24854         return {};
24855     };
24856     RouteComponent.prototype.play = function () {
24857         this.configure({ playing: true });
24858     };
24859     RouteComponent.prototype.stop = function () {
24860         this.configure({ playing: false });
24861     };
24862     RouteComponent.prototype._getRouteAnnotationNode = function (description) {
24863         return vd.h("div.RouteFrame", {}, [
24864             vd.h("p", { textContent: description }, []),
24865         ]);
24866     };
24867     RouteComponent.componentName = "route";
24868     return RouteComponent;
24869 }(Component_1.Component));
24870 exports.RouteComponent = RouteComponent;
24871 Component_1.ComponentService.register(RouteComponent);
24872 exports.default = RouteComponent;
24873
24874 },{"../Component":291,"rxjs/Observable":29,"rxjs/add/observable/fromPromise":44,"rxjs/add/observable/of":46,"rxjs/add/operator/combineLatest":55,"rxjs/add/operator/distinct":59,"rxjs/add/operator/distinctUntilChanged":60,"rxjs/add/operator/filter":63,"rxjs/add/operator/map":67,"rxjs/add/operator/mergeMap":70,"rxjs/add/operator/pluck":72,"rxjs/add/operator/scan":78,"underscore":243,"virtual-dom":247}],317:[function(require,module,exports){
24875 "use strict";
24876 var __extends = (this && this.__extends) || (function () {
24877     var extendStatics = Object.setPrototypeOf ||
24878         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24879         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24880     return function (d, b) {
24881         extendStatics(d, b);
24882         function __() { this.constructor = d; }
24883         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24884     };
24885 })();
24886 Object.defineProperty(exports, "__esModule", { value: true });
24887 var Observable_1 = require("rxjs/Observable");
24888 require("rxjs/add/operator/buffer");
24889 require("rxjs/add/operator/debounceTime");
24890 require("rxjs/add/operator/filter");
24891 require("rxjs/add/operator/map");
24892 require("rxjs/add/operator/scan");
24893 var Component_1 = require("../Component");
24894 var StatsComponent = /** @class */ (function (_super) {
24895     __extends(StatsComponent, _super);
24896     function StatsComponent(name, container, navigator) {
24897         return _super.call(this, name, container, navigator) || this;
24898     }
24899     StatsComponent.prototype._activate = function () {
24900         var _this = this;
24901         this._sequenceSubscription = this._navigator.stateService.currentNode$
24902             .scan(function (keys, node) {
24903             var sKey = node.sequenceKey;
24904             keys.report = [];
24905             if (!(sKey in keys.reported)) {
24906                 keys.report = [sKey];
24907                 keys.reported[sKey] = true;
24908             }
24909             return keys;
24910         }, { report: [], reported: {} })
24911             .filter(function (keys) {
24912             return keys.report.length > 0;
24913         })
24914             .mergeMap(function (keys) {
24915             return _this._navigator.apiV3.sequenceViewAdd$(keys.report)
24916                 .catch(function (error, caught) {
24917                 console.error("Failed to report sequence stats (" + keys.report + ")", error);
24918                 return Observable_1.Observable.empty();
24919             });
24920         })
24921             .subscribe(function () { });
24922         this._imageSubscription = this._navigator.stateService.currentNode$
24923             .map(function (node) {
24924             return node.key;
24925         })
24926             .buffer(this._navigator.stateService.currentNode$.debounceTime(5000))
24927             .scan(function (keys, newKeys) {
24928             keys.report = [];
24929             for (var _i = 0, newKeys_1 = newKeys; _i < newKeys_1.length; _i++) {
24930                 var key = newKeys_1[_i];
24931                 if (!(key in keys.reported)) {
24932                     keys.report.push(key);
24933                     keys.reported[key] = true;
24934                 }
24935             }
24936             return keys;
24937         }, { report: [], reported: {} })
24938             .filter(function (keys) {
24939             return keys.report.length > 0;
24940         })
24941             .mergeMap(function (keys) {
24942             return _this._navigator.apiV3.imageViewAdd$(keys.report)
24943                 .catch(function (error, caught) {
24944                 console.error("Failed to report image stats (" + keys.report + ")", error);
24945                 return Observable_1.Observable.empty();
24946             });
24947         })
24948             .subscribe(function () { });
24949     };
24950     StatsComponent.prototype._deactivate = function () {
24951         this._sequenceSubscription.unsubscribe();
24952         this._imageSubscription.unsubscribe();
24953     };
24954     StatsComponent.prototype._getDefaultConfiguration = function () {
24955         return {};
24956     };
24957     StatsComponent.componentName = "stats";
24958     return StatsComponent;
24959 }(Component_1.Component));
24960 exports.StatsComponent = StatsComponent;
24961 Component_1.ComponentService.register(StatsComponent);
24962 exports.default = StatsComponent;
24963
24964 },{"../Component":291,"rxjs/Observable":29,"rxjs/add/operator/buffer":51,"rxjs/add/operator/debounceTime":57,"rxjs/add/operator/filter":63,"rxjs/add/operator/map":67,"rxjs/add/operator/scan":78}],318:[function(require,module,exports){
24965 "use strict";
24966 /// <reference path="../../../typings/index.d.ts" />
24967 var __extends = (this && this.__extends) || (function () {
24968     var extendStatics = Object.setPrototypeOf ||
24969         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24970         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
24971     return function (d, b) {
24972         extendStatics(d, b);
24973         function __() { this.constructor = d; }
24974         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24975     };
24976 })();
24977 Object.defineProperty(exports, "__esModule", { value: true });
24978 var vd = require("virtual-dom");
24979 var Observable_1 = require("rxjs/Observable");
24980 var Subject_1 = require("rxjs/Subject");
24981 require("rxjs/add/observable/combineLatest");
24982 require("rxjs/add/operator/do");
24983 require("rxjs/add/operator/distinctUntilChanged");
24984 require("rxjs/add/operator/filter");
24985 require("rxjs/add/operator/map");
24986 require("rxjs/add/operator/share");
24987 var Component_1 = require("../../Component");
24988 /**
24989  * @class DirectionComponent
24990  * @classdesc Component showing navigation arrows for steps and turns.
24991  */
24992 var DirectionComponent = /** @class */ (function (_super) {
24993     __extends(DirectionComponent, _super);
24994     function DirectionComponent(name, container, navigator, directionDOMRenderer) {
24995         var _this = _super.call(this, name, container, navigator) || this;
24996         _this._renderer = !!directionDOMRenderer ?
24997             directionDOMRenderer :
24998             new Component_1.DirectionDOMRenderer(_this.defaultConfiguration, container.element);
24999         _this._hoveredKeySubject$ = new Subject_1.Subject();
25000         _this._hoveredKey$ = _this._hoveredKeySubject$.share();
25001         return _this;
25002     }
25003     Object.defineProperty(DirectionComponent.prototype, "hoveredKey$", {
25004         /**
25005          * Get hovered key observable.
25006          *
25007          * @description An observable emitting the key of the node for the direction
25008          * arrow that is being hovered. When the mouse leaves a direction arrow null
25009          * is emitted.
25010          *
25011          * @returns {Observable<string>}
25012          */
25013         get: function () {
25014             return this._hoveredKey$;
25015         },
25016         enumerable: true,
25017         configurable: true
25018     });
25019     /**
25020      * Set highlight key.
25021      *
25022      * @description The arrow pointing towards the node corresponding to the
25023      * highlight key will be highlighted.
25024      *
25025      * @param {string} highlightKey Key of node to be highlighted if existing
25026      * among arrows.
25027      */
25028     DirectionComponent.prototype.setHighlightKey = function (highlightKey) {
25029         this.configure({ highlightKey: highlightKey });
25030     };
25031     /**
25032      * Set min width of container element.
25033      *
25034      * @description  Set min width of the non transformed container element holding
25035      * the navigation arrows. If the min width is larger than the max width the
25036      * min width value will be used.
25037      *
25038      * The container element is automatically resized when the resize
25039      * method on the Viewer class is called.
25040      *
25041      * @param {number} minWidth
25042      */
25043     DirectionComponent.prototype.setMinWidth = function (minWidth) {
25044         this.configure({ minWidth: minWidth });
25045     };
25046     /**
25047      * Set max width of container element.
25048      *
25049      * @description Set max width of the non transformed container element holding
25050      * the navigation arrows. If the min width is larger than the max width the
25051      * min width value will be used.
25052      *
25053      * The container element is automatically resized when the resize
25054      * method on the Viewer class is called.
25055      *
25056      * @param {number} minWidth
25057      */
25058     DirectionComponent.prototype.setMaxWidth = function (maxWidth) {
25059         this.configure({ maxWidth: maxWidth });
25060     };
25061     /** @inheritdoc */
25062     DirectionComponent.prototype.resize = function () {
25063         this._renderer.resize(this._container.element);
25064     };
25065     DirectionComponent.prototype._activate = function () {
25066         var _this = this;
25067         this._configurationSubscription = this._configuration$
25068             .subscribe(function (configuration) {
25069             _this._renderer.setConfiguration(configuration);
25070         });
25071         this._nodeSubscription = this._navigator.stateService.currentNode$
25072             .do(function (node) {
25073             _this._container.domRenderer.render$.next({ name: _this._name, vnode: vd.h("div", {}, []) });
25074             _this._renderer.setNode(node);
25075         })
25076             .withLatestFrom(this._configuration$)
25077             .switchMap(function (_a) {
25078             var node = _a[0], configuration = _a[1];
25079             return Observable_1.Observable
25080                 .combineLatest(node.spatialEdges$, configuration.distinguishSequence ?
25081                 _this._navigator.graphService
25082                     .cacheSequence$(node.sequenceKey)
25083                     .catch(function (error, caught) {
25084                     console.error("Failed to cache sequence (" + node.sequenceKey + ")", error);
25085                     return Observable_1.Observable.of(null);
25086                 }) :
25087                 Observable_1.Observable.of(null));
25088         })
25089             .subscribe(function (_a) {
25090             var edgeStatus = _a[0], sequence = _a[1];
25091             _this._renderer.setEdges(edgeStatus, sequence);
25092         });
25093         this._renderCameraSubscription = this._container.renderService.renderCameraFrame$
25094             .do(function (renderCamera) {
25095             _this._renderer.setRenderCamera(renderCamera);
25096         })
25097             .map(function (renderCamera) {
25098             return _this._renderer;
25099         })
25100             .filter(function (renderer) {
25101             return renderer.needsRender;
25102         })
25103             .map(function (renderer) {
25104             return { name: _this._name, vnode: renderer.render(_this._navigator) };
25105         })
25106             .subscribe(this._container.domRenderer.render$);
25107         this._hoveredKeySubscription = Observable_1.Observable
25108             .combineLatest([
25109             this._container.domRenderer.element$,
25110             this._container.renderService.renderCamera$,
25111             this._container.mouseService.mouseMove$.startWith(null),
25112             this._container.mouseService.mouseUp$.startWith(null),
25113         ], function (e, rc, mm, mu) {
25114             return e;
25115         })
25116             .map(function (element) {
25117             var elements = element.getElementsByClassName("DirectionsPerspective");
25118             for (var i = 0; i < elements.length; i++) {
25119                 var hovered = elements.item(i).querySelector(":hover");
25120                 if (hovered != null && hovered.hasAttribute("data-key")) {
25121                     return hovered.getAttribute("data-key");
25122                 }
25123             }
25124             return null;
25125         })
25126             .distinctUntilChanged()
25127             .subscribe(this._hoveredKeySubject$);
25128     };
25129     DirectionComponent.prototype._deactivate = function () {
25130         this._configurationSubscription.unsubscribe();
25131         this._nodeSubscription.unsubscribe();
25132         this._renderCameraSubscription.unsubscribe();
25133         this._hoveredKeySubscription.unsubscribe();
25134     };
25135     DirectionComponent.prototype._getDefaultConfiguration = function () {
25136         return {
25137             distinguishSequence: false,
25138             maxWidth: 460,
25139             minWidth: 260,
25140         };
25141     };
25142     /** @inheritdoc */
25143     DirectionComponent.componentName = "direction";
25144     return DirectionComponent;
25145 }(Component_1.Component));
25146 exports.DirectionComponent = DirectionComponent;
25147 Component_1.ComponentService.register(DirectionComponent);
25148 exports.default = DirectionComponent;
25149
25150 },{"../../Component":291,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/distinctUntilChanged":60,"rxjs/add/operator/do":61,"rxjs/add/operator/filter":63,"rxjs/add/operator/map":67,"rxjs/add/operator/share":79,"virtual-dom":247}],319:[function(require,module,exports){
25151 "use strict";
25152 Object.defineProperty(exports, "__esModule", { value: true });
25153 var Geo_1 = require("../../Geo");
25154 /**
25155  * @class DirectionDOMCalculator
25156  * @classdesc Helper class for calculating DOM CSS properties.
25157  */
25158 var DirectionDOMCalculator = /** @class */ (function () {
25159     function DirectionDOMCalculator(configuration, element) {
25160         this._spatial = new Geo_1.Spatial();
25161         this._minThresholdWidth = 320;
25162         this._maxThresholdWidth = 1480;
25163         this._minThresholdHeight = 240;
25164         this._maxThresholdHeight = 820;
25165         this._configure(configuration);
25166         this._resize(element);
25167         this._reset();
25168     }
25169     Object.defineProperty(DirectionDOMCalculator.prototype, "minWidth", {
25170         get: function () {
25171             return this._minWidth;
25172         },
25173         enumerable: true,
25174         configurable: true
25175     });
25176     Object.defineProperty(DirectionDOMCalculator.prototype, "maxWidth", {
25177         get: function () {
25178             return this._maxWidth;
25179         },
25180         enumerable: true,
25181         configurable: true
25182     });
25183     Object.defineProperty(DirectionDOMCalculator.prototype, "containerWidth", {
25184         get: function () {
25185             return this._containerWidth;
25186         },
25187         enumerable: true,
25188         configurable: true
25189     });
25190     Object.defineProperty(DirectionDOMCalculator.prototype, "containerWidthCss", {
25191         get: function () {
25192             return this._containerWidthCss;
25193         },
25194         enumerable: true,
25195         configurable: true
25196     });
25197     Object.defineProperty(DirectionDOMCalculator.prototype, "containerMarginCss", {
25198         get: function () {
25199             return this._containerMarginCss;
25200         },
25201         enumerable: true,
25202         configurable: true
25203     });
25204     Object.defineProperty(DirectionDOMCalculator.prototype, "containerLeftCss", {
25205         get: function () {
25206             return this._containerLeftCss;
25207         },
25208         enumerable: true,
25209         configurable: true
25210     });
25211     Object.defineProperty(DirectionDOMCalculator.prototype, "containerHeight", {
25212         get: function () {
25213             return this._containerHeight;
25214         },
25215         enumerable: true,
25216         configurable: true
25217     });
25218     Object.defineProperty(DirectionDOMCalculator.prototype, "containerHeightCss", {
25219         get: function () {
25220             return this._containerHeightCss;
25221         },
25222         enumerable: true,
25223         configurable: true
25224     });
25225     Object.defineProperty(DirectionDOMCalculator.prototype, "containerBottomCss", {
25226         get: function () {
25227             return this._containerBottomCss;
25228         },
25229         enumerable: true,
25230         configurable: true
25231     });
25232     Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleSize", {
25233         get: function () {
25234             return this._stepCircleSize;
25235         },
25236         enumerable: true,
25237         configurable: true
25238     });
25239     Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleSizeCss", {
25240         get: function () {
25241             return this._stepCircleSizeCss;
25242         },
25243         enumerable: true,
25244         configurable: true
25245     });
25246     Object.defineProperty(DirectionDOMCalculator.prototype, "stepCircleMarginCss", {
25247         get: function () {
25248             return this._stepCircleMarginCss;
25249         },
25250         enumerable: true,
25251         configurable: true
25252     });
25253     Object.defineProperty(DirectionDOMCalculator.prototype, "turnCircleSize", {
25254         get: function () {
25255             return this._turnCircleSize;
25256         },
25257         enumerable: true,
25258         configurable: true
25259     });
25260     Object.defineProperty(DirectionDOMCalculator.prototype, "turnCircleSizeCss", {
25261         get: function () {
25262             return this._turnCircleSizeCss;
25263         },
25264         enumerable: true,
25265         configurable: true
25266     });
25267     Object.defineProperty(DirectionDOMCalculator.prototype, "outerRadius", {
25268         get: function () {
25269             return this._outerRadius;
25270         },
25271         enumerable: true,
25272         configurable: true
25273     });
25274     Object.defineProperty(DirectionDOMCalculator.prototype, "innerRadius", {
25275         get: function () {
25276             return this._innerRadius;
25277         },
25278         enumerable: true,
25279         configurable: true
25280     });
25281     Object.defineProperty(DirectionDOMCalculator.prototype, "shadowOffset", {
25282         get: function () {
25283             return this._shadowOffset;
25284         },
25285         enumerable: true,
25286         configurable: true
25287     });
25288     /**
25289      * Configures the min and max width values.
25290      *
25291      * @param {IDirectionConfiguration} configuration Configuration
25292      * with min and max width values.
25293      */
25294     DirectionDOMCalculator.prototype.configure = function (configuration) {
25295         this._configure(configuration);
25296         this._reset();
25297     };
25298     /**
25299      * Resizes all properties according to the width and height
25300      * of the element.
25301      *
25302      * @param {HTMLElement} element The container element from which to extract
25303      * the width and height.
25304      */
25305     DirectionDOMCalculator.prototype.resize = function (element) {
25306         this._resize(element);
25307         this._reset();
25308     };
25309     /**
25310      * Calculates the coordinates on the unit circle for an angle.
25311      *
25312      * @param {number} angle Angle in radians.
25313      * @returns {Array<number>} The x and y coordinates on the unit circle.
25314      */
25315     DirectionDOMCalculator.prototype.angleToCoordinates = function (angle) {
25316         return [Math.cos(angle), Math.sin(angle)];
25317     };
25318     /**
25319      * Calculates the coordinates on the unit circle for the
25320      * relative angle between the first and second angle.
25321      *
25322      * @param {number} first Angle in radians.
25323      * @param {number} second Angle in radians.
25324      * @returns {Array<number>} The x and y coordinates on the unit circle
25325      * for the relative angle between the first and second angle.
25326      */
25327     DirectionDOMCalculator.prototype.relativeAngleToCoordiantes = function (first, second) {
25328         var relativeAngle = this._spatial.wrapAngle(first - second);
25329         return this.angleToCoordinates(relativeAngle);
25330     };
25331     DirectionDOMCalculator.prototype._configure = function (configuration) {
25332         this._minWidth = configuration.minWidth;
25333         this._maxWidth = this._getMaxWidth(configuration.minWidth, configuration.maxWidth);
25334     };
25335     DirectionDOMCalculator.prototype._resize = function (element) {
25336         this._elementWidth = element.offsetWidth;
25337         this._elementHeight = element.offsetHeight;
25338     };
25339     DirectionDOMCalculator.prototype._reset = function () {
25340         this._containerWidth = this._getContainerWidth(this._elementWidth, this._elementHeight);
25341         this._containerHeight = this._getContainerHeight(this.containerWidth);
25342         this._stepCircleSize = this._getStepCircleDiameter(this._containerHeight);
25343         this._turnCircleSize = this._getTurnCircleDiameter(this.containerHeight);
25344         this._outerRadius = this._getOuterRadius(this._containerHeight);
25345         this._innerRadius = this._getInnerRadius(this._containerHeight);
25346         this._shadowOffset = 3;
25347         this._containerWidthCss = this._numberToCssPixels(this._containerWidth);
25348         this._containerMarginCss = this._numberToCssPixels(-0.5 * this._containerWidth);
25349         this._containerLeftCss = this._numberToCssPixels(Math.floor(0.5 * this._elementWidth));
25350         this._containerHeightCss = this._numberToCssPixels(this._containerHeight);
25351         this._containerBottomCss = this._numberToCssPixels(Math.floor(-0.08 * this._containerHeight));
25352         this._stepCircleSizeCss = this._numberToCssPixels(this._stepCircleSize);
25353         this._stepCircleMarginCss = this._numberToCssPixels(-0.5 * this._stepCircleSize);
25354         this._turnCircleSizeCss = this._numberToCssPixels(this._turnCircleSize);
25355     };
25356     DirectionDOMCalculator.prototype._getContainerWidth = function (elementWidth, elementHeight) {
25357         var relativeWidth = (elementWidth - this._minThresholdWidth) / (this._maxThresholdWidth - this._minThresholdWidth);
25358         var relativeHeight = (elementHeight - this._minThresholdHeight) / (this._maxThresholdHeight - this._minThresholdHeight);
25359         var coeff = Math.max(0, Math.min(1, Math.min(relativeWidth, relativeHeight)));
25360         coeff = 0.04 * Math.round(25 * coeff);
25361         return this._minWidth + coeff * (this._maxWidth - this._minWidth);
25362     };
25363     DirectionDOMCalculator.prototype._getContainerHeight = function (containerWidth) {
25364         return 0.77 * containerWidth;
25365     };
25366     DirectionDOMCalculator.prototype._getStepCircleDiameter = function (containerHeight) {
25367         return 0.34 * containerHeight;
25368     };
25369     DirectionDOMCalculator.prototype._getTurnCircleDiameter = function (containerHeight) {
25370         return 0.3 * containerHeight;
25371     };
25372     DirectionDOMCalculator.prototype._getOuterRadius = function (containerHeight) {
25373         return 0.31 * containerHeight;
25374     };
25375     DirectionDOMCalculator.prototype._getInnerRadius = function (containerHeight) {
25376         return 0.125 * containerHeight;
25377     };
25378     DirectionDOMCalculator.prototype._numberToCssPixels = function (value) {
25379         return value + "px";
25380     };
25381     DirectionDOMCalculator.prototype._getMaxWidth = function (value, minWidth) {
25382         return value > minWidth ? value : minWidth;
25383     };
25384     return DirectionDOMCalculator;
25385 }());
25386 exports.DirectionDOMCalculator = DirectionDOMCalculator;
25387 exports.default = DirectionDOMCalculator;
25388
25389 },{"../../Geo":294}],320:[function(require,module,exports){
25390 "use strict";
25391 /// <reference path="../../../typings/index.d.ts" />
25392 Object.defineProperty(exports, "__esModule", { value: true });
25393 var vd = require("virtual-dom");
25394 var Component_1 = require("../../Component");
25395 var Edge_1 = require("../../Edge");
25396 var Error_1 = require("../../Error");
25397 var Geo_1 = require("../../Geo");
25398 /**
25399  * @class DirectionDOMRenderer
25400  * @classdesc DOM renderer for direction arrows.
25401  */
25402 var DirectionDOMRenderer = /** @class */ (function () {
25403     function DirectionDOMRenderer(configuration, element) {
25404         this._isEdge = false;
25405         this._spatial = new Geo_1.Spatial();
25406         this._calculator = new Component_1.DirectionDOMCalculator(configuration, element);
25407         this._node = null;
25408         this._rotation = { phi: 0, theta: 0 };
25409         this._epsilon = 0.5 * Math.PI / 180;
25410         this._highlightKey = null;
25411         this._distinguishSequence = false;
25412         this._needsRender = false;
25413         this._stepEdges = [];
25414         this._turnEdges = [];
25415         this._panoEdges = [];
25416         this._sequenceEdgeKeys = [];
25417         this._stepDirections = [
25418             Edge_1.EdgeDirection.StepForward,
25419             Edge_1.EdgeDirection.StepBackward,
25420             Edge_1.EdgeDirection.StepLeft,
25421             Edge_1.EdgeDirection.StepRight,
25422         ];
25423         this._turnDirections = [
25424             Edge_1.EdgeDirection.TurnLeft,
25425             Edge_1.EdgeDirection.TurnRight,
25426             Edge_1.EdgeDirection.TurnU,
25427         ];
25428         this._turnNames = {};
25429         this._turnNames[Edge_1.EdgeDirection.TurnLeft] = "TurnLeft";
25430         this._turnNames[Edge_1.EdgeDirection.TurnRight] = "TurnRight";
25431         this._turnNames[Edge_1.EdgeDirection.TurnU] = "TurnAround";
25432         // detects IE 8-11, then Edge 20+.
25433         var isIE = !!document.documentMode;
25434         this._isEdge = !isIE && !!window.StyleMedia;
25435     }
25436     Object.defineProperty(DirectionDOMRenderer.prototype, "needsRender", {
25437         /**
25438          * Get needs render.
25439          *
25440          * @returns {boolean} Value indicating whether render should be called.
25441          */
25442         get: function () {
25443             return this._needsRender;
25444         },
25445         enumerable: true,
25446         configurable: true
25447     });
25448     /**
25449      * Renders virtual DOM elements.
25450      *
25451      * @description Calling render resets the needs render property.
25452      */
25453     DirectionDOMRenderer.prototype.render = function (navigator) {
25454         this._needsRender = false;
25455         var rotation = this._rotation;
25456         var steps = [];
25457         var turns = [];
25458         if (this._node.pano) {
25459             steps = steps.concat(this._createPanoArrows(navigator, rotation));
25460         }
25461         else {
25462             steps = steps.concat(this._createPerspectiveToPanoArrows(navigator, rotation));
25463             steps = steps.concat(this._createStepArrows(navigator, rotation));
25464             turns = turns.concat(this._createTurnArrows(navigator));
25465         }
25466         return this._getContainer(steps, turns, rotation);
25467     };
25468     DirectionDOMRenderer.prototype.setEdges = function (edgeStatus, sequence) {
25469         this._setEdges(edgeStatus, sequence);
25470         this._setNeedsRender();
25471     };
25472     /**
25473      * Set node for which to show edges.
25474      *
25475      * @param {Node} node
25476      */
25477     DirectionDOMRenderer.prototype.setNode = function (node) {
25478         this._node = node;
25479         this._clearEdges();
25480         this._setNeedsRender();
25481     };
25482     /**
25483      * Set the render camera to use for calculating rotations.
25484      *
25485      * @param {RenderCamera} renderCamera
25486      */
25487     DirectionDOMRenderer.prototype.setRenderCamera = function (renderCamera) {
25488         var rotation = renderCamera.rotation;
25489         if (Math.abs(rotation.phi - this._rotation.phi) < this._epsilon) {
25490             return;
25491         }
25492         this._rotation = rotation;
25493         this._setNeedsRender();
25494     };
25495     /**
25496      * Set configuration values.
25497      *
25498      * @param {IDirectionConfiguration} configuration
25499      */
25500     DirectionDOMRenderer.prototype.setConfiguration = function (configuration) {
25501         var needsRender = false;
25502         if (this._highlightKey !== configuration.highlightKey ||
25503             this._distinguishSequence !== configuration.distinguishSequence) {
25504             this._highlightKey = configuration.highlightKey;
25505             this._distinguishSequence = configuration.distinguishSequence;
25506             needsRender = true;
25507         }
25508         if (this._calculator.minWidth !== configuration.minWidth ||
25509             this._calculator.maxWidth !== configuration.maxWidth) {
25510             this._calculator.configure(configuration);
25511             needsRender = true;
25512         }
25513         if (needsRender) {
25514             this._setNeedsRender();
25515         }
25516     };
25517     /**
25518      * Detect the element's width and height and resize
25519      * elements accordingly.
25520      *
25521      * @param {HTMLElement} element Viewer container element.
25522      */
25523     DirectionDOMRenderer.prototype.resize = function (element) {
25524         this._calculator.resize(element);
25525         this._setNeedsRender();
25526     };
25527     DirectionDOMRenderer.prototype._setNeedsRender = function () {
25528         if (this._node != null) {
25529             this._needsRender = true;
25530         }
25531     };
25532     DirectionDOMRenderer.prototype._clearEdges = function () {
25533         this._stepEdges = [];
25534         this._turnEdges = [];
25535         this._panoEdges = [];
25536         this._sequenceEdgeKeys = [];
25537     };
25538     DirectionDOMRenderer.prototype._setEdges = function (edgeStatus, sequence) {
25539         this._stepEdges = [];
25540         this._turnEdges = [];
25541         this._panoEdges = [];
25542         this._sequenceEdgeKeys = [];
25543         for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
25544             var edge = _a[_i];
25545             var direction = edge.data.direction;
25546             if (this._stepDirections.indexOf(direction) > -1) {
25547                 this._stepEdges.push(edge);
25548                 continue;
25549             }
25550             if (this._turnDirections.indexOf(direction) > -1) {
25551                 this._turnEdges.push(edge);
25552                 continue;
25553             }
25554             if (edge.data.direction === Edge_1.EdgeDirection.Pano) {
25555                 this._panoEdges.push(edge);
25556             }
25557         }
25558         if (this._distinguishSequence && sequence != null) {
25559             var edges = this._panoEdges
25560                 .concat(this._stepEdges)
25561                 .concat(this._turnEdges);
25562             for (var _b = 0, edges_1 = edges; _b < edges_1.length; _b++) {
25563                 var edge = edges_1[_b];
25564                 var edgeKey = edge.to;
25565                 for (var _c = 0, _d = sequence.keys; _c < _d.length; _c++) {
25566                     var sequenceKey = _d[_c];
25567                     if (sequenceKey === edgeKey) {
25568                         this._sequenceEdgeKeys.push(edgeKey);
25569                         break;
25570                     }
25571                 }
25572             }
25573         }
25574     };
25575     DirectionDOMRenderer.prototype._createPanoArrows = function (navigator, rotation) {
25576         var arrows = [];
25577         for (var _i = 0, _a = this._panoEdges; _i < _a.length; _i++) {
25578             var panoEdge = _a[_i];
25579             arrows.push(this._createVNodeByKey(navigator, panoEdge.to, panoEdge.data.worldMotionAzimuth, rotation, this._calculator.outerRadius, "DirectionsArrowPano"));
25580         }
25581         for (var _b = 0, _c = this._stepEdges; _b < _c.length; _b++) {
25582             var stepEdge = _c[_b];
25583             arrows.push(this._createPanoToPerspectiveArrow(navigator, stepEdge.to, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction));
25584         }
25585         return arrows;
25586     };
25587     DirectionDOMRenderer.prototype._createPanoToPerspectiveArrow = function (navigator, key, azimuth, rotation, direction) {
25588         var threshold = Math.PI / 8;
25589         var relativePhi = rotation.phi;
25590         switch (direction) {
25591             case Edge_1.EdgeDirection.StepBackward:
25592                 relativePhi = rotation.phi - Math.PI;
25593                 break;
25594             case Edge_1.EdgeDirection.StepLeft:
25595                 relativePhi = rotation.phi + Math.PI / 2;
25596                 break;
25597             case Edge_1.EdgeDirection.StepRight:
25598                 relativePhi = rotation.phi - Math.PI / 2;
25599                 break;
25600             default:
25601                 break;
25602         }
25603         if (Math.abs(this._spatial.wrapAngle(azimuth - relativePhi)) < threshold) {
25604             return this._createVNodeByKey(navigator, key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowStep");
25605         }
25606         return this._createVNodeDisabled(key, azimuth, rotation);
25607     };
25608     DirectionDOMRenderer.prototype._createPerspectiveToPanoArrows = function (navigator, rotation) {
25609         var arrows = [];
25610         for (var _i = 0, _a = this._panoEdges; _i < _a.length; _i++) {
25611             var panoEdge = _a[_i];
25612             arrows.push(this._createVNodeByKey(navigator, panoEdge.to, panoEdge.data.worldMotionAzimuth, rotation, this._calculator.innerRadius, "DirectionsArrowPano", true));
25613         }
25614         return arrows;
25615     };
25616     DirectionDOMRenderer.prototype._createStepArrows = function (navigator, rotation) {
25617         var arrows = [];
25618         for (var _i = 0, _a = this._stepEdges; _i < _a.length; _i++) {
25619             var stepEdge = _a[_i];
25620             arrows.push(this._createVNodeByDirection(navigator, stepEdge.to, stepEdge.data.worldMotionAzimuth, rotation, stepEdge.data.direction));
25621         }
25622         return arrows;
25623     };
25624     DirectionDOMRenderer.prototype._createTurnArrows = function (navigator) {
25625         var turns = [];
25626         for (var _i = 0, _a = this._turnEdges; _i < _a.length; _i++) {
25627             var turnEdge = _a[_i];
25628             var direction = turnEdge.data.direction;
25629             var name_1 = this._turnNames[direction];
25630             turns.push(this._createVNodeByTurn(navigator, turnEdge.to, name_1, direction));
25631         }
25632         return turns;
25633     };
25634     DirectionDOMRenderer.prototype._createVNodeByKey = function (navigator, key, azimuth, rotation, offset, className, shiftVertically) {
25635         var onClick = function (e) {
25636             navigator.moveToKey$(key)
25637                 .subscribe(undefined, function (error) {
25638                 if (!(error instanceof Error_1.AbortMapillaryError)) {
25639                     console.error(error);
25640                 }
25641             });
25642         };
25643         return this._createVNode(key, azimuth, rotation, offset, className, "DirectionsCircle", onClick, shiftVertically);
25644     };
25645     DirectionDOMRenderer.prototype._createVNodeByDirection = function (navigator, key, azimuth, rotation, direction) {
25646         var onClick = function (e) {
25647             navigator.moveDir$(direction)
25648                 .subscribe(undefined, function (error) {
25649                 if (!(error instanceof Error_1.AbortMapillaryError)) {
25650                     console.error(error);
25651                 }
25652             });
25653         };
25654         return this._createVNode(key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowStep", "DirectionsCircle", onClick);
25655     };
25656     DirectionDOMRenderer.prototype._createVNodeByTurn = function (navigator, key, className, direction) {
25657         var onClick = function (e) {
25658             navigator.moveDir$(direction)
25659                 .subscribe(undefined, function (error) {
25660                 if (!(error instanceof Error_1.AbortMapillaryError)) {
25661                     console.error(error);
25662                 }
25663             });
25664         };
25665         var style = {
25666             height: this._calculator.turnCircleSizeCss,
25667             transform: "rotate(0)",
25668             width: this._calculator.turnCircleSizeCss,
25669         };
25670         switch (direction) {
25671             case Edge_1.EdgeDirection.TurnLeft:
25672                 style.left = "5px";
25673                 style.top = "5px";
25674                 break;
25675             case Edge_1.EdgeDirection.TurnRight:
25676                 style.right = "5px";
25677                 style.top = "5px";
25678                 break;
25679             case Edge_1.EdgeDirection.TurnU:
25680                 style.left = "5px";
25681                 style.bottom = "5px";
25682                 break;
25683             default:
25684                 break;
25685         }
25686         var circleProperties = {
25687             attributes: {
25688                 "data-key": key,
25689             },
25690             onclick: onClick,
25691             style: style,
25692         };
25693         var circleClassName = "TurnCircle";
25694         if (this._sequenceEdgeKeys.indexOf(key) > -1) {
25695             circleClassName += "Sequence";
25696         }
25697         if (this._highlightKey === key) {
25698             circleClassName += "Highlight";
25699         }
25700         var turn = vd.h("div." + className, {}, []);
25701         return vd.h("div." + circleClassName, circleProperties, [turn]);
25702     };
25703     DirectionDOMRenderer.prototype._createVNodeDisabled = function (key, azimuth, rotation) {
25704         return this._createVNode(key, azimuth, rotation, this._calculator.outerRadius, "DirectionsArrowDisabled", "DirectionsCircleDisabled");
25705     };
25706     DirectionDOMRenderer.prototype._createVNode = function (key, azimuth, rotation, radius, className, circleClassName, onClick, shiftVertically) {
25707         var translation = this._calculator.angleToCoordinates(azimuth - rotation.phi);
25708         // rotate 90 degrees clockwise and flip over X-axis
25709         var translationX = Math.round(-radius * translation[1] + 0.5 * this._calculator.containerWidth);
25710         var translationY = Math.round(-radius * translation[0] + 0.5 * this._calculator.containerHeight);
25711         var shadowTranslation = this._calculator.relativeAngleToCoordiantes(azimuth, rotation.phi);
25712         var shadowOffset = this._calculator.shadowOffset;
25713         var shadowTranslationX = -shadowOffset * shadowTranslation[1];
25714         var shadowTranslationY = shadowOffset * shadowTranslation[0];
25715         var filter = "drop-shadow(" + shadowTranslationX + "px " + shadowTranslationY + "px 1px rgba(0,0,0,0.8))";
25716         var properties = {
25717             style: {
25718                 "-webkit-filter": filter,
25719                 filter: filter,
25720             },
25721         };
25722         var chevron = vd.h("div." + className, properties, []);
25723         var azimuthDeg = -this._spatial.radToDeg(azimuth - rotation.phi);
25724         var circleTransform = shiftVertically ?
25725             "translate(" + translationX + "px, " + translationY + "px) rotate(" + azimuthDeg + "deg) translateZ(-0.01px)" :
25726             "translate(" + translationX + "px, " + translationY + "px) rotate(" + azimuthDeg + "deg)";
25727         var circleProperties = {
25728             attributes: { "data-key": key },
25729             onclick: onClick,
25730             style: {
25731                 height: this._calculator.stepCircleSizeCss,
25732                 marginLeft: this._calculator.stepCircleMarginCss,
25733                 marginTop: this._calculator.stepCircleMarginCss,
25734                 transform: circleTransform,
25735                 width: this._calculator.stepCircleSizeCss,
25736             },
25737         };
25738         if (this._sequenceEdgeKeys.indexOf(key) > -1) {
25739             circleClassName += "Sequence";
25740         }
25741         if (this._highlightKey === key) {
25742             circleClassName += "Highlight";
25743         }
25744         return vd.h("div." + circleClassName, circleProperties, [chevron]);
25745     };
25746     DirectionDOMRenderer.prototype._getContainer = function (steps, turns, rotation) {
25747         // edge does not handle hover on perspective transforms.
25748         var transform = this._isEdge ?
25749             "rotateX(60deg)" :
25750             "perspective(" + this._calculator.containerWidthCss + ") rotateX(60deg)";
25751         var properties = {
25752             oncontextmenu: function (event) { event.preventDefault(); },
25753             style: {
25754                 bottom: this._calculator.containerBottomCss,
25755                 height: this._calculator.containerHeightCss,
25756                 left: this._calculator.containerLeftCss,
25757                 marginLeft: this._calculator.containerMarginCss,
25758                 transform: transform,
25759                 width: this._calculator.containerWidthCss,
25760             },
25761         };
25762         return vd.h("div.DirectionsPerspective", properties, turns.concat(steps));
25763     };
25764     return DirectionDOMRenderer;
25765 }());
25766 exports.DirectionDOMRenderer = DirectionDOMRenderer;
25767 exports.default = DirectionDOMRenderer;
25768
25769 },{"../../Component":291,"../../Edge":292,"../../Error":293,"../../Geo":294,"virtual-dom":247}],321:[function(require,module,exports){
25770 "use strict";
25771 var __extends = (this && this.__extends) || (function () {
25772     var extendStatics = Object.setPrototypeOf ||
25773         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25774         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25775     return function (d, b) {
25776         extendStatics(d, b);
25777         function __() { this.constructor = d; }
25778         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
25779     };
25780 })();
25781 Object.defineProperty(exports, "__esModule", { value: true });
25782 var Observable_1 = require("rxjs/Observable");
25783 var Subject_1 = require("rxjs/Subject");
25784 require("rxjs/add/operator/catch");
25785 require("rxjs/add/operator/combineLatest");
25786 require("rxjs/add/operator/debounceTime");
25787 require("rxjs/add/operator/distinctUntilChanged");
25788 require("rxjs/add/operator/filter");
25789 require("rxjs/add/operator/map");
25790 require("rxjs/add/operator/pairwise");
25791 require("rxjs/add/operator/publish");
25792 require("rxjs/add/operator/publishReplay");
25793 require("rxjs/add/operator/scan");
25794 require("rxjs/add/operator/skipWhile");
25795 require("rxjs/add/operator/startWith");
25796 require("rxjs/add/operator/switchMap");
25797 require("rxjs/add/operator/takeUntil");
25798 require("rxjs/add/operator/withLatestFrom");
25799 var Component_1 = require("../../Component");
25800 var Render_1 = require("../../Render");
25801 var Tiles_1 = require("../../Tiles");
25802 var Utils_1 = require("../../Utils");
25803 var ImagePlaneComponent = /** @class */ (function (_super) {
25804     __extends(ImagePlaneComponent, _super);
25805     function ImagePlaneComponent(name, container, navigator) {
25806         var _this = _super.call(this, name, container, navigator) || this;
25807         _this._imageTileLoader = new Tiles_1.ImageTileLoader(Utils_1.Urls.tileScheme, Utils_1.Urls.tileDomain, Utils_1.Urls.origin);
25808         _this._roiCalculator = new Tiles_1.RegionOfInterestCalculator();
25809         _this._rendererOperation$ = new Subject_1.Subject();
25810         _this._rendererCreator$ = new Subject_1.Subject();
25811         _this._rendererDisposer$ = new Subject_1.Subject();
25812         _this._renderer$ = _this._rendererOperation$
25813             .scan(function (renderer, operation) {
25814             return operation(renderer);
25815         }, null)
25816             .filter(function (renderer) {
25817             return renderer != null;
25818         })
25819             .distinctUntilChanged(undefined, function (renderer) {
25820             return renderer.frameId;
25821         });
25822         _this._rendererCreator$
25823             .map(function () {
25824             return function (renderer) {
25825                 if (renderer != null) {
25826                     throw new Error("Multiple image plane states can not be created at the same time");
25827                 }
25828                 return new Component_1.ImagePlaneGLRenderer();
25829             };
25830         })
25831             .subscribe(_this._rendererOperation$);
25832         _this._rendererDisposer$
25833             .map(function () {
25834             return function (renderer) {
25835                 renderer.dispose();
25836                 return null;
25837             };
25838         })
25839             .subscribe(_this._rendererOperation$);
25840         return _this;
25841     }
25842     ImagePlaneComponent.prototype._activate = function () {
25843         var _this = this;
25844         this._rendererSubscription = this._renderer$
25845             .map(function (renderer) {
25846             var renderHash = {
25847                 name: _this._name,
25848                 render: {
25849                     frameId: renderer.frameId,
25850                     needsRender: renderer.needsRender,
25851                     render: renderer.render.bind(renderer),
25852                     stage: Render_1.GLRenderStage.Background,
25853                 },
25854             };
25855             renderer.clearNeedsRender();
25856             return renderHash;
25857         })
25858             .subscribe(this._container.glRenderer.render$);
25859         this._rendererCreator$.next(null);
25860         this._stateSubscription = this._navigator.stateService.currentState$
25861             .map(function (frame) {
25862             return function (renderer) {
25863                 renderer.updateFrame(frame);
25864                 return renderer;
25865             };
25866         })
25867             .subscribe(this._rendererOperation$);
25868         var textureProvider$ = this._navigator.stateService.currentState$
25869             .distinctUntilChanged(undefined, function (frame) {
25870             return frame.state.currentNode.key;
25871         })
25872             .combineLatest(this._configuration$)
25873             .filter(function (args) {
25874             return args[1].imageTiling === true;
25875         })
25876             .map(function (args) {
25877             return args[0];
25878         })
25879             .withLatestFrom(this._container.glRenderer.webGLRenderer$, this._container.renderService.size$)
25880             .map(function (_a) {
25881             var frame = _a[0], renderer = _a[1], size = _a[2];
25882             var state = frame.state;
25883             var viewportSize = Math.max(size.width, size.height);
25884             var currentNode = state.currentNode;
25885             var currentTransform = state.currentTransform;
25886             var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512;
25887             return new Tiles_1.TextureProvider(currentNode.key, currentTransform.basicWidth, currentTransform.basicHeight, tileSize, currentNode.image, _this._imageTileLoader, new Tiles_1.ImageTileStore(), renderer);
25888         })
25889             .publishReplay(1)
25890             .refCount();
25891         this._textureProviderSubscription = textureProvider$.subscribe(function () { });
25892         this._setTextureProviderSubscription = textureProvider$
25893             .map(function (provider) {
25894             return function (renderer) {
25895                 renderer.setTextureProvider(provider.key, provider);
25896                 return renderer;
25897             };
25898         })
25899             .subscribe(this._rendererOperation$);
25900         this._setTileSizeSubscription = this._container.renderService.size$
25901             .switchMap(function (size) {
25902             return Observable_1.Observable
25903                 .combineLatest(textureProvider$, Observable_1.Observable.of(size))
25904                 .first();
25905         })
25906             .subscribe(function (_a) {
25907             var provider = _a[0], size = _a[1];
25908             var viewportSize = Math.max(size.width, size.height);
25909             var tileSize = viewportSize > 2048 ? 2048 : viewportSize > 1024 ? 1024 : 512;
25910             provider.setTileSize(tileSize);
25911         });
25912         this._abortTextureProviderSubscription = textureProvider$
25913             .pairwise()
25914             .subscribe(function (pair) {
25915             var previous = pair[0];
25916             previous.abort();
25917         });
25918         var roiTrigger$ = Observable_1.Observable
25919             .combineLatest(this._container.renderService.renderCameraFrame$, this._container.renderService.size$.debounceTime(250))
25920             .map(function (_a) {
25921             var camera = _a[0], size = _a[1];
25922             return [
25923                 camera.camera.position.clone(),
25924                 camera.camera.lookat.clone(),
25925                 camera.zoom.valueOf(),
25926                 size.height.valueOf(),
25927                 size.width.valueOf()
25928             ];
25929         })
25930             .pairwise()
25931             .skipWhile(function (pls) {
25932             return pls[1][2] - pls[0][2] < 0 || pls[1][2] === 0;
25933         })
25934             .map(function (pls) {
25935             var samePosition = pls[0][0].equals(pls[1][0]);
25936             var sameLookat = pls[0][1].equals(pls[1][1]);
25937             var sameZoom = pls[0][2] === pls[1][2];
25938             var sameHeight = pls[0][3] === pls[1][3];
25939             var sameWidth = pls[0][4] === pls[1][4];
25940             return samePosition && sameLookat && sameZoom && sameHeight && sameWidth;
25941         })
25942             .distinctUntilChanged()
25943             .filter(function (stalled) {
25944             return stalled;
25945         })
25946             .switchMap(function (stalled) {
25947             return _this._container.renderService.renderCameraFrame$
25948                 .first();
25949         })
25950             .withLatestFrom(this._container.renderService.size$, this._navigator.stateService.currentTransform$);
25951         this._setRegionOfInterestSubscription = textureProvider$
25952             .switchMap(function (provider) {
25953             return roiTrigger$
25954                 .map(function (_a) {
25955                 var camera = _a[0], size = _a[1], transform = _a[2];
25956                 return [
25957                     _this._roiCalculator.computeRegionOfInterest(camera, size, transform),
25958                     provider,
25959                 ];
25960             });
25961         })
25962             .filter(function (args) {
25963             return !args[1].disposed;
25964         })
25965             .subscribe(function (args) {
25966             var roi = args[0];
25967             var provider = args[1];
25968             provider.setRegionOfInterest(roi);
25969         });
25970         var hasTexture$ = textureProvider$
25971             .switchMap(function (provider) {
25972             return provider.hasTexture$;
25973         })
25974             .startWith(false)
25975             .publishReplay(1)
25976             .refCount();
25977         this._hasTextureSubscription = hasTexture$.subscribe(function () { });
25978         var nodeImage$ = this._navigator.stateService.currentState$
25979             .filter(function (frame) {
25980             return frame.state.nodesAhead === 0;
25981         })
25982             .map(function (frame) {
25983             return frame.state.currentNode;
25984         })
25985             .distinctUntilChanged(undefined, function (node) {
25986             return node.key;
25987         })
25988             .debounceTime(1000)
25989             .withLatestFrom(hasTexture$)
25990             .filter(function (args) {
25991             return !args[1];
25992         })
25993             .map(function (args) {
25994             return args[0];
25995         })
25996             .filter(function (node) {
25997             return node.pano ?
25998                 Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize :
25999                 Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize;
26000         })
26001             .switchMap(function (node) {
26002             var baseImageSize = node.pano ?
26003                 Utils_1.Settings.basePanoramaSize :
26004                 Utils_1.Settings.baseImageSize;
26005             if (Math.max(node.image.width, node.image.height) > baseImageSize) {
26006                 return Observable_1.Observable.empty();
26007             }
26008             var image$ = node
26009                 .cacheImage$(Utils_1.Settings.maxImageSize)
26010                 .map(function (n) {
26011                 return [n.image, n];
26012             });
26013             return image$
26014                 .takeUntil(hasTexture$
26015                 .filter(function (hasTexture) {
26016                 return hasTexture;
26017             }))
26018                 .catch(function (error, caught) {
26019                 console.error("Failed to fetch high res image (" + node.key + ")", error);
26020                 return Observable_1.Observable.empty();
26021             });
26022         })
26023             .publish()
26024             .refCount();
26025         this._updateBackgroundSubscription = nodeImage$
26026             .withLatestFrom(textureProvider$)
26027             .subscribe(function (args) {
26028             if (args[0][1].key !== args[1].key ||
26029                 args[1].disposed) {
26030                 return;
26031             }
26032             args[1].updateBackground(args[0][0]);
26033         });
26034         this._updateTextureImageSubscription = nodeImage$
26035             .map(function (imn) {
26036             return function (renderer) {
26037                 renderer.updateTextureImage(imn[0], imn[1]);
26038                 return renderer;
26039             };
26040         })
26041             .subscribe(this._rendererOperation$);
26042     };
26043     ImagePlaneComponent.prototype._deactivate = function () {
26044         this._rendererDisposer$.next(null);
26045         this._abortTextureProviderSubscription.unsubscribe();
26046         this._hasTextureSubscription.unsubscribe();
26047         this._rendererSubscription.unsubscribe();
26048         this._setRegionOfInterestSubscription.unsubscribe();
26049         this._setTextureProviderSubscription.unsubscribe();
26050         this._setTileSizeSubscription.unsubscribe();
26051         this._stateSubscription.unsubscribe();
26052         this._textureProviderSubscription.unsubscribe();
26053         this._updateBackgroundSubscription.unsubscribe();
26054         this._updateTextureImageSubscription.unsubscribe();
26055     };
26056     ImagePlaneComponent.prototype._getDefaultConfiguration = function () {
26057         return { imageTiling: false };
26058     };
26059     ImagePlaneComponent.componentName = "imagePlane";
26060     return ImagePlaneComponent;
26061 }(Component_1.Component));
26062 exports.ImagePlaneComponent = ImagePlaneComponent;
26063 Component_1.ComponentService.register(ImagePlaneComponent);
26064 exports.default = ImagePlaneComponent;
26065
26066 },{"../../Component":291,"../../Render":297,"../../Tiles":300,"../../Utils":301,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/operator/catch":54,"rxjs/add/operator/combineLatest":55,"rxjs/add/operator/debounceTime":57,"rxjs/add/operator/distinctUntilChanged":60,"rxjs/add/operator/filter":63,"rxjs/add/operator/map":67,"rxjs/add/operator/pairwise":71,"rxjs/add/operator/publish":73,"rxjs/add/operator/publishReplay":74,"rxjs/add/operator/scan":78,"rxjs/add/operator/skipWhile":82,"rxjs/add/operator/startWith":83,"rxjs/add/operator/switchMap":84,"rxjs/add/operator/takeUntil":86,"rxjs/add/operator/withLatestFrom":90}],322:[function(require,module,exports){
26067 "use strict";
26068 /// <reference path="../../../typings/index.d.ts" />
26069 Object.defineProperty(exports, "__esModule", { value: true });
26070 var THREE = require("three");
26071 var Component_1 = require("../../Component");
26072 var ImagePlaneFactory = /** @class */ (function () {
26073     function ImagePlaneFactory(imagePlaneDepth, imageSphereRadius) {
26074         this._imagePlaneDepth = imagePlaneDepth != null ? imagePlaneDepth : 200;
26075         this._imageSphereRadius = imageSphereRadius != null ? imageSphereRadius : 200;
26076     }
26077     ImagePlaneFactory.prototype.createMesh = function (node, transform) {
26078         var mesh = node.pano ?
26079             this._createImageSphere(node, transform) :
26080             this._createImagePlane(node, transform);
26081         return mesh;
26082     };
26083     ImagePlaneFactory.prototype._createImageSphere = function (node, transform) {
26084         var texture = this._createTexture(node.image);
26085         var materialParameters = this._createSphereMaterialParameters(transform, texture);
26086         var material = new THREE.ShaderMaterial(materialParameters);
26087         var mesh = this._useMesh(transform, node) ?
26088             new THREE.Mesh(this._getImageSphereGeo(transform, node), material) :
26089             new THREE.Mesh(this._getFlatImageSphereGeo(transform), material);
26090         return mesh;
26091     };
26092     ImagePlaneFactory.prototype._createImagePlane = function (node, transform) {
26093         var texture = this._createTexture(node.image);
26094         var materialParameters = this._createPlaneMaterialParameters(transform, texture);
26095         var material = new THREE.ShaderMaterial(materialParameters);
26096         var geometry = this._useMesh(transform, node) ?
26097             this._getImagePlaneGeo(transform, node) :
26098             this._getFlatImagePlaneGeo(transform);
26099         return new THREE.Mesh(geometry, material);
26100     };
26101     ImagePlaneFactory.prototype._createSphereMaterialParameters = function (transform, texture) {
26102         var gpano = transform.gpano;
26103         var halfCroppedWidth = (gpano.FullPanoWidthPixels - gpano.CroppedAreaImageWidthPixels) / 2;
26104         var phiShift = 2 * Math.PI * (gpano.CroppedAreaLeftPixels - halfCroppedWidth) / gpano.FullPanoWidthPixels;
26105         var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels;
26106         var halfCroppedHeight = (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels) / 2;
26107         var thetaShift = Math.PI * (halfCroppedHeight - gpano.CroppedAreaTopPixels) / gpano.FullPanoHeightPixels;
26108         var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels;
26109         var materialParameters = {
26110             depthWrite: false,
26111             fragmentShader: Component_1.ImagePlaneShaders.equirectangular.fragment,
26112             side: THREE.DoubleSide,
26113             transparent: true,
26114             uniforms: {
26115                 opacity: {
26116                     type: "f",
26117                     value: 1,
26118                 },
26119                 phiLength: {
26120                     type: "f",
26121                     value: phiLength,
26122                 },
26123                 phiShift: {
26124                     type: "f",
26125                     value: phiShift,
26126                 },
26127                 projectorMat: {
26128                     type: "m4",
26129                     value: transform.rt,
26130                 },
26131                 projectorTex: {
26132                     type: "t",
26133                     value: texture,
26134                 },
26135                 thetaLength: {
26136                     type: "f",
26137                     value: thetaLength,
26138                 },
26139                 thetaShift: {
26140                     type: "f",
26141                     value: thetaShift,
26142                 },
26143             },
26144             vertexShader: Component_1.ImagePlaneShaders.equirectangular.vertex,
26145         };
26146         return materialParameters;
26147     };
26148     ImagePlaneFactory.prototype._createPlaneMaterialParameters = function (transform, texture) {
26149         var materialParameters = {
26150             depthWrite: false,
26151             fragmentShader: Component_1.ImagePlaneShaders.perspective.fragment,
26152             side: THREE.DoubleSide,
26153             transparent: true,
26154             uniforms: {
26155                 bbox: {
26156                     type: "v4",
26157                     value: new THREE.Vector4(0, 0, 1, 1),
26158                 },
26159                 opacity: {
26160                     type: "f",
26161                     value: 1,
26162                 },
26163                 projectorMat: {
26164                     type: "m4",
26165                     value: transform.projectorMatrix(),
26166                 },
26167                 projectorTex: {
26168                     type: "t",
26169                     value: texture,
26170                 },
26171             },
26172             vertexShader: Component_1.ImagePlaneShaders.perspective.vertex,
26173         };
26174         return materialParameters;
26175     };
26176     ImagePlaneFactory.prototype._createTexture = function (image) {
26177         var texture = new THREE.Texture(image);
26178         texture.minFilter = THREE.LinearFilter;
26179         texture.needsUpdate = true;
26180         return texture;
26181     };
26182     ImagePlaneFactory.prototype._useMesh = function (transform, node) {
26183         return node.mesh.vertices.length && transform.hasValidScale;
26184     };
26185     ImagePlaneFactory.prototype._getImageSphereGeo = function (transform, node) {
26186         var t = new THREE.Matrix4().getInverse(transform.srt);
26187         // push everything at least 5 meters in front of the camera
26188         var minZ = 5.0 * transform.scale;
26189         var maxZ = this._imageSphereRadius * transform.scale;
26190         var vertices = node.mesh.vertices;
26191         var numVertices = vertices.length / 3;
26192         var positions = new Float32Array(vertices.length);
26193         for (var i = 0; i < numVertices; ++i) {
26194             var index = 3 * i;
26195             var x = vertices[index + 0];
26196             var y = vertices[index + 1];
26197             var z = vertices[index + 2];
26198             var l = Math.sqrt(x * x + y * y + z * z);
26199             var boundedL = Math.max(minZ, Math.min(l, maxZ));
26200             var factor = boundedL / l;
26201             var p = new THREE.Vector3(x * factor, y * factor, z * factor);
26202             p.applyMatrix4(t);
26203             positions[index + 0] = p.x;
26204             positions[index + 1] = p.y;
26205             positions[index + 2] = p.z;
26206         }
26207         var faces = node.mesh.faces;
26208         var indices = new Uint16Array(faces.length);
26209         for (var i = 0; i < faces.length; ++i) {
26210             indices[i] = faces[i];
26211         }
26212         var geometry = new THREE.BufferGeometry();
26213         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
26214         geometry.setIndex(new THREE.BufferAttribute(indices, 1));
26215         return geometry;
26216     };
26217     ImagePlaneFactory.prototype._getImagePlaneGeo = function (transform, node) {
26218         var t = new THREE.Matrix4().getInverse(transform.srt);
26219         // push everything at least 5 meters in front of the camera
26220         var minZ = 5.0 * transform.scale;
26221         var maxZ = this._imagePlaneDepth * transform.scale;
26222         var vertices = node.mesh.vertices;
26223         var numVertices = vertices.length / 3;
26224         var positions = new Float32Array(vertices.length);
26225         for (var i = 0; i < numVertices; ++i) {
26226             var index = 3 * i;
26227             var x = vertices[index + 0];
26228             var y = vertices[index + 1];
26229             var z = vertices[index + 2];
26230             var boundedZ = Math.max(minZ, Math.min(z, maxZ));
26231             var factor = boundedZ / z;
26232             var p = new THREE.Vector3(x * factor, y * factor, boundedZ);
26233             p.applyMatrix4(t);
26234             positions[index + 0] = p.x;
26235             positions[index + 1] = p.y;
26236             positions[index + 2] = p.z;
26237         }
26238         var faces = node.mesh.faces;
26239         var indices = new Uint16Array(faces.length);
26240         for (var i = 0; i < faces.length; ++i) {
26241             indices[i] = faces[i];
26242         }
26243         var geometry = new THREE.BufferGeometry();
26244         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
26245         geometry.setIndex(new THREE.BufferAttribute(indices, 1));
26246         return geometry;
26247     };
26248     ImagePlaneFactory.prototype._getFlatImageSphereGeo = function (transform) {
26249         var gpano = transform.gpano;
26250         var phiStart = 2 * Math.PI * gpano.CroppedAreaLeftPixels / gpano.FullPanoWidthPixels;
26251         var phiLength = 2 * Math.PI * gpano.CroppedAreaImageWidthPixels / gpano.FullPanoWidthPixels;
26252         var thetaStart = Math.PI *
26253             (gpano.FullPanoHeightPixels - gpano.CroppedAreaImageHeightPixels - gpano.CroppedAreaTopPixels) /
26254             gpano.FullPanoHeightPixels;
26255         var thetaLength = Math.PI * gpano.CroppedAreaImageHeightPixels / gpano.FullPanoHeightPixels;
26256         var geometry = new THREE.SphereGeometry(this._imageSphereRadius, 20, 40, phiStart - Math.PI / 2, phiLength, thetaStart, thetaLength);
26257         geometry.applyMatrix(new THREE.Matrix4().getInverse(transform.rt));
26258         return geometry;
26259     };
26260     ImagePlaneFactory.prototype._getFlatImagePlaneGeo = function (transform) {
26261         var width = transform.width;
26262         var height = transform.height;
26263         var size = Math.max(width, height);
26264         var dx = width / 2.0 / size;
26265         var dy = height / 2.0 / size;
26266         var vertices = [];
26267         vertices.push(transform.unprojectSfM([-dx, -dy], this._imagePlaneDepth));
26268         vertices.push(transform.unprojectSfM([dx, -dy], this._imagePlaneDepth));
26269         vertices.push(transform.unprojectSfM([dx, dy], this._imagePlaneDepth));
26270         vertices.push(transform.unprojectSfM([-dx, dy], this._imagePlaneDepth));
26271         var positions = new Float32Array(12);
26272         for (var i = 0; i < vertices.length; i++) {
26273             var index = 3 * i;
26274             positions[index + 0] = vertices[i][0];
26275             positions[index + 1] = vertices[i][1];
26276             positions[index + 2] = vertices[i][2];
26277         }
26278         var indices = new Uint16Array(6);
26279         indices[0] = 0;
26280         indices[1] = 1;
26281         indices[2] = 3;
26282         indices[3] = 1;
26283         indices[4] = 2;
26284         indices[5] = 3;
26285         var geometry = new THREE.BufferGeometry();
26286         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
26287         geometry.setIndex(new THREE.BufferAttribute(indices, 1));
26288         return geometry;
26289     };
26290     return ImagePlaneFactory;
26291 }());
26292 exports.ImagePlaneFactory = ImagePlaneFactory;
26293 exports.default = ImagePlaneFactory;
26294
26295 },{"../../Component":291,"three":241}],323:[function(require,module,exports){
26296 "use strict";
26297 /// <reference path="../../../typings/index.d.ts" />
26298 Object.defineProperty(exports, "__esModule", { value: true });
26299 var Component_1 = require("../../Component");
26300 var ImagePlaneGLRenderer = /** @class */ (function () {
26301     function ImagePlaneGLRenderer() {
26302         this._imagePlaneFactory = new Component_1.ImagePlaneFactory();
26303         this._imagePlaneScene = new Component_1.ImagePlaneScene();
26304         this._alpha = 0;
26305         this._alphaOld = 0;
26306         this._fadeOutSpeed = 0.05;
26307         this._currentKey = null;
26308         this._previousKey = null;
26309         this._providerDisposers = {};
26310         this._frameId = 0;
26311         this._needsRender = false;
26312     }
26313     Object.defineProperty(ImagePlaneGLRenderer.prototype, "frameId", {
26314         get: function () {
26315             return this._frameId;
26316         },
26317         enumerable: true,
26318         configurable: true
26319     });
26320     Object.defineProperty(ImagePlaneGLRenderer.prototype, "needsRender", {
26321         get: function () {
26322             return this._needsRender;
26323         },
26324         enumerable: true,
26325         configurable: true
26326     });
26327     ImagePlaneGLRenderer.prototype.indicateNeedsRender = function () {
26328         this._needsRender = true;
26329     };
26330     ImagePlaneGLRenderer.prototype.updateFrame = function (frame) {
26331         this._updateFrameId(frame.id);
26332         this._needsRender = this._updateAlpha(frame.state.alpha) || this._needsRender;
26333         this._needsRender = this._updateAlphaOld(frame.state.alpha) || this._needsRender;
26334         this._needsRender = this._updateImagePlanes(frame.state) || this._needsRender;
26335     };
26336     ImagePlaneGLRenderer.prototype.setTextureProvider = function (key, provider) {
26337         var _this = this;
26338         if (key !== this._currentKey) {
26339             return;
26340         }
26341         var createdSubscription = provider.textureCreated$
26342             .subscribe(function (texture) {
26343             _this._updateTexture(texture);
26344         });
26345         var updatedSubscription = provider.textureUpdated$
26346             .subscribe(function (updated) {
26347             _this._needsRender = true;
26348         });
26349         var dispose = function () {
26350             createdSubscription.unsubscribe();
26351             updatedSubscription.unsubscribe();
26352             provider.dispose();
26353         };
26354         if (key in this._providerDisposers) {
26355             var disposeProvider = this._providerDisposers[key];
26356             disposeProvider();
26357             delete this._providerDisposers[key];
26358         }
26359         this._providerDisposers[key] = dispose;
26360     };
26361     ImagePlaneGLRenderer.prototype._updateTexture = function (texture) {
26362         this._needsRender = true;
26363         for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
26364             var plane = _a[_i];
26365             var material = plane.material;
26366             var oldTexture = material.uniforms.projectorTex.value;
26367             material.uniforms.projectorTex.value = null;
26368             oldTexture.dispose();
26369             material.uniforms.projectorTex.value = texture;
26370         }
26371     };
26372     ImagePlaneGLRenderer.prototype.updateTextureImage = function (image, node) {
26373         if (this._currentKey !== node.key) {
26374             return;
26375         }
26376         this._needsRender = true;
26377         for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
26378             var plane = _a[_i];
26379             var material = plane.material;
26380             var texture = material.uniforms.projectorTex.value;
26381             texture.image = image;
26382             texture.needsUpdate = true;
26383         }
26384     };
26385     ImagePlaneGLRenderer.prototype.render = function (perspectiveCamera, renderer) {
26386         var planeAlpha = this._imagePlaneScene.imagePlanesOld.length ? 1 : this._alpha;
26387         for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
26388             var plane = _a[_i];
26389             plane.material.uniforms.opacity.value = planeAlpha;
26390         }
26391         for (var _b = 0, _c = this._imagePlaneScene.imagePlanesOld; _b < _c.length; _b++) {
26392             var plane = _c[_b];
26393             plane.material.uniforms.opacity.value = this._alphaOld;
26394         }
26395         renderer.render(this._imagePlaneScene.scene, perspectiveCamera);
26396         renderer.render(this._imagePlaneScene.sceneOld, perspectiveCamera);
26397         for (var _d = 0, _e = this._imagePlaneScene.imagePlanes; _d < _e.length; _d++) {
26398             var plane = _e[_d];
26399             plane.material.uniforms.opacity.value = this._alpha;
26400         }
26401         renderer.render(this._imagePlaneScene.scene, perspectiveCamera);
26402     };
26403     ImagePlaneGLRenderer.prototype.clearNeedsRender = function () {
26404         this._needsRender = false;
26405     };
26406     ImagePlaneGLRenderer.prototype.dispose = function () {
26407         this._imagePlaneScene.clear();
26408     };
26409     ImagePlaneGLRenderer.prototype._updateFrameId = function (frameId) {
26410         this._frameId = frameId;
26411     };
26412     ImagePlaneGLRenderer.prototype._updateAlpha = function (alpha) {
26413         if (alpha === this._alpha) {
26414             return false;
26415         }
26416         this._alpha = alpha;
26417         return true;
26418     };
26419     ImagePlaneGLRenderer.prototype._updateAlphaOld = function (alpha) {
26420         if (alpha < 1 || this._alphaOld === 0) {
26421             return false;
26422         }
26423         this._alphaOld = Math.max(0, this._alphaOld - this._fadeOutSpeed);
26424         return true;
26425     };
26426     ImagePlaneGLRenderer.prototype._updateImagePlanes = function (state) {
26427         if (state.currentNode == null || state.currentNode.key === this._currentKey) {
26428             return false;
26429         }
26430         var previousKey = state.previousNode != null ? state.previousNode.key : null;
26431         var currentKey = state.currentNode.key;
26432         if (this._previousKey !== previousKey &&
26433             this._previousKey !== currentKey &&
26434             this._previousKey in this._providerDisposers) {
26435             var disposeProvider = this._providerDisposers[this._previousKey];
26436             disposeProvider();
26437             delete this._providerDisposers[this._previousKey];
26438         }
26439         if (previousKey != null) {
26440             if (previousKey !== this._currentKey && previousKey !== this._previousKey) {
26441                 var previousMesh = this._imagePlaneFactory.createMesh(state.previousNode, state.previousTransform);
26442                 this._imagePlaneScene.updateImagePlanes([previousMesh]);
26443             }
26444             this._previousKey = previousKey;
26445         }
26446         this._currentKey = currentKey;
26447         var currentMesh = this._imagePlaneFactory.createMesh(state.currentNode, state.currentTransform);
26448         this._imagePlaneScene.updateImagePlanes([currentMesh]);
26449         this._alphaOld = 1;
26450         return true;
26451     };
26452     return ImagePlaneGLRenderer;
26453 }());
26454 exports.ImagePlaneGLRenderer = ImagePlaneGLRenderer;
26455 exports.default = ImagePlaneGLRenderer;
26456
26457 },{"../../Component":291}],324:[function(require,module,exports){
26458 "use strict";
26459 /// <reference path="../../../typings/index.d.ts" />
26460 Object.defineProperty(exports, "__esModule", { value: true });
26461 var THREE = require("three");
26462 var ImagePlaneScene = /** @class */ (function () {
26463     function ImagePlaneScene() {
26464         this.scene = new THREE.Scene();
26465         this.sceneOld = new THREE.Scene();
26466         this.imagePlanes = [];
26467         this.imagePlanesOld = [];
26468     }
26469     ImagePlaneScene.prototype.updateImagePlanes = function (planes) {
26470         this._dispose(this.imagePlanesOld, this.sceneOld);
26471         for (var _i = 0, _a = this.imagePlanes; _i < _a.length; _i++) {
26472             var plane = _a[_i];
26473             this.scene.remove(plane);
26474             this.sceneOld.add(plane);
26475         }
26476         for (var _b = 0, planes_1 = planes; _b < planes_1.length; _b++) {
26477             var plane = planes_1[_b];
26478             this.scene.add(plane);
26479         }
26480         this.imagePlanesOld = this.imagePlanes;
26481         this.imagePlanes = planes;
26482     };
26483     ImagePlaneScene.prototype.addImagePlanes = function (planes) {
26484         for (var _i = 0, planes_2 = planes; _i < planes_2.length; _i++) {
26485             var plane = planes_2[_i];
26486             this.scene.add(plane);
26487             this.imagePlanes.push(plane);
26488         }
26489     };
26490     ImagePlaneScene.prototype.addImagePlanesOld = function (planes) {
26491         for (var _i = 0, planes_3 = planes; _i < planes_3.length; _i++) {
26492             var plane = planes_3[_i];
26493             this.sceneOld.add(plane);
26494             this.imagePlanesOld.push(plane);
26495         }
26496     };
26497     ImagePlaneScene.prototype.setImagePlanes = function (planes) {
26498         this._clear();
26499         this.addImagePlanes(planes);
26500     };
26501     ImagePlaneScene.prototype.setImagePlanesOld = function (planes) {
26502         this._clearOld();
26503         this.addImagePlanesOld(planes);
26504     };
26505     ImagePlaneScene.prototype.clear = function () {
26506         this._clear();
26507         this._clearOld();
26508     };
26509     ImagePlaneScene.prototype._clear = function () {
26510         this._dispose(this.imagePlanes, this.scene);
26511         this.imagePlanes.length = 0;
26512     };
26513     ImagePlaneScene.prototype._clearOld = function () {
26514         this._dispose(this.imagePlanesOld, this.sceneOld);
26515         this.imagePlanesOld.length = 0;
26516     };
26517     ImagePlaneScene.prototype._dispose = function (planes, scene) {
26518         for (var _i = 0, planes_4 = planes; _i < planes_4.length; _i++) {
26519             var plane = planes_4[_i];
26520             scene.remove(plane);
26521             plane.geometry.dispose();
26522             plane.material.dispose();
26523             var texture = plane.material.uniforms.projectorTex.value;
26524             if (texture != null) {
26525                 texture.dispose();
26526             }
26527         }
26528     };
26529     return ImagePlaneScene;
26530 }());
26531 exports.ImagePlaneScene = ImagePlaneScene;
26532 exports.default = ImagePlaneScene;
26533
26534 },{"three":241}],325:[function(require,module,exports){
26535 "use strict";
26536 /// <reference path="../../../typings/index.d.ts" />
26537 Object.defineProperty(exports, "__esModule", { value: true });
26538
26539 var path = require("path");
26540 var ImagePlaneShaders = /** @class */ (function () {
26541     function ImagePlaneShaders() {
26542     }
26543     ImagePlaneShaders.equirectangular = {
26544         fragment: "#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n\nuniform sampler2D projectorTex;\nuniform float opacity;\nuniform float phiLength;\nuniform float phiShift;\nuniform float thetaLength;\nuniform float thetaShift;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n    vec3 b = normalize(vRstq.xyz);\n    float lat = -asin(b.y);\n    float lon = atan(b.x, b.z);\n    float x = (lon - phiShift) / phiLength + 0.5;\n    float y = (lat - thetaShift) / thetaLength + 0.5;\n    vec4 baseColor = texture2D(projectorTex, vec2(x, y));\n    baseColor.a = opacity;\n    gl_FragColor = baseColor;\n}",
26545         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}",
26546     };
26547     ImagePlaneShaders.perspective = {
26548         fragment: "#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n\nuniform sampler2D projectorTex;\nuniform float opacity;\nuniform vec4 bbox;\n\nvarying vec4 vRstq;\n\nvoid main()\n{\n    float x = vRstq.x / vRstq.w;\n    float y = vRstq.y / vRstq.w;\n\n    vec4 baseColor;\n    if (x > bbox[0] && y > bbox[1] && x < bbox[2] && y < bbox[3]) {\n        baseColor = texture2D(projectorTex, vec2(x, y));\n        baseColor.a = opacity;\n    } else {\n        baseColor = vec4(0.0, 0.0, 0.0, 0.0);\n    }\n\n    gl_FragColor = baseColor;\n}",
26549         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}",
26550     };
26551     return ImagePlaneShaders;
26552 }());
26553 exports.ImagePlaneShaders = ImagePlaneShaders;
26554
26555 },{"path":22}],326:[function(require,module,exports){
26556 "use strict";
26557 /// <reference path="../../../typings/index.d.ts" />
26558 var __extends = (this && this.__extends) || (function () {
26559     var extendStatics = Object.setPrototypeOf ||
26560         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
26561         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
26562     return function (d, b) {
26563         extendStatics(d, b);
26564         function __() { this.constructor = d; }
26565         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
26566     };
26567 })();
26568 Object.defineProperty(exports, "__esModule", { value: true });
26569 var Observable_1 = require("rxjs/Observable");
26570 var Subject_1 = require("rxjs/Subject");
26571 require("rxjs/add/observable/combineLatest");
26572 require("rxjs/add/observable/fromEvent");
26573 require("rxjs/add/observable/of");
26574 require("rxjs/add/observable/zip");
26575 require("rxjs/add/operator/distinctUntilChanged");
26576 require("rxjs/add/operator/filter");
26577 require("rxjs/add/operator/first");
26578 require("rxjs/add/operator/map");
26579 require("rxjs/add/operator/merge");
26580 require("rxjs/add/operator/mergeMap");
26581 require("rxjs/add/operator/scan");
26582 require("rxjs/add/operator/switchMap");
26583 require("rxjs/add/operator/withLatestFrom");
26584 require("rxjs/add/operator/zip");
26585 var State_1 = require("../../State");
26586 var Render_1 = require("../../Render");
26587 var Utils_1 = require("../../Utils");
26588 var Component_1 = require("../../Component");
26589 var SliderState = /** @class */ (function () {
26590     function SliderState() {
26591         this._imagePlaneFactory = new Component_1.ImagePlaneFactory();
26592         this._imagePlaneScene = new Component_1.ImagePlaneScene();
26593         this._currentKey = null;
26594         this._previousKey = null;
26595         this._currentPano = false;
26596         this._frameId = 0;
26597         this._glNeedsRender = false;
26598         this._domNeedsRender = true;
26599         this._curtain = 1;
26600     }
26601     Object.defineProperty(SliderState.prototype, "frameId", {
26602         get: function () {
26603             return this._frameId;
26604         },
26605         enumerable: true,
26606         configurable: true
26607     });
26608     Object.defineProperty(SliderState.prototype, "curtain", {
26609         get: function () {
26610             return this._curtain;
26611         },
26612         enumerable: true,
26613         configurable: true
26614     });
26615     Object.defineProperty(SliderState.prototype, "glNeedsRender", {
26616         get: function () {
26617             return this._glNeedsRender;
26618         },
26619         enumerable: true,
26620         configurable: true
26621     });
26622     Object.defineProperty(SliderState.prototype, "domNeedsRender", {
26623         get: function () {
26624             return this._domNeedsRender;
26625         },
26626         enumerable: true,
26627         configurable: true
26628     });
26629     Object.defineProperty(SliderState.prototype, "sliderVisible", {
26630         get: function () {
26631             return this._sliderVisible;
26632         },
26633         set: function (value) {
26634             this._sliderVisible = value;
26635             this._domNeedsRender = true;
26636         },
26637         enumerable: true,
26638         configurable: true
26639     });
26640     Object.defineProperty(SliderState.prototype, "disabled", {
26641         get: function () {
26642             return this._currentKey == null ||
26643                 this._previousKey == null ||
26644                 this._currentPano;
26645         },
26646         enumerable: true,
26647         configurable: true
26648     });
26649     SliderState.prototype.update = function (frame) {
26650         this._updateFrameId(frame.id);
26651         var needsRender = this._updateImagePlanes(frame.state);
26652         this._domNeedsRender = needsRender || this._domNeedsRender;
26653         needsRender = this._updateCurtain(frame.state.alpha) || needsRender;
26654         this._glNeedsRender = needsRender || this._glNeedsRender;
26655     };
26656     SliderState.prototype.updateTexture = function (image, node) {
26657         var imagePlanes = node.key === this._currentKey ?
26658             this._imagePlaneScene.imagePlanes :
26659             node.key === this._previousKey ?
26660                 this._imagePlaneScene.imagePlanesOld :
26661                 [];
26662         if (imagePlanes.length === 0) {
26663             return;
26664         }
26665         this._glNeedsRender = true;
26666         for (var _i = 0, imagePlanes_1 = imagePlanes; _i < imagePlanes_1.length; _i++) {
26667             var plane = imagePlanes_1[_i];
26668             var material = plane.material;
26669             var texture = material.uniforms.projectorTex.value;
26670             texture.image = image;
26671             texture.needsUpdate = true;
26672         }
26673     };
26674     SliderState.prototype.render = function (perspectiveCamera, renderer) {
26675         if (!this.disabled) {
26676             renderer.render(this._imagePlaneScene.sceneOld, perspectiveCamera);
26677         }
26678         renderer.render(this._imagePlaneScene.scene, perspectiveCamera);
26679     };
26680     SliderState.prototype.dispose = function () {
26681         this._imagePlaneScene.clear();
26682     };
26683     SliderState.prototype.clearGLNeedsRender = function () {
26684         this._glNeedsRender = false;
26685     };
26686     SliderState.prototype.clearDomNeedsRender = function () {
26687         this._domNeedsRender = false;
26688     };
26689     SliderState.prototype._updateFrameId = function (frameId) {
26690         this._frameId = frameId;
26691     };
26692     SliderState.prototype._updateImagePlanes = function (state) {
26693         if (state.currentNode == null) {
26694             return;
26695         }
26696         var needsRender = false;
26697         if (state.previousNode != null && this._previousKey !== state.previousNode.key) {
26698             needsRender = true;
26699             this._previousKey = state.previousNode.key;
26700             this._imagePlaneScene.setImagePlanesOld([
26701                 this._imagePlaneFactory.createMesh(state.previousNode, state.previousTransform),
26702             ]);
26703         }
26704         if (this._currentKey !== state.currentNode.key) {
26705             needsRender = true;
26706             this._currentKey = state.currentNode.key;
26707             this._currentPano = state.currentNode.pano;
26708             this._imagePlaneScene.setImagePlanes([
26709                 this._imagePlaneFactory.createMesh(state.currentNode, state.currentTransform),
26710             ]);
26711             if (!this.disabled) {
26712                 this._updateBbox();
26713             }
26714         }
26715         return needsRender;
26716     };
26717     SliderState.prototype._updateCurtain = function (alpha) {
26718         if (this.disabled ||
26719             Math.abs(this._curtain - alpha) < 0.001) {
26720             return false;
26721         }
26722         this._curtain = alpha;
26723         this._updateBbox();
26724         return true;
26725     };
26726     SliderState.prototype._updateBbox = function () {
26727         for (var _i = 0, _a = this._imagePlaneScene.imagePlanes; _i < _a.length; _i++) {
26728             var plane = _a[_i];
26729             var shaderMaterial = plane.material;
26730             var bbox = shaderMaterial.uniforms.bbox.value;
26731             bbox.z = this._curtain;
26732         }
26733     };
26734     return SliderState;
26735 }());
26736 var SliderComponent = /** @class */ (function (_super) {
26737     __extends(SliderComponent, _super);
26738     /**
26739      * Create a new slider component instance.
26740      * @class SliderComponent
26741      */
26742     function SliderComponent(name, container, navigator, dom) {
26743         var _this = _super.call(this, name, container, navigator) || this;
26744         _this._dom = !!dom ? dom : new Utils_1.DOM();
26745         _this._sliderStateOperation$ = new Subject_1.Subject();
26746         _this._sliderStateCreator$ = new Subject_1.Subject();
26747         _this._sliderStateDisposer$ = new Subject_1.Subject();
26748         _this._sliderState$ = _this._sliderStateOperation$
26749             .scan(function (sliderState, operation) {
26750             return operation(sliderState);
26751         }, null)
26752             .filter(function (sliderState) {
26753             return sliderState != null;
26754         })
26755             .distinctUntilChanged(undefined, function (sliderState) {
26756             return sliderState.frameId;
26757         });
26758         _this._sliderStateCreator$
26759             .map(function () {
26760             return function (sliderState) {
26761                 if (sliderState != null) {
26762                     throw new Error("Multiple slider states can not be created at the same time");
26763                 }
26764                 return new SliderState();
26765             };
26766         })
26767             .subscribe(_this._sliderStateOperation$);
26768         _this._sliderStateDisposer$
26769             .map(function () {
26770             return function (sliderState) {
26771                 sliderState.dispose();
26772                 return null;
26773             };
26774         })
26775             .subscribe(_this._sliderStateOperation$);
26776         return _this;
26777     }
26778     /**
26779      * Set the image keys.
26780      *
26781      * Configures the component to show the image planes for the supplied image keys.
26782      *
26783      * @param {keys} ISliderKeys - Slider keys object specifying the images to be shown in the foreground and the background.
26784      */
26785     SliderComponent.prototype.setKeys = function (keys) {
26786         this.configure({ keys: keys });
26787     };
26788     /**
26789      * Set the initial position.
26790      *
26791      * Configures the intial position of the slider. The inital position value will be used when the component is activated.
26792      *
26793      * @param {number} initialPosition - Initial slider position.
26794      */
26795     SliderComponent.prototype.setInitialPosition = function (initialPosition) {
26796         this.configure({ initialPosition: initialPosition });
26797     };
26798     /**
26799      * Set the value controlling if the slider is visible.
26800      *
26801      * @param {boolean} sliderVisible - Value indicating if the slider should be visible or not.
26802      */
26803     SliderComponent.prototype.setSliderVisible = function (sliderVisible) {
26804         this.configure({ sliderVisible: sliderVisible });
26805     };
26806     SliderComponent.prototype._activate = function () {
26807         var _this = this;
26808         this._sliderContainer = this._dom.createElement("div", "mapillary-js-slider-container", this._container.element);
26809         this._sliderWrapper = this._dom.createElement("div", "SliderWrapper", this._sliderContainer);
26810         this._sliderControl = this._dom.createElement("input", "SliderControl", this._sliderWrapper);
26811         this._sliderControl.setAttribute("type", "range");
26812         this._sliderControl.setAttribute("min", "0");
26813         this._sliderControl.setAttribute("max", "1000");
26814         this._sliderControl.style.visibility = "hidden";
26815         this._moveToHandler = function (e) {
26816             var curtain = Number(e.target.value) / 1000;
26817             _this._navigator.stateService.moveTo(curtain);
26818         };
26819         this._sliderControl.addEventListener("input", this._moveToHandler);
26820         this._sliderControl.addEventListener("change", this._moveToHandler);
26821         Observable_1.Observable
26822             .combineLatest(this._navigator.stateService.state$, this._configuration$)
26823             .first()
26824             .subscribe(function (_a) {
26825             var state = _a[0], configuration = _a[1];
26826             if (state === State_1.State.Traversing) {
26827                 _this._navigator.stateService.wait();
26828                 var position = configuration.initialPosition != null ? configuration.initialPosition : 1;
26829                 _this._sliderControl.value = (1000 * position).toString();
26830                 _this._navigator.stateService.moveTo(position);
26831             }
26832         });
26833         this._glRenderSubscription = this._sliderState$
26834             .map(function (sliderState) {
26835             var renderHash = {
26836                 name: _this._name,
26837                 render: {
26838                     frameId: sliderState.frameId,
26839                     needsRender: sliderState.glNeedsRender,
26840                     render: sliderState.render.bind(sliderState),
26841                     stage: Render_1.GLRenderStage.Background,
26842                 },
26843             };
26844             sliderState.clearGLNeedsRender();
26845             return renderHash;
26846         })
26847             .subscribe(this._container.glRenderer.render$);
26848         this._domRenderSubscription = this._sliderState$
26849             .filter(function (sliderState) {
26850             return sliderState.domNeedsRender;
26851         })
26852             .subscribe(function (sliderState) {
26853             _this._sliderControl.value = (1000 * sliderState.curtain).toString();
26854             var visibility = sliderState.disabled || !sliderState.sliderVisible ? "hidden" : "visible";
26855             _this._sliderControl.style.visibility = visibility;
26856             sliderState.clearDomNeedsRender();
26857         });
26858         this._sliderStateCreator$.next(null);
26859         this._stateSubscription = this._navigator.stateService.currentState$
26860             .map(function (frame) {
26861             return function (sliderState) {
26862                 sliderState.update(frame);
26863                 return sliderState;
26864             };
26865         })
26866             .subscribe(this._sliderStateOperation$);
26867         this._setSliderVisibleSubscription = this._configuration$
26868             .map(function (configuration) {
26869             return configuration.sliderVisible == null || configuration.sliderVisible;
26870         })
26871             .distinctUntilChanged()
26872             .map(function (sliderVisible) {
26873             return function (sliderState) {
26874                 sliderState.sliderVisible = sliderVisible;
26875                 return sliderState;
26876             };
26877         })
26878             .subscribe(this._sliderStateOperation$);
26879         this._setKeysSubscription = this._configuration$
26880             .filter(function (configuration) {
26881             return configuration.keys != null;
26882         })
26883             .switchMap(function (configuration) {
26884             return Observable_1.Observable
26885                 .zip(_this._catchCacheNode$(configuration.keys.background), _this._catchCacheNode$(configuration.keys.foreground))
26886                 .map(function (nodes) {
26887                 return { background: nodes[0], foreground: nodes[1] };
26888             })
26889                 .zip(_this._navigator.stateService.currentState$.first())
26890                 .map(function (nf) {
26891                 return { nodes: nf[0], state: nf[1].state };
26892             });
26893         })
26894             .subscribe(function (co) {
26895             if (co.state.currentNode != null &&
26896                 co.state.previousNode != null &&
26897                 co.state.currentNode.key === co.nodes.foreground.key &&
26898                 co.state.previousNode.key === co.nodes.background.key) {
26899                 return;
26900             }
26901             if (co.state.currentNode.key === co.nodes.background.key) {
26902                 _this._navigator.stateService.setNodes([co.nodes.foreground]);
26903                 return;
26904             }
26905             if (co.state.currentNode.key === co.nodes.foreground.key &&
26906                 co.state.trajectory.length === 1) {
26907                 _this._navigator.stateService.prependNodes([co.nodes.background]);
26908                 return;
26909             }
26910             _this._navigator.stateService.setNodes([co.nodes.background]);
26911             _this._navigator.stateService.setNodes([co.nodes.foreground]);
26912         }, function (e) {
26913             console.error(e);
26914         });
26915         var previousNode$ = this._navigator.stateService.currentState$
26916             .map(function (frame) {
26917             return frame.state.previousNode;
26918         })
26919             .filter(function (node) {
26920             return node != null;
26921         })
26922             .distinctUntilChanged(undefined, function (node) {
26923             return node.key;
26924         });
26925         this._nodeSubscription = Observable_1.Observable
26926             .merge(previousNode$, this._navigator.stateService.currentNode$)
26927             .filter(function (node) {
26928             return node.pano ?
26929                 Utils_1.Settings.maxImageSize > Utils_1.Settings.basePanoramaSize :
26930                 Utils_1.Settings.maxImageSize > Utils_1.Settings.baseImageSize;
26931         })
26932             .mergeMap(function (node) {
26933             var baseImageSize = node.pano ?
26934                 Utils_1.Settings.basePanoramaSize :
26935                 Utils_1.Settings.baseImageSize;
26936             if (Math.max(node.image.width, node.image.height) > baseImageSize) {
26937                 return Observable_1.Observable.empty();
26938             }
26939             return node.cacheImage$(Utils_1.Settings.maxImageSize)
26940                 .map(function (n) {
26941                 return [n.image, n];
26942             })
26943                 .catch(function (error, caught) {
26944                 console.error("Failed to fetch high res slider image (" + node.key + ")", error);
26945                 return Observable_1.Observable.empty();
26946             });
26947         })
26948             .map(function (_a) {
26949             var element = _a[0], node = _a[1];
26950             return function (sliderState) {
26951                 sliderState.updateTexture(element, node);
26952                 return sliderState;
26953             };
26954         })
26955             .subscribe(this._sliderStateOperation$);
26956     };
26957     SliderComponent.prototype._deactivate = function () {
26958         var _this = this;
26959         this._navigator.stateService.state$
26960             .first()
26961             .subscribe(function (state) {
26962             if (state === State_1.State.Waiting) {
26963                 _this._navigator.stateService.traverse();
26964             }
26965         });
26966         this._sliderStateDisposer$.next(null);
26967         this._setKeysSubscription.unsubscribe();
26968         this._setSliderVisibleSubscription.unsubscribe();
26969         this._stateSubscription.unsubscribe();
26970         this._glRenderSubscription.unsubscribe();
26971         this._domRenderSubscription.unsubscribe();
26972         this._nodeSubscription.unsubscribe();
26973         this.configure({ keys: null });
26974         this._sliderControl.removeEventListener("input", this._moveToHandler);
26975         this._sliderControl.removeEventListener("change", this._moveToHandler);
26976         this._container.element.removeChild(this._sliderContainer);
26977         this._moveToHandler = null;
26978         this._sliderControl = null;
26979         this._sliderWrapper = null;
26980         this._sliderContainer = null;
26981     };
26982     SliderComponent.prototype._getDefaultConfiguration = function () {
26983         return {};
26984     };
26985     SliderComponent.prototype._catchCacheNode$ = function (key) {
26986         return this._navigator.graphService.cacheNode$(key)
26987             .catch(function (error, caught) {
26988             console.error("Failed to cache slider node (" + key + ")", error);
26989             return Observable_1.Observable.empty();
26990         });
26991     };
26992     SliderComponent.componentName = "slider";
26993     return SliderComponent;
26994 }(Component_1.Component));
26995 exports.SliderComponent = SliderComponent;
26996 Component_1.ComponentService.register(SliderComponent);
26997 exports.default = SliderComponent;
26998
26999 },{"../../Component":291,"../../Render":297,"../../State":298,"../../Utils":301,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/combineLatest":38,"rxjs/add/observable/fromEvent":43,"rxjs/add/observable/of":46,"rxjs/add/observable/zip":49,"rxjs/add/operator/distinctUntilChanged":60,"rxjs/add/operator/filter":63,"rxjs/add/operator/first":65,"rxjs/add/operator/map":67,"rxjs/add/operator/merge":68,"rxjs/add/operator/mergeMap":70,"rxjs/add/operator/scan":78,"rxjs/add/operator/switchMap":84,"rxjs/add/operator/withLatestFrom":90,"rxjs/add/operator/zip":91}],327:[function(require,module,exports){
27000 "use strict";
27001 Object.defineProperty(exports, "__esModule", { value: true });
27002 var CoverState;
27003 (function (CoverState) {
27004     CoverState[CoverState["Hidden"] = 0] = "Hidden";
27005     CoverState[CoverState["Loading"] = 1] = "Loading";
27006     CoverState[CoverState["Visible"] = 2] = "Visible";
27007 })(CoverState = exports.CoverState || (exports.CoverState = {}));
27008
27009 },{}],328:[function(require,module,exports){
27010 "use strict";
27011 Object.defineProperty(exports, "__esModule", { value: true });
27012 var ICoverConfiguration_1 = require("./ICoverConfiguration");
27013 exports.CoverState = ICoverConfiguration_1.CoverState;
27014
27015 },{"./ICoverConfiguration":327}],329:[function(require,module,exports){
27016 "use strict";
27017 /// <reference path="../../../typings/index.d.ts" />
27018 var __extends = (this && this.__extends) || (function () {
27019     var extendStatics = Object.setPrototypeOf ||
27020         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
27021         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
27022     return function (d, b) {
27023         extendStatics(d, b);
27024         function __() { this.constructor = d; }
27025         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
27026     };
27027 })();
27028 Object.defineProperty(exports, "__esModule", { value: true });
27029 var Component_1 = require("../../Component");
27030 var Edge_1 = require("../../Edge");
27031 /**
27032  * The `KeyPlayHandler` allows the user to control the play behavior
27033  * using the following key commands:
27034  *
27035  * `Spacebar`: Start or stop playing.
27036  * `SHIFT` + `D`: Switch direction.
27037  * `<`: Decrease speed.
27038  * `>`: Increase speed.
27039  *
27040  * @example
27041  * ```
27042  * var keyboardComponent = viewer.getComponent("keyboard");
27043  *
27044  * keyboardComponent.keyPlay.disable();
27045  * keyboardComponent.keyPlay.enable();
27046  *
27047  * var isEnabled = keyboardComponent.keyPlay.isEnabled;
27048  * ```
27049  */
27050 var KeyPlayHandler = /** @class */ (function (_super) {
27051     __extends(KeyPlayHandler, _super);
27052     function KeyPlayHandler() {
27053         return _super !== null && _super.apply(this, arguments) || this;
27054     }
27055     KeyPlayHandler.prototype._enable = function () {
27056         var _this = this;
27057         this._keyDownSubscription = this._container.keyboardService.keyDown$
27058             .withLatestFrom(this._navigator.playService.playing$, this._navigator.playService.direction$, this._navigator.playService.speed$, this._navigator.stateService.currentNode$
27059             .switchMap(function (node) {
27060             return node.sequenceEdges$;
27061         }))
27062             .subscribe(function (_a) {
27063             var event = _a[0], playing = _a[1], direction = _a[2], speed = _a[3], status = _a[4];
27064             if (event.altKey || event.ctrlKey || event.metaKey) {
27065                 return;
27066             }
27067             switch (event.key) {
27068                 case "D":
27069                     if (!event.shiftKey) {
27070                         return;
27071                     }
27072                     var newDirection = playing ?
27073                         null : direction === Edge_1.EdgeDirection.Next ?
27074                         Edge_1.EdgeDirection.Prev : direction === Edge_1.EdgeDirection.Prev ?
27075                         Edge_1.EdgeDirection.Next : null;
27076                     if (newDirection != null) {
27077                         _this._navigator.playService.setDirection(newDirection);
27078                     }
27079                     break;
27080                 case " ":
27081                     if (event.shiftKey) {
27082                         return;
27083                     }
27084                     if (playing) {
27085                         _this._navigator.playService.stop();
27086                     }
27087                     else {
27088                         for (var _i = 0, _b = status.edges; _i < _b.length; _i++) {
27089                             var edge = _b[_i];
27090                             if (edge.data.direction === direction) {
27091                                 _this._navigator.playService.play();
27092                             }
27093                         }
27094                     }
27095                     break;
27096                 case "<":
27097                     _this._navigator.playService.setSpeed(speed - 0.05);
27098                     break;
27099                 case ">":
27100                     _this._navigator.playService.setSpeed(speed + 0.05);
27101                     break;
27102                 default:
27103                     return;
27104             }
27105             event.preventDefault();
27106         });
27107     };
27108     KeyPlayHandler.prototype._disable = function () {
27109         this._keyDownSubscription.unsubscribe();
27110     };
27111     KeyPlayHandler.prototype._getConfiguration = function (enable) {
27112         return { keyZoom: enable };
27113     };
27114     return KeyPlayHandler;
27115 }(Component_1.HandlerBase));
27116 exports.KeyPlayHandler = KeyPlayHandler;
27117 exports.default = KeyPlayHandler;
27118
27119 },{"../../Component":291,"../../Edge":292}],330:[function(require,module,exports){
27120 "use strict";
27121 /// <reference path="../../../typings/index.d.ts" />
27122 var __extends = (this && this.__extends) || (function () {
27123     var extendStatics = Object.setPrototypeOf ||
27124         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
27125         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
27126     return function (d, b) {
27127         extendStatics(d, b);
27128         function __() { this.constructor = d; }
27129         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
27130     };
27131 })();
27132 Object.defineProperty(exports, "__esModule", { value: true });
27133 require("rxjs/add/operator/switchMap");
27134 require("rxjs/add/operator/withLatestFrom");
27135 var Component_1 = require("../../Component");
27136 var Edge_1 = require("../../Edge");
27137 var Error_1 = require("../../Error");
27138 /**
27139  * The `KeySequenceNavigationHandler` allows the user to navigate through a sequence using the
27140  * following key commands:
27141  *
27142  * `ALT` + `Up Arrow`: Navigate to next image in the sequence.
27143  * `ALT` + `Down Arrow`: Navigate to previous image in sequence.
27144  *
27145  * @example
27146  * ```
27147  * var keyboardComponent = viewer.getComponent("keyboard");
27148  *
27149  * keyboardComponent.keySequenceNavigation.disable();
27150  * keyboardComponent.keySequenceNavigation.enable();
27151  *
27152  * var isEnabled = keyboardComponent.keySequenceNavigation.isEnabled;
27153  * ```
27154  */
27155 var KeySequenceNavigationHandler = /** @class */ (function (_super) {
27156     __extends(KeySequenceNavigationHandler, _super);
27157     function KeySequenceNavigationHandler() {
27158         return _super !== null && _super.apply(this, arguments) || this;
27159     }
27160     KeySequenceNavigationHandler.prototype._enable = function () {
27161         var _this = this;
27162         var sequenceEdges$ = this._navigator.stateService.currentNode$
27163             .switchMap(function (node) {
27164             return node.sequenceEdges$;
27165         });
27166         this._keyDownSubscription = this._container.keyboardService.keyDown$
27167             .withLatestFrom(sequenceEdges$)
27168             .subscribe(function (_a) {
27169             var event = _a[0], edgeStatus = _a[1];
27170             var direction = null;
27171             switch (event.keyCode) {
27172                 case 38:// up
27173                     direction = Edge_1.EdgeDirection.Next;
27174                     break;
27175                 case 40:// down
27176                     direction = Edge_1.EdgeDirection.Prev;
27177                     break;
27178                 default:
27179                     return;
27180             }
27181             event.preventDefault();
27182             if (!event.altKey || event.shiftKey || !edgeStatus.cached) {
27183                 return;
27184             }
27185             for (var _i = 0, _b = edgeStatus.edges; _i < _b.length; _i++) {
27186                 var edge = _b[_i];
27187                 if (edge.data.direction === direction) {
27188                     _this._navigator.moveToKey$(edge.to)
27189                         .subscribe(undefined, function (error) {
27190                         if (!(error instanceof Error_1.AbortMapillaryError)) {
27191                             console.error(error);
27192                         }
27193                     });
27194                     return;
27195                 }
27196             }
27197         });
27198     };
27199     KeySequenceNavigationHandler.prototype._disable = function () {
27200         this._keyDownSubscription.unsubscribe();
27201     };
27202     KeySequenceNavigationHandler.prototype._getConfiguration = function (enable) {
27203         return { keySequenceNavigation: enable };
27204     };
27205     return KeySequenceNavigationHandler;
27206 }(Component_1.HandlerBase));
27207 exports.KeySequenceNavigationHandler = KeySequenceNavigationHandler;
27208 exports.default = KeySequenceNavigationHandler;
27209
27210 },{"../../Component":291,"../../Edge":292,"../../Error":293,"rxjs/add/operator/switchMap":84,"rxjs/add/operator/withLatestFrom":90}],331:[function(require,module,exports){
27211 "use strict";
27212 /// <reference path="../../../typings/index.d.ts" />
27213 var __extends = (this && this.__extends) || (function () {
27214     var extendStatics = Object.setPrototypeOf ||
27215         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
27216         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
27217     return function (d, b) {
27218         extendStatics(d, b);
27219         function __() { this.constructor = d; }
27220         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
27221     };
27222 })();
27223 Object.defineProperty(exports, "__esModule", { value: true });
27224 require("rxjs/add/operator/switchMap");
27225 require("rxjs/add/operator/withLatestFrom");
27226 var Component_1 = require("../../Component");
27227 var Edge_1 = require("../../Edge");
27228 var Error_1 = require("../../Error");
27229 /**
27230  * The `KeySpatialNavigationHandler` allows the user to navigate through a sequence using the
27231  * following key commands:
27232  *
27233  * `Up Arrow`: Step forward.
27234  * `Down Arrow`: Step backward.
27235  * `Left Arrow`: Step to the left.
27236  * `Rigth Arrow`: Step to the right.
27237  * `SHIFT` + `Down Arrow`: Turn around.
27238  * `SHIFT` + `Left Arrow`: Turn to the left.
27239  * `SHIFT` + `Rigth Arrow`: Turn to the right.
27240  *
27241  * @example
27242  * ```
27243  * var keyboardComponent = viewer.getComponent("keyboard");
27244  *
27245  * keyboardComponent.keySpatialNavigation.disable();
27246  * keyboardComponent.keySpatialNavigation.enable();
27247  *
27248  * var isEnabled = keyboardComponent.keySpatialNavigation.isEnabled;
27249  * ```
27250  */
27251 var KeySpatialNavigationHandler = /** @class */ (function (_super) {
27252     __extends(KeySpatialNavigationHandler, _super);
27253     function KeySpatialNavigationHandler(component, container, navigator, spatial) {
27254         var _this = _super.call(this, component, container, navigator) || this;
27255         _this._spatial = spatial;
27256         return _this;
27257     }
27258     KeySpatialNavigationHandler.prototype._enable = function () {
27259         var _this = this;
27260         var spatialEdges$ = this._navigator.stateService.currentNode$
27261             .switchMap(function (node) {
27262             return node.spatialEdges$;
27263         });
27264         this._keyDownSubscription = this._container.keyboardService.keyDown$
27265             .withLatestFrom(spatialEdges$, this._navigator.stateService.currentState$)
27266             .subscribe(function (_a) {
27267             var event = _a[0], edgeStatus = _a[1], frame = _a[2];
27268             var pano = frame.state.currentNode.pano;
27269             var direction = null;
27270             switch (event.keyCode) {
27271                 case 37:// left
27272                     direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.TurnLeft : Edge_1.EdgeDirection.StepLeft;
27273                     break;
27274                 case 38:// up
27275                     direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.Pano : Edge_1.EdgeDirection.StepForward;
27276                     break;
27277                 case 39:// right
27278                     direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.TurnRight : Edge_1.EdgeDirection.StepRight;
27279                     break;
27280                 case 40:// down
27281                     direction = event.shiftKey && !pano ? Edge_1.EdgeDirection.TurnU : Edge_1.EdgeDirection.StepBackward;
27282                     break;
27283                 default:
27284                     return;
27285             }
27286             event.preventDefault();
27287             if (event.altKey || !edgeStatus.cached ||
27288                 (event.shiftKey && pano)) {
27289                 return;
27290             }
27291             if (!pano) {
27292                 _this._moveDir(direction, edgeStatus);
27293             }
27294             else {
27295                 var shifts = {};
27296                 shifts[Edge_1.EdgeDirection.StepBackward] = Math.PI;
27297                 shifts[Edge_1.EdgeDirection.StepForward] = 0;
27298                 shifts[Edge_1.EdgeDirection.StepLeft] = Math.PI / 2;
27299                 shifts[Edge_1.EdgeDirection.StepRight] = -Math.PI / 2;
27300                 var phi = _this._rotationFromCamera(frame.state.camera).phi;
27301                 var navigationAngle = _this._spatial.wrapAngle(phi + shifts[direction]);
27302                 var threshold = Math.PI / 4;
27303                 var edges = edgeStatus.edges.filter(function (e) {
27304                     return e.data.direction === Edge_1.EdgeDirection.Pano || e.data.direction === direction;
27305                 });
27306                 var smallestAngle = Number.MAX_VALUE;
27307                 var toKey = null;
27308                 for (var _i = 0, edges_1 = edges; _i < edges_1.length; _i++) {
27309                     var edge = edges_1[_i];
27310                     var angle = Math.abs(_this._spatial.wrapAngle(edge.data.worldMotionAzimuth - navigationAngle));
27311                     if (angle < Math.min(smallestAngle, threshold)) {
27312                         smallestAngle = angle;
27313                         toKey = edge.to;
27314                     }
27315                 }
27316                 if (toKey == null) {
27317                     return;
27318                 }
27319                 _this._moveToKey(toKey);
27320             }
27321         });
27322     };
27323     KeySpatialNavigationHandler.prototype._disable = function () {
27324         this._keyDownSubscription.unsubscribe();
27325     };
27326     KeySpatialNavigationHandler.prototype._getConfiguration = function (enable) {
27327         return { keySpatialNavigation: enable };
27328     };
27329     KeySpatialNavigationHandler.prototype._moveDir = function (direction, edgeStatus) {
27330         for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
27331             var edge = _a[_i];
27332             if (edge.data.direction === direction) {
27333                 this._moveToKey(edge.to);
27334                 return;
27335             }
27336         }
27337     };
27338     KeySpatialNavigationHandler.prototype._moveToKey = function (key) {
27339         this._navigator.moveToKey$(key)
27340             .subscribe(undefined, function (error) {
27341             if (!(error instanceof Error_1.AbortMapillaryError)) {
27342                 console.error(error);
27343             }
27344         });
27345     };
27346     KeySpatialNavigationHandler.prototype._rotationFromCamera = function (camera) {
27347         var direction = camera.lookat.clone().sub(camera.position);
27348         var upProjection = direction.clone().dot(camera.up);
27349         var planeProjection = direction.clone().sub(camera.up.clone().multiplyScalar(upProjection));
27350         var phi = Math.atan2(planeProjection.y, planeProjection.x);
27351         var theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
27352         return { phi: phi, theta: theta };
27353     };
27354     return KeySpatialNavigationHandler;
27355 }(Component_1.HandlerBase));
27356 exports.KeySpatialNavigationHandler = KeySpatialNavigationHandler;
27357 exports.default = KeySpatialNavigationHandler;
27358
27359 },{"../../Component":291,"../../Edge":292,"../../Error":293,"rxjs/add/operator/switchMap":84,"rxjs/add/operator/withLatestFrom":90}],332:[function(require,module,exports){
27360 "use strict";
27361 /// <reference path="../../../typings/index.d.ts" />
27362 var __extends = (this && this.__extends) || (function () {
27363     var extendStatics = Object.setPrototypeOf ||
27364         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
27365         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
27366     return function (d, b) {
27367         extendStatics(d, b);
27368         function __() { this.constructor = d; }
27369         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
27370     };
27371 })();
27372 Object.defineProperty(exports, "__esModule", { value: true });
27373 require("rxjs/add/operator/withLatestFrom");
27374 var Component_1 = require("../../Component");
27375 /**
27376  * The `KeyZoomHandler` allows the user to zoom in and out using the
27377  * following key commands:
27378  *
27379  * `+`: Zoom in.
27380  * `-`: Zoom out.
27381  *
27382  * @example
27383  * ```
27384  * var keyboardComponent = viewer.getComponent("keyboard");
27385  *
27386  * keyboardComponent.keyZoom.disable();
27387  * keyboardComponent.keyZoom.enable();
27388  *
27389  * var isEnabled = keyboardComponent.keyZoom.isEnabled;
27390  * ```
27391  */
27392 var KeyZoomHandler = /** @class */ (function (_super) {
27393     __extends(KeyZoomHandler, _super);
27394     function KeyZoomHandler(component, container, navigator, viewportCoords) {
27395         var _this = _super.call(this, component, container, navigator) || this;
27396         _this._viewportCoords = viewportCoords;
27397         return _this;
27398     }
27399     KeyZoomHandler.prototype._enable = function () {
27400         var _this = this;
27401         this._keyDownSubscription = this._container.keyboardService.keyDown$
27402             .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
27403             .subscribe(function (_a) {
27404             var event = _a[0], render = _a[1], transform = _a[2];
27405             if (event.altKey || event.shiftKey || event.ctrlKey || event.metaKey) {
27406                 return;
27407             }
27408             var delta = 0;
27409             switch (event.key) {
27410                 case "+":
27411                     delta = 1;
27412                     break;
27413                 case "-":
27414                     delta = -1;
27415                     break;
27416                 default:
27417                     return;
27418             }
27419             event.preventDefault();
27420             var unprojected = _this._viewportCoords.unprojectFromViewport(0, 0, render.perspective);
27421             var reference = transform.projectBasic(unprojected.toArray());
27422             _this._navigator.stateService.zoomIn(delta, reference);
27423         });
27424     };
27425     KeyZoomHandler.prototype._disable = function () {
27426         this._keyDownSubscription.unsubscribe();
27427     };
27428     KeyZoomHandler.prototype._getConfiguration = function (enable) {
27429         return { keyZoom: enable };
27430     };
27431     return KeyZoomHandler;
27432 }(Component_1.HandlerBase));
27433 exports.KeyZoomHandler = KeyZoomHandler;
27434 exports.default = KeyZoomHandler;
27435
27436 },{"../../Component":291,"rxjs/add/operator/withLatestFrom":90}],333:[function(require,module,exports){
27437 "use strict";
27438 var __extends = (this && this.__extends) || (function () {
27439     var extendStatics = Object.setPrototypeOf ||
27440         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
27441         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
27442     return function (d, b) {
27443         extendStatics(d, b);
27444         function __() { this.constructor = d; }
27445         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
27446     };
27447 })();
27448 Object.defineProperty(exports, "__esModule", { value: true });
27449 var Component_1 = require("../../Component");
27450 var Geo_1 = require("../../Geo");
27451 /**
27452  * @class KeyboardComponent
27453  *
27454  * @classdesc Component for keyboard event handling.
27455  *
27456  * To retrive and use the keyboard component
27457  *
27458  * @example
27459  * ```
27460  * var viewer = new Mapillary.Viewer(
27461  *     "<element-id>",
27462  *     "<client-id>",
27463  *     "<my key>");
27464  *
27465  * var keyboardComponent = viewer.getComponent("keyboard");
27466  * ```
27467  */
27468 var KeyboardComponent = /** @class */ (function (_super) {
27469     __extends(KeyboardComponent, _super);
27470     function KeyboardComponent(name, container, navigator) {
27471         var _this = _super.call(this, name, container, navigator) || this;
27472         _this._keyPlayHandler = new Component_1.KeyPlayHandler(_this, container, navigator);
27473         _this._keySequenceNavigationHandler = new Component_1.KeySequenceNavigationHandler(_this, container, navigator);
27474         _this._keySpatialNavigationHandler = new Component_1.KeySpatialNavigationHandler(_this, container, navigator, new Geo_1.Spatial());
27475         _this._keyZoomHandler = new Component_1.KeyZoomHandler(_this, container, navigator, new Geo_1.ViewportCoords());
27476         return _this;
27477     }
27478     Object.defineProperty(KeyboardComponent.prototype, "keyPlay", {
27479         /**
27480          * Get key play.
27481          *
27482          * @returns {KeyPlayHandler} The key play handler.
27483          */
27484         get: function () {
27485             return this._keyPlayHandler;
27486         },
27487         enumerable: true,
27488         configurable: true
27489     });
27490     Object.defineProperty(KeyboardComponent.prototype, "keySequenceNavigation", {
27491         /**
27492          * Get key sequence navigation.
27493          *
27494          * @returns {KeySequenceNavigationHandler} The key sequence navigation handler.
27495          */
27496         get: function () {
27497             return this._keySequenceNavigationHandler;
27498         },
27499         enumerable: true,
27500         configurable: true
27501     });
27502     Object.defineProperty(KeyboardComponent.prototype, "keySpatialNavigation", {
27503         /**
27504          * Get spatial.
27505          *
27506          * @returns {KeySpatialNavigationHandler} The spatial handler.
27507          */
27508         get: function () {
27509             return this._keySpatialNavigationHandler;
27510         },
27511         enumerable: true,
27512         configurable: true
27513     });
27514     Object.defineProperty(KeyboardComponent.prototype, "keyZoom", {
27515         /**
27516          * Get key zoom.
27517          *
27518          * @returns {KeyZoomHandler} The key zoom handler.
27519          */
27520         get: function () {
27521             return this._keyZoomHandler;
27522         },
27523         enumerable: true,
27524         configurable: true
27525     });
27526     KeyboardComponent.prototype._activate = function () {
27527         var _this = this;
27528         this._configurationSubscription = this._configuration$
27529             .subscribe(function (configuration) {
27530             if (configuration.keyPlay) {
27531                 _this._keyPlayHandler.enable();
27532             }
27533             else {
27534                 _this._keyPlayHandler.disable();
27535             }
27536             if (configuration.keySequenceNavigation) {
27537                 _this._keySequenceNavigationHandler.enable();
27538             }
27539             else {
27540                 _this._keySequenceNavigationHandler.disable();
27541             }
27542             if (configuration.keySpatialNavigation) {
27543                 _this._keySpatialNavigationHandler.enable();
27544             }
27545             else {
27546                 _this._keySpatialNavigationHandler.disable();
27547             }
27548             if (configuration.keyZoom) {
27549                 _this._keyZoomHandler.enable();
27550             }
27551             else {
27552                 _this._keyZoomHandler.disable();
27553             }
27554         });
27555     };
27556     KeyboardComponent.prototype._deactivate = function () {
27557         this._configurationSubscription.unsubscribe();
27558         this._keyPlayHandler.disable();
27559         this._keySequenceNavigationHandler.disable();
27560         this._keySpatialNavigationHandler.disable();
27561         this._keyZoomHandler.disable();
27562     };
27563     KeyboardComponent.prototype._getDefaultConfiguration = function () {
27564         return { keyPlay: true, keySequenceNavigation: true, keySpatialNavigation: true, keyZoom: true };
27565     };
27566     KeyboardComponent.componentName = "keyboard";
27567     return KeyboardComponent;
27568 }(Component_1.Component));
27569 exports.KeyboardComponent = KeyboardComponent;
27570 Component_1.ComponentService.register(KeyboardComponent);
27571 exports.default = KeyboardComponent;
27572
27573 },{"../../Component":291,"../../Geo":294}],334:[function(require,module,exports){
27574 "use strict";
27575 Object.defineProperty(exports, "__esModule", { value: true });
27576 var MarkerComponent_1 = require("./MarkerComponent");
27577 exports.MarkerComponent = MarkerComponent_1.MarkerComponent;
27578 var SimpleMarker_1 = require("./marker/SimpleMarker");
27579 exports.SimpleMarker = SimpleMarker_1.SimpleMarker;
27580 var CircleMarker_1 = require("./marker/CircleMarker");
27581 exports.CircleMarker = CircleMarker_1.CircleMarker;
27582
27583 },{"./MarkerComponent":335,"./marker/CircleMarker":338,"./marker/SimpleMarker":340}],335:[function(require,module,exports){
27584 "use strict";
27585 /// <reference path="../../../typings/index.d.ts" />
27586 var __extends = (this && this.__extends) || (function () {
27587     var extendStatics = Object.setPrototypeOf ||
27588         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
27589         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
27590     return function (d, b) {
27591         extendStatics(d, b);
27592         function __() { this.constructor = d; }
27593         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
27594     };
27595 })();
27596 Object.defineProperty(exports, "__esModule", { value: true });
27597 var THREE = require("three");
27598 var when = require("when");
27599 var Observable_1 = require("rxjs/Observable");
27600 require("rxjs/add/observable/combineLatest");
27601 require("rxjs/add/operator/distinctUntilChanged");
27602 require("rxjs/add/operator/map");
27603 var Component_1 = require("../../Component");
27604 var Render_1 = require("../../Render");
27605 var Graph_1 = require("../../Graph");
27606 var Geo_1 = require("../../Geo");
27607 /**
27608  * @class MarkerComponent
27609  *
27610  * @classdesc Component for showing and editing 3D marker objects.
27611  *
27612  * The `add` method is used for adding new markers or replacing
27613  * markers already in the set.
27614  *
27615  * If a marker already in the set has the same
27616  * id as one of the markers added, the old marker will be removed and
27617  * the added marker will take its place.
27618  *
27619  * It is not possible to update markers in the set by updating any properties
27620  * directly on the marker object. Markers need to be replaced by
27621  * re-adding them for updates to geographic position or configuration
27622  * to be reflected.
27623  *
27624  * Markers added to the marker component can be either interactive
27625  * or non-interactive. Different marker types define their behavior.
27626  * Markers with interaction support can be configured with options
27627  * to respond to dragging inside the viewer and be detected when
27628  * retrieving markers from pixel points with the `getMarkerIdAt` method.
27629  *
27630  * To retrive and use the marker component
27631  *
27632  * @example
27633  * ```
27634  * var viewer = new Mapillary.Viewer(
27635  *     "<element-id>",
27636  *     "<client-id>",
27637  *     "<my key>",
27638  *     { component: { marker: true } });
27639  *
27640  * var markerComponent = viewer.getComponent("marker");
27641  * ```
27642  */
27643 var MarkerComponent = /** @class */ (function (_super) {
27644     __extends(MarkerComponent, _super);
27645     function MarkerComponent(name, container, navigator) {
27646         var _this = _super.call(this, name, container, navigator) || this;
27647         _this._relativeGroundAltitude = -2;
27648         _this._geoCoords = new Geo_1.GeoCoords();
27649         _this._graphCalculator = new Graph_1.GraphCalculator();
27650         _this._markerScene = new Component_1.MarkerScene();
27651         _this._markerSet = new Component_1.MarkerSet();
27652         _this._viewportCoords = new Geo_1.ViewportCoords();
27653         return _this;
27654     }
27655     /**
27656      * Add markers to the marker set or replace markers in the marker set.
27657      *
27658      * @description If a marker already in the set has the same
27659      * id as one of the markers added, the old marker will be removed
27660      * the added marker will take its place.
27661      *
27662      * Any marker inside the visible bounding bbox
27663      * will be initialized and placed in the viewer.
27664      *
27665      * @param {Array<Marker>} markers - Markers to add.
27666      *
27667      * @example ```markerComponent.add([marker1, marker2]);```
27668      */
27669     MarkerComponent.prototype.add = function (markers) {
27670         this._markerSet.add(markers);
27671     };
27672     /**
27673      * Returns the marker in the marker set with the specified id, or
27674      * undefined if the id matches no marker.
27675      *
27676      * @param {string} markerId - Id of the marker.
27677      *
27678      * @example ```var marker = markerComponent.get("markerId");```
27679      *
27680      */
27681     MarkerComponent.prototype.get = function (markerId) {
27682         return this._markerSet.get(markerId);
27683     };
27684     /**
27685      * Returns an array of all markers.
27686      *
27687      * @example ```var markers = markerComponent.getAll();```
27688      */
27689     MarkerComponent.prototype.getAll = function () {
27690         return this._markerSet.getAll();
27691     };
27692     /**
27693      * Returns the id of the interactive marker closest to the current camera
27694      * position at the specified point.
27695      *
27696      * @description Notice that the pixelPoint argument requires x, y
27697      * coordinates from pixel space.
27698      *
27699      * With this function, you can use the coordinates provided by mouse
27700      * events to get information out of the marker component.
27701      *
27702      * If no interactive geometry of an interactive marker exist at the pixel
27703      * point, `null` will be returned.
27704      *
27705      * @param {Array<number>} pixelPoint - Pixel coordinates on the viewer element.
27706      * @returns {string} Id of the interactive marker closest to the camera. If no
27707      * interactive marker exist at the pixel point, `null` will be returned.
27708      *
27709      * @example
27710      * ```
27711      * markerComponent.getMarkerIdAt([100, 100])
27712      *     .then((markerId) => { console.log(markerId); });
27713      * ```
27714      */
27715     MarkerComponent.prototype.getMarkerIdAt = function (pixelPoint) {
27716         var _this = this;
27717         return when.promise(function (resolve, reject) {
27718             _this._container.renderService.renderCamera$
27719                 .first()
27720                 .map(function (render) {
27721                 var viewport = _this._viewportCoords
27722                     .canvasToViewport(pixelPoint[0], pixelPoint[1], _this._container.element);
27723                 var id = _this._markerScene.intersectObjects(viewport, render.perspective);
27724                 return id;
27725             })
27726                 .subscribe(function (id) {
27727                 resolve(id);
27728             }, function (error) {
27729                 reject(error);
27730             });
27731         });
27732     };
27733     /**
27734      * Check if a marker exist in the marker set.
27735      *
27736      * @param {string} markerId - Id of the marker.
27737      *
27738      * @example ```var markerExists = markerComponent.has("markerId");```
27739      */
27740     MarkerComponent.prototype.has = function (markerId) {
27741         return this._markerSet.has(markerId);
27742     };
27743     /**
27744      * Remove markers with the specified ids from the marker set.
27745      *
27746      * @param {Array<string>} markerIds - Ids for markers to remove.
27747      *
27748      * @example ```markerComponent.remove(["id-1", "id-2"]);```
27749      */
27750     MarkerComponent.prototype.remove = function (markerIds) {
27751         this._markerSet.remove(markerIds);
27752     };
27753     /**
27754      * Remove all markers from the marker set.
27755      *
27756      * @example ```markerComponent.removeAll();```
27757      */
27758     MarkerComponent.prototype.removeAll = function () {
27759         this._markerSet.removeAll();
27760     };
27761     MarkerComponent.prototype._activate = function () {
27762         var _this = this;
27763         var groundAltitude$ = this._navigator.stateService.currentState$
27764             .map(function (frame) {
27765             return frame.state.camera.position.z + _this._relativeGroundAltitude;
27766         })
27767             .distinctUntilChanged(function (a1, a2) {
27768             return Math.abs(a1 - a2) < 0.01;
27769         })
27770             .publishReplay(1)
27771             .refCount();
27772         var geoInitiated$ = Observable_1.Observable
27773             .combineLatest(groundAltitude$, this._navigator.stateService.reference$)
27774             .first()
27775             .map(function () { })
27776             .publishReplay(1)
27777             .refCount();
27778         var clampedConfiguration$ = this._configuration$
27779             .map(function (configuration) {
27780             return { visibleBBoxSize: Math.max(1, Math.min(200, configuration.visibleBBoxSize)) };
27781         });
27782         var currentlatLon$ = this._navigator.stateService.currentNode$
27783             .map(function (node) { return node.latLon; })
27784             .publishReplay(1)
27785             .refCount();
27786         var visibleBBox$ = Observable_1.Observable
27787             .combineLatest(clampedConfiguration$, currentlatLon$)
27788             .map(function (_a) {
27789             var configuration = _a[0], latLon = _a[1];
27790             return _this._graphCalculator
27791                 .boundingBoxCorners(latLon, configuration.visibleBBoxSize / 2);
27792         })
27793             .publishReplay(1)
27794             .refCount();
27795         var visibleMarkers$ = Observable_1.Observable
27796             .combineLatest(Observable_1.Observable
27797             .of(this._markerSet)
27798             .concat(this._markerSet.changed$), visibleBBox$)
27799             .map(function (_a) {
27800             var set = _a[0], bbox = _a[1];
27801             return set.search(bbox);
27802         });
27803         this._setChangedSubscription = geoInitiated$
27804             .switchMap(function () {
27805             return visibleMarkers$
27806                 .withLatestFrom(_this._navigator.stateService.reference$, groundAltitude$);
27807         })
27808             .subscribe(function (_a) {
27809             var markers = _a[0], reference = _a[1], alt = _a[2];
27810             var geoCoords = _this._geoCoords;
27811             var markerScene = _this._markerScene;
27812             var sceneMarkers = markerScene.markers;
27813             var markersToRemove = Object.assign({}, sceneMarkers);
27814             for (var _i = 0, markers_1 = markers; _i < markers_1.length; _i++) {
27815                 var marker = markers_1[_i];
27816                 if (marker.id in sceneMarkers) {
27817                     delete markersToRemove[marker.id];
27818                 }
27819                 else {
27820                     var point3d = geoCoords
27821                         .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
27822                     markerScene.add(marker, point3d);
27823                 }
27824             }
27825             for (var id in markersToRemove) {
27826                 if (!markersToRemove.hasOwnProperty(id)) {
27827                     continue;
27828                 }
27829                 markerScene.remove(id);
27830             }
27831         });
27832         this._markersUpdatedSubscription = geoInitiated$
27833             .switchMap(function () {
27834             return _this._markerSet.updated$
27835                 .withLatestFrom(visibleBBox$, _this._navigator.stateService.reference$, groundAltitude$);
27836         })
27837             .subscribe(function (_a) {
27838             var markers = _a[0], _b = _a[1], sw = _b[0], ne = _b[1], reference = _a[2], alt = _a[3];
27839             var geoCoords = _this._geoCoords;
27840             var markerScene = _this._markerScene;
27841             for (var _i = 0, markers_2 = markers; _i < markers_2.length; _i++) {
27842                 var marker = markers_2[_i];
27843                 var exists = markerScene.has(marker.id);
27844                 var visible = marker.latLon.lat > sw.lat &&
27845                     marker.latLon.lat < ne.lat &&
27846                     marker.latLon.lon > sw.lon &&
27847                     marker.latLon.lon < ne.lon;
27848                 if (visible) {
27849                     var point3d = geoCoords
27850                         .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
27851                     markerScene.add(marker, point3d);
27852                 }
27853                 else if (!visible && exists) {
27854                     markerScene.remove(marker.id);
27855                 }
27856             }
27857         });
27858         this._referenceSubscription = this._navigator.stateService.reference$
27859             .skip(1)
27860             .withLatestFrom(groundAltitude$)
27861             .subscribe(function (_a) {
27862             var reference = _a[0], alt = _a[1];
27863             var geoCoords = _this._geoCoords;
27864             var markerScene = _this._markerScene;
27865             for (var _i = 0, _b = markerScene.getAll(); _i < _b.length; _i++) {
27866                 var marker = _b[_i];
27867                 var point3d = geoCoords
27868                     .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
27869                 markerScene.update(marker.id, point3d);
27870             }
27871         });
27872         this._adjustHeightSubscription = groundAltitude$
27873             .skip(1)
27874             .withLatestFrom(this._navigator.stateService.reference$, currentlatLon$)
27875             .subscribe(function (_a) {
27876             var alt = _a[0], reference = _a[1], latLon = _a[2];
27877             var geoCoords = _this._geoCoords;
27878             var markerScene = _this._markerScene;
27879             var position = geoCoords
27880                 .geodeticToEnu(latLon.lat, latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
27881             for (var _i = 0, _b = markerScene.getAll(); _i < _b.length; _i++) {
27882                 var marker = _b[_i];
27883                 var point3d = geoCoords
27884                     .geodeticToEnu(marker.latLon.lat, marker.latLon.lon, reference.alt + alt, reference.lat, reference.lon, reference.alt);
27885                 var distanceX = point3d[0] - position[0];
27886                 var distanceY = point3d[1] - position[1];
27887                 var groundDistance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
27888                 if (groundDistance > 50) {
27889                     continue;
27890                 }
27891                 markerScene.lerpAltitude(marker.id, alt, Math.min(1, Math.max(0, 1.2 - 1.2 * groundDistance / 50)));
27892             }
27893         });
27894         this._renderSubscription = this._navigator.stateService.currentState$
27895             .map(function (frame) {
27896             var scene = _this._markerScene;
27897             return {
27898                 name: _this._name,
27899                 render: {
27900                     frameId: frame.id,
27901                     needsRender: scene.needsRender,
27902                     render: scene.render.bind(scene),
27903                     stage: Render_1.GLRenderStage.Foreground,
27904                 },
27905             };
27906         })
27907             .subscribe(this._container.glRenderer.render$);
27908         var hoveredMarkerId$ = Observable_1.Observable
27909             .combineLatest(this._container.renderService.renderCamera$, this._container.mouseService.mouseMove$)
27910             .map(function (_a) {
27911             var render = _a[0], event = _a[1];
27912             var element = _this._container.element;
27913             var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
27914             var viewport = _this._viewportCoords.canvasToViewport(canvasX, canvasY, element);
27915             var markerId = _this._markerScene.intersectObjects(viewport, render.perspective);
27916             return markerId;
27917         })
27918             .publishReplay(1)
27919             .refCount();
27920         var draggingStarted$ = this._container.mouseService
27921             .filtered$(this._name, this._container.mouseService.mouseDragStart$)
27922             .map(function (event) {
27923             return true;
27924         });
27925         var draggingStopped$ = this._container.mouseService
27926             .filtered$(this._name, this._container.mouseService.mouseDragEnd$)
27927             .map(function (event) {
27928             return false;
27929         });
27930         var filteredDragging$ = Observable_1.Observable
27931             .merge(draggingStarted$, draggingStopped$)
27932             .startWith(false);
27933         this._dragEventSubscription = draggingStarted$
27934             .withLatestFrom(hoveredMarkerId$)
27935             .merge(Observable_1.Observable
27936             .combineLatest(draggingStopped$, Observable_1.Observable.of(null)))
27937             .startWith([false, null])
27938             .pairwise()
27939             .subscribe(function (_a) {
27940             var previous = _a[0], current = _a[1];
27941             var dragging = current[0];
27942             var eventType = dragging ? MarkerComponent.dragstart : MarkerComponent.dragend;
27943             var id = dragging ? current[1] : previous[1];
27944             var marker = _this._markerScene.get(id);
27945             var markerEvent = { marker: marker, target: _this, type: eventType };
27946             _this.fire(eventType, markerEvent);
27947         });
27948         var mouseDown$ = Observable_1.Observable
27949             .merge(this._container.mouseService.mouseDown$
27950             .map(function (event) { return true; }), this._container.mouseService.documentMouseUp$
27951             .map(function (event) { return false; }))
27952             .startWith(false);
27953         this._mouseClaimSubscription = Observable_1.Observable
27954             .combineLatest(this._container.mouseService.active$, hoveredMarkerId$.distinctUntilChanged(), mouseDown$, filteredDragging$)
27955             .map(function (_a) {
27956             var active = _a[0], markerId = _a[1], mouseDown = _a[2], filteredDragging = _a[3];
27957             return (!active && markerId != null && mouseDown) || filteredDragging;
27958         })
27959             .distinctUntilChanged()
27960             .subscribe(function (claim) {
27961             if (claim) {
27962                 _this._container.mouseService.claimMouse(_this._name, 1);
27963                 _this._container.mouseService.claimWheel(_this._name, 1);
27964             }
27965             else {
27966                 _this._container.mouseService.unclaimMouse(_this._name);
27967                 _this._container.mouseService.unclaimWheel(_this._name);
27968             }
27969         });
27970         var offset$ = this._container.mouseService
27971             .filtered$(this._name, this._container.mouseService.mouseDragStart$)
27972             .withLatestFrom(hoveredMarkerId$, this._container.renderService.renderCamera$)
27973             .map(function (_a) {
27974             var e = _a[0], id = _a[1], r = _a[2];
27975             var marker = _this._markerScene.get(id);
27976             var element = _this._container.element;
27977             var _b = _this._viewportCoords.projectToCanvas(marker.geometry.position.toArray(), element, r.perspective), groundCanvasX = _b[0], groundCanvasY = _b[1];
27978             var _c = _this._viewportCoords.canvasPosition(e, element), canvasX = _c[0], canvasY = _c[1];
27979             var offset = [canvasX - groundCanvasX, canvasY - groundCanvasY];
27980             return [marker, offset, r];
27981         })
27982             .publishReplay(1)
27983             .refCount();
27984         this._updateMarkerSubscription = this._container.mouseService
27985             .filtered$(this._name, this._container.mouseService.mouseDrag$)
27986             .withLatestFrom(offset$, this._navigator.stateService.reference$, clampedConfiguration$)
27987             .subscribe(function (_a) {
27988             var event = _a[0], _b = _a[1], marker = _b[0], offset = _b[1], render = _b[2], reference = _a[2], configuration = _a[3];
27989             if (!_this._markerScene.has(marker.id)) {
27990                 return;
27991             }
27992             var element = _this._container.element;
27993             var _c = _this._viewportCoords.canvasPosition(event, element), canvasX = _c[0], canvasY = _c[1];
27994             var groundX = canvasX - offset[0];
27995             var groundY = canvasY - offset[1];
27996             var _d = _this._viewportCoords
27997                 .canvasToViewport(groundX, groundY, element), viewportX = _d[0], viewportY = _d[1];
27998             var direction = new THREE.Vector3(viewportX, viewportY, 1)
27999                 .unproject(render.perspective)
28000                 .sub(render.perspective.position)
28001                 .normalize();
28002             var distance = Math.min(_this._relativeGroundAltitude / direction.z, configuration.visibleBBoxSize / 2 - 0.1);
28003             if (distance < 0) {
28004                 return;
28005             }
28006             var intersection = direction
28007                 .clone()
28008                 .multiplyScalar(distance)
28009                 .add(render.perspective.position);
28010             intersection.z = render.perspective.position.z + _this._relativeGroundAltitude;
28011             var _e = _this._geoCoords
28012                 .enuToGeodetic(intersection.x, intersection.y, intersection.z, reference.lat, reference.lon, reference.alt), lat = _e[0], lon = _e[1];
28013             _this._markerScene.update(marker.id, intersection.toArray(), { lat: lat, lon: lon });
28014             _this._markerSet.update(marker);
28015             var markerEvent = { marker: marker, target: _this, type: MarkerComponent.changed };
28016             _this.fire(MarkerComponent.changed, markerEvent);
28017         });
28018     };
28019     MarkerComponent.prototype._deactivate = function () {
28020         this._adjustHeightSubscription.unsubscribe();
28021         this._dragEventSubscription.unsubscribe();
28022         this._markersUpdatedSubscription.unsubscribe();
28023         this._mouseClaimSubscription.unsubscribe();
28024         this._referenceSubscription.unsubscribe();
28025         this._renderSubscription.unsubscribe();
28026         this._setChangedSubscription.unsubscribe();
28027         this._updateMarkerSubscription.unsubscribe();
28028         this._markerScene.clear();
28029     };
28030     MarkerComponent.prototype._getDefaultConfiguration = function () {
28031         return { visibleBBoxSize: 100 };
28032     };
28033     MarkerComponent.componentName = "marker";
28034     /**
28035      * Fired when the position of a marker is changed.
28036      * @event
28037      * @type {IMarkerEvent} markerEvent - Marker event data.
28038      * @example
28039      * ```
28040      * markerComponent.on("changed", function(e) {
28041      *     console.log(e.marker.id, e.marker.latLon);
28042      * });
28043      * ```
28044      */
28045     MarkerComponent.changed = "changed";
28046     /**
28047      * Fired when a marker drag interaction starts.
28048      * @event
28049      * @type {IMarkerEvent} markerEvent - Marker event data.
28050      * @example
28051      * ```
28052      * markerComponent.on("dragstart", function(e) {
28053      *     console.log(e.marker.id, e.marker.latLon);
28054      * });
28055      * ```
28056      */
28057     MarkerComponent.dragstart = "dragstart";
28058     /**
28059      * Fired when a marker drag interaction ends.
28060      * @event
28061      * @type {IMarkerEvent} markerEvent - Marker event data.
28062      * @example
28063      * ```
28064      * markerComponent.on("dragend", function(e) {
28065      *     console.log(e.marker.id, e.marker.latLon);
28066      * });
28067      * ```
28068      */
28069     MarkerComponent.dragend = "dragend";
28070     return MarkerComponent;
28071 }(Component_1.Component));
28072 exports.MarkerComponent = MarkerComponent;
28073 Component_1.ComponentService.register(MarkerComponent);
28074 exports.default = MarkerComponent;
28075
28076 },{"../../Component":291,"../../Geo":294,"../../Graph":295,"../../Render":297,"rxjs/Observable":29,"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/distinctUntilChanged":60,"rxjs/add/operator/map":67,"three":241,"when":288}],336:[function(require,module,exports){
28077 "use strict";
28078 /// <reference path="../../../typings/index.d.ts" />
28079 Object.defineProperty(exports, "__esModule", { value: true });
28080 var THREE = require("three");
28081 var MarkerScene = /** @class */ (function () {
28082     function MarkerScene(scene, raycaster) {
28083         this._needsRender = false;
28084         this._interactiveObjects = [];
28085         this._markers = {};
28086         this._objectMarkers = {};
28087         this._raycaster = !!raycaster ? raycaster : new THREE.Raycaster();
28088         this._scene = !!scene ? scene : new THREE.Scene();
28089     }
28090     Object.defineProperty(MarkerScene.prototype, "markers", {
28091         get: function () {
28092             return this._markers;
28093         },
28094         enumerable: true,
28095         configurable: true
28096     });
28097     Object.defineProperty(MarkerScene.prototype, "needsRender", {
28098         get: function () {
28099             return this._needsRender;
28100         },
28101         enumerable: true,
28102         configurable: true
28103     });
28104     MarkerScene.prototype.add = function (marker, position) {
28105         if (marker.id in this._markers) {
28106             this._dispose(marker.id);
28107         }
28108         marker.createGeometry(position);
28109         this._scene.add(marker.geometry);
28110         this._markers[marker.id] = marker;
28111         for (var _i = 0, _a = marker.getInteractiveObjects(); _i < _a.length; _i++) {
28112             var interactiveObject = _a[_i];
28113             this._interactiveObjects.push(interactiveObject);
28114             this._objectMarkers[interactiveObject.uuid] = marker.id;
28115         }
28116         this._needsRender = true;
28117     };
28118     MarkerScene.prototype.clear = function () {
28119         for (var id in this._markers) {
28120             if (!this._markers.hasOwnProperty) {
28121                 continue;
28122             }
28123             this._dispose(id);
28124         }
28125         this._needsRender = true;
28126     };
28127     MarkerScene.prototype.get = function (id) {
28128         return this._markers[id];
28129     };
28130     MarkerScene.prototype.getAll = function () {
28131         var _this = this;
28132         return Object
28133             .keys(this._markers)
28134             .map(function (id) { return _this._markers[id]; });
28135     };
28136     MarkerScene.prototype.has = function (id) {
28137         return id in this._markers;
28138     };
28139     MarkerScene.prototype.intersectObjects = function (_a, camera) {
28140         var viewportX = _a[0], viewportY = _a[1];
28141         this._raycaster.setFromCamera(new THREE.Vector2(viewportX, viewportY), camera);
28142         var intersects = this._raycaster.intersectObjects(this._interactiveObjects);
28143         for (var _i = 0, intersects_1 = intersects; _i < intersects_1.length; _i++) {
28144             var intersect = intersects_1[_i];
28145             if (intersect.object.uuid in this._objectMarkers) {
28146                 return this._objectMarkers[intersect.object.uuid];
28147             }
28148         }
28149         return null;
28150     };
28151     MarkerScene.prototype.lerpAltitude = function (id, alt, alpha) {
28152         if (!(id in this._markers)) {
28153             return;
28154         }
28155         this._markers[id].lerpAltitude(alt, alpha);
28156         this._needsRender = true;
28157     };
28158     MarkerScene.prototype.remove = function (id) {
28159         if (!(id in this._markers)) {
28160             return;
28161         }
28162         this._dispose(id);
28163         this._needsRender = true;
28164     };
28165     MarkerScene.prototype.render = function (perspectiveCamera, renderer) {
28166         renderer.render(this._scene, perspectiveCamera);
28167         this._needsRender = false;
28168     };
28169     MarkerScene.prototype.update = function (id, position, latLon) {
28170         if (!(id in this._markers)) {
28171             return;
28172         }
28173         var marker = this._markers[id];
28174         marker.updatePosition(position, latLon);
28175         this._needsRender = true;
28176     };
28177     MarkerScene.prototype._dispose = function (id) {
28178         var marker = this._markers[id];
28179         this._scene.remove(marker.geometry);
28180         for (var _i = 0, _a = marker.getInteractiveObjects(); _i < _a.length; _i++) {
28181             var interactiveObject = _a[_i];
28182             var index = this._interactiveObjects.indexOf(interactiveObject);
28183             if (index !== -1) {
28184                 this._interactiveObjects.splice(index, 1);
28185             }
28186             else {
28187                 console.warn("Object does not exist (" + interactiveObject.id + ") for " + id);
28188             }
28189             delete this._objectMarkers[interactiveObject.uuid];
28190         }
28191         marker.disposeGeometry();
28192         delete this._markers[id];
28193     };
28194     return MarkerScene;
28195 }());
28196 exports.MarkerScene = MarkerScene;
28197 exports.default = MarkerScene;
28198
28199 },{"three":241}],337:[function(require,module,exports){
28200 "use strict";
28201 /// <reference path="../../../typings/index.d.ts" />
28202 Object.defineProperty(exports, "__esModule", { value: true });
28203 var rbush = require("rbush");
28204 var Subject_1 = require("rxjs/Subject");
28205 require("rxjs/add/operator/map");
28206 require("rxjs/add/operator/publishReplay");
28207 require("rxjs/add/operator/scan");
28208 var MarkerSet = /** @class */ (function () {
28209     function MarkerSet() {
28210         this._hash = {};
28211         this._index = rbush(16, [".lon", ".lat", ".lon", ".lat"]);
28212         this._indexChanged$ = new Subject_1.Subject();
28213         this._updated$ = new Subject_1.Subject();
28214     }
28215     Object.defineProperty(MarkerSet.prototype, "changed$", {
28216         get: function () {
28217             return this._indexChanged$;
28218         },
28219         enumerable: true,
28220         configurable: true
28221     });
28222     Object.defineProperty(MarkerSet.prototype, "updated$", {
28223         get: function () {
28224             return this._updated$;
28225         },
28226         enumerable: true,
28227         configurable: true
28228     });
28229     MarkerSet.prototype.add = function (markers) {
28230         var updated = [];
28231         var hash = this._hash;
28232         var index = this._index;
28233         for (var _i = 0, markers_1 = markers; _i < markers_1.length; _i++) {
28234             var marker = markers_1[_i];
28235             var id = marker.id;
28236             if (id in hash) {
28237                 index.remove(hash[id]);
28238                 updated.push(marker);
28239             }
28240             var item = {
28241                 lat: marker.latLon.lat,
28242                 lon: marker.latLon.lon,
28243                 marker: marker,
28244             };
28245             hash[id] = item;
28246             index.insert(item);
28247         }
28248         if (updated.length > 0) {
28249             this._updated$.next(updated);
28250         }
28251         if (markers.length > updated.length) {
28252             this._indexChanged$.next(this);
28253         }
28254     };
28255     MarkerSet.prototype.has = function (id) {
28256         return id in this._hash;
28257     };
28258     MarkerSet.prototype.get = function (id) {
28259         return this.has(id) ? this._hash[id].marker : undefined;
28260     };
28261     MarkerSet.prototype.getAll = function () {
28262         return this._index
28263             .all()
28264             .map(function (indexItem) {
28265             return indexItem.marker;
28266         });
28267     };
28268     MarkerSet.prototype.remove = function (ids) {
28269         var hash = this._hash;
28270         var index = this._index;
28271         var changed = false;
28272         for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
28273             var id = ids_1[_i];
28274             if (!(id in hash)) {
28275                 continue;
28276             }
28277             var item = hash[id];
28278             index.remove(item);
28279             delete hash[id];
28280             changed = true;
28281         }
28282         if (changed) {
28283             this._indexChanged$.next(this);
28284         }
28285     };
28286     MarkerSet.prototype.removeAll = function () {
28287         this._hash = {};
28288         this._index.clear();
28289         this._indexChanged$.next(this);
28290     };
28291     MarkerSet.prototype.search = function (_a) {
28292         var sw = _a[0], ne = _a[1];
28293         return this._index
28294             .search({ maxX: ne.lon, maxY: ne.lat, minX: sw.lon, minY: sw.lat })
28295             .map(function (indexItem) {
28296             return indexItem.marker;
28297         });
28298     };
28299     MarkerSet.prototype.update = function (marker) {
28300         var hash = this._hash;
28301         var index = this._index;
28302         var id = marker.id;
28303         if (!(id in hash)) {
28304             return;
28305         }
28306         index.remove(hash[id]);
28307         var item = {
28308             lat: marker.latLon.lat,
28309             lon: marker.latLon.lon,
28310             marker: marker,
28311         };
28312         hash[id] = item;
28313         index.insert(item);
28314     };
28315     return MarkerSet;
28316 }());
28317 exports.MarkerSet = MarkerSet;
28318 exports.default = MarkerSet;
28319
28320 },{"rbush":25,"rxjs/Subject":34,"rxjs/add/operator/map":67,"rxjs/add/operator/publishReplay":74,"rxjs/add/operator/scan":78}],338:[function(require,module,exports){
28321 "use strict";
28322 /// <reference path="../../../../typings/index.d.ts" />
28323 var __extends = (this && this.__extends) || (function () {
28324     var extendStatics = Object.setPrototypeOf ||
28325         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28326         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28327     return function (d, b) {
28328         extendStatics(d, b);
28329         function __() { this.constructor = d; }
28330         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28331     };
28332 })();
28333 Object.defineProperty(exports, "__esModule", { value: true });
28334 var THREE = require("three");
28335 var Component_1 = require("../../../Component");
28336 /**
28337  * @class CircleMarker
28338  *
28339  * @classdesc Non-interactive marker with a flat circle shape. The circle
28340  * marker can not be configured to be interactive.
28341  *
28342  * Circle marker properties can not be updated after creation.
28343  *
28344  * To create and add one `CircleMarker` with default configuration
28345  * and one with configuration use
28346  *
28347  * @example
28348  * ```
28349  * var defaultMarker = new Mapillary.MarkerComponent.CircleMarker(
28350  *     "id-1",
28351  *     { lat: 0, lon: 0, });
28352  *
28353  * var configuredMarker = new Mapillary.MarkerComponent.CircleMarker(
28354  *     "id-2",
28355  *     { lat: 0, lon: 0, },
28356  *     {
28357  *         color: "#0Ff",
28358  *         opacity: 0.3,
28359  *         radius: 0.7,
28360  *     });
28361  *
28362  * markerComponent.add([defaultMarker, configuredMarker]);
28363  * ```
28364  */
28365 var CircleMarker = /** @class */ (function (_super) {
28366     __extends(CircleMarker, _super);
28367     function CircleMarker(id, latLon, options) {
28368         var _this = _super.call(this, id, latLon) || this;
28369         options = !!options ? options : {};
28370         _this._color = options.color != null ? options.color : 0xffffff;
28371         _this._opacity = options.opacity != null ? options.opacity : 0.4;
28372         _this._radius = options.radius != null ? options.radius : 1;
28373         return _this;
28374     }
28375     CircleMarker.prototype._createGeometry = function (position) {
28376         var circle = new THREE.Mesh(new THREE.CircleGeometry(this._radius, 16), new THREE.MeshBasicMaterial({
28377             color: this._color,
28378             opacity: this._opacity,
28379             transparent: true,
28380         }));
28381         circle.up.fromArray([0, 0, 1]);
28382         circle.renderOrder = -1;
28383         var group = new THREE.Object3D();
28384         group.add(circle);
28385         group.position.fromArray(position);
28386         this._geometry = group;
28387     };
28388     CircleMarker.prototype._disposeGeometry = function () {
28389         for (var _i = 0, _a = this._geometry.children; _i < _a.length; _i++) {
28390             var mesh = _a[_i];
28391             mesh.geometry.dispose();
28392             mesh.material.dispose();
28393         }
28394     };
28395     CircleMarker.prototype._getInteractiveObjects = function () {
28396         return [];
28397     };
28398     return CircleMarker;
28399 }(Component_1.Marker));
28400 exports.CircleMarker = CircleMarker;
28401 exports.default = CircleMarker;
28402
28403 },{"../../../Component":291,"three":241}],339:[function(require,module,exports){
28404 "use strict";
28405 /// <reference path="../../../../typings/index.d.ts" />
28406 Object.defineProperty(exports, "__esModule", { value: true });
28407 /**
28408  * @class Marker
28409  *
28410  * @classdesc Represents an abstract marker class that should be extended
28411  * by marker implementations used in the marker component.
28412  */
28413 var Marker = /** @class */ (function () {
28414     function Marker(id, latLon) {
28415         this._id = id;
28416         this._latLon = latLon;
28417     }
28418     Object.defineProperty(Marker.prototype, "id", {
28419         /**
28420          * Get id.
28421          * @returns {string} The id of the marker.
28422          */
28423         get: function () {
28424             return this._id;
28425         },
28426         enumerable: true,
28427         configurable: true
28428     });
28429     Object.defineProperty(Marker.prototype, "geometry", {
28430         get: function () {
28431             return this._geometry;
28432         },
28433         enumerable: true,
28434         configurable: true
28435     });
28436     Object.defineProperty(Marker.prototype, "latLon", {
28437         /**
28438          * Get lat lon.
28439          * @returns {ILatLon} The geographic coordinates of the marker.
28440          */
28441         get: function () {
28442             return this._latLon;
28443         },
28444         enumerable: true,
28445         configurable: true
28446     });
28447     Marker.prototype.createGeometry = function (position) {
28448         if (!!this._geometry) {
28449             return;
28450         }
28451         this._createGeometry(position);
28452         // update matrix world if raycasting occurs before first render
28453         this._geometry.updateMatrixWorld(true);
28454     };
28455     Marker.prototype.disposeGeometry = function () {
28456         if (!this._geometry) {
28457             return;
28458         }
28459         this._disposeGeometry();
28460         this._geometry = undefined;
28461     };
28462     Marker.prototype.getInteractiveObjects = function () {
28463         if (!this._geometry) {
28464             return [];
28465         }
28466         return this._getInteractiveObjects();
28467     };
28468     Marker.prototype.lerpAltitude = function (alt, alpha) {
28469         if (!this._geometry) {
28470             return;
28471         }
28472         this._geometry.position.z = (1 - alpha) * this._geometry.position.z + alpha * alt;
28473     };
28474     Marker.prototype.updatePosition = function (position, latLon) {
28475         if (!!latLon) {
28476             this._latLon.lat = latLon.lat;
28477             this._latLon.lon = latLon.lon;
28478         }
28479         if (!this._geometry) {
28480             return;
28481         }
28482         this._geometry.position.fromArray(position);
28483         this._geometry.updateMatrixWorld(true);
28484     };
28485     return Marker;
28486 }());
28487 exports.Marker = Marker;
28488 exports.default = Marker;
28489
28490 },{}],340:[function(require,module,exports){
28491 "use strict";
28492 /// <reference path="../../../../typings/index.d.ts" />
28493 var __extends = (this && this.__extends) || (function () {
28494     var extendStatics = Object.setPrototypeOf ||
28495         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28496         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28497     return function (d, b) {
28498         extendStatics(d, b);
28499         function __() { this.constructor = d; }
28500         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28501     };
28502 })();
28503 Object.defineProperty(exports, "__esModule", { value: true });
28504 var THREE = require("three");
28505 var Component_1 = require("../../../Component");
28506 /**
28507  * @class SimpleMarker
28508  *
28509  * @classdesc Interactive marker with ice cream shape. The sphere
28510  * inside the ice cream can be configured to be interactive.
28511  *
28512  * Simple marker properties can not be updated after creation.
28513  *
28514  * To create and add one `SimpleMarker` with default configuration
28515  * (non-interactive) and one interactive with configuration use
28516  *
28517  * @example
28518  * ```
28519  * var defaultMarker = new Mapillary.MarkerComponent.SimpleMarker(
28520  *     "id-1",
28521  *     { lat: 0, lon: 0, });
28522  *
28523  * var interactiveMarker = new Mapillary.MarkerComponent.SimpleMarker(
28524  *     "id-2",
28525  *     { lat: 0, lon: 0, },
28526  *     {
28527  *         ballColor: "#00f",
28528  *         ballOpacity: 0.5,
28529  *         color: "#00f",
28530  *         interactive: true,
28531  *         opacity: 0.3,
28532  *         radius: 0.7,
28533  *     });
28534  *
28535  * markerComponent.add([defaultMarker, interactiveMarker]);
28536  * ```
28537  */
28538 var SimpleMarker = /** @class */ (function (_super) {
28539     __extends(SimpleMarker, _super);
28540     function SimpleMarker(id, latLon, options) {
28541         var _this = _super.call(this, id, latLon) || this;
28542         options = !!options ? options : {};
28543         _this._ballColor = options.ballColor != null ? options.ballColor : 0xff0000;
28544         _this._ballOpacity = options.ballOpacity != null ? options.ballOpacity : 0.8;
28545         _this._circleToRayAngle = 2;
28546         _this._color = options.color != null ? options.color : 0xff0000;
28547         _this._interactive = !!options.interactive;
28548         _this._opacity = options.opacity != null ? options.opacity : 0.4;
28549         _this._radius = options.radius != null ? options.radius : 1;
28550         return _this;
28551     }
28552     SimpleMarker.prototype._createGeometry = function (position) {
28553         var radius = this._radius;
28554         var cone = new THREE.Mesh(this._markerGeometry(radius, 8, 8), new THREE.MeshBasicMaterial({
28555             color: this._color,
28556             opacity: this._opacity,
28557             transparent: true,
28558         }));
28559         cone.renderOrder = 1;
28560         var ball = new THREE.Mesh(new THREE.SphereGeometry(radius / 2, 8, 8), new THREE.MeshBasicMaterial({
28561             color: this._ballColor,
28562             opacity: this._ballOpacity,
28563             transparent: true,
28564         }));
28565         ball.position.z = this._markerHeight(radius);
28566         var group = new THREE.Object3D();
28567         group.add(ball);
28568         group.add(cone);
28569         group.position.fromArray(position);
28570         this._geometry = group;
28571     };
28572     SimpleMarker.prototype._disposeGeometry = function () {
28573         for (var _i = 0, _a = this._geometry.children; _i < _a.length; _i++) {
28574             var mesh = _a[_i];
28575             mesh.geometry.dispose();
28576             mesh.material.dispose();
28577         }
28578     };
28579     SimpleMarker.prototype._getInteractiveObjects = function () {
28580         return this._interactive ? [this._geometry.children[0]] : [];
28581     };
28582     SimpleMarker.prototype._markerHeight = function (radius) {
28583         var t = Math.tan(Math.PI - this._circleToRayAngle);
28584         return radius * Math.sqrt(1 + t * t);
28585     };
28586     SimpleMarker.prototype._markerGeometry = function (radius, widthSegments, heightSegments) {
28587         var geometry = new THREE.Geometry();
28588         widthSegments = Math.max(3, Math.floor(widthSegments) || 8);
28589         heightSegments = Math.max(2, Math.floor(heightSegments) || 6);
28590         var height = this._markerHeight(radius);
28591         var vertices = [];
28592         for (var y = 0; y <= heightSegments; ++y) {
28593             var verticesRow = [];
28594             for (var x = 0; x <= widthSegments; ++x) {
28595                 var u = x / widthSegments * Math.PI * 2;
28596                 var v = y / heightSegments * Math.PI;
28597                 var r = void 0;
28598                 if (v < this._circleToRayAngle) {
28599                     r = radius;
28600                 }
28601                 else {
28602                     var t = Math.tan(v - this._circleToRayAngle);
28603                     r = radius * Math.sqrt(1 + t * t);
28604                 }
28605                 var vertex = new THREE.Vector3();
28606                 vertex.x = r * Math.cos(u) * Math.sin(v);
28607                 vertex.y = r * Math.sin(u) * Math.sin(v);
28608                 vertex.z = r * Math.cos(v) + height;
28609                 geometry.vertices.push(vertex);
28610                 verticesRow.push(geometry.vertices.length - 1);
28611             }
28612             vertices.push(verticesRow);
28613         }
28614         for (var y = 0; y < heightSegments; ++y) {
28615             for (var x = 0; x < widthSegments; ++x) {
28616                 var v1 = vertices[y][x + 1];
28617                 var v2 = vertices[y][x];
28618                 var v3 = vertices[y + 1][x];
28619                 var v4 = vertices[y + 1][x + 1];
28620                 var n1 = geometry.vertices[v1].clone().normalize();
28621                 var n2 = geometry.vertices[v2].clone().normalize();
28622                 var n3 = geometry.vertices[v3].clone().normalize();
28623                 var n4 = geometry.vertices[v4].clone().normalize();
28624                 geometry.faces.push(new THREE.Face3(v1, v2, v4, [n1, n2, n4]));
28625                 geometry.faces.push(new THREE.Face3(v2, v3, v4, [n2.clone(), n3, n4.clone()]));
28626             }
28627         }
28628         geometry.computeFaceNormals();
28629         geometry.boundingSphere = new THREE.Sphere(new THREE.Vector3(), radius + height);
28630         return geometry;
28631     };
28632     return SimpleMarker;
28633 }(Component_1.Marker));
28634 exports.SimpleMarker = SimpleMarker;
28635 exports.default = SimpleMarker;
28636
28637 },{"../../../Component":291,"three":241}],341:[function(require,module,exports){
28638 "use strict";
28639 /// <reference path="../../../typings/index.d.ts" />
28640 var __extends = (this && this.__extends) || (function () {
28641     var extendStatics = Object.setPrototypeOf ||
28642         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28643         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28644     return function (d, b) {
28645         extendStatics(d, b);
28646         function __() { this.constructor = d; }
28647         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28648     };
28649 })();
28650 Object.defineProperty(exports, "__esModule", { value: true });
28651 var Observable_1 = require("rxjs/Observable");
28652 var Component_1 = require("../../Component");
28653 /**
28654  * The `BounceHandler` ensures that the viewer bounces back to the image
28655  * when drag panning outside of the image edge.
28656  */
28657 var BounceHandler = /** @class */ (function (_super) {
28658     __extends(BounceHandler, _super);
28659     function BounceHandler(component, container, navigator, viewportCoords, spatial) {
28660         var _this = _super.call(this, component, container, navigator) || this;
28661         _this._spatial = spatial;
28662         _this._viewportCoords = viewportCoords;
28663         _this._basicDistanceThreshold = 1e-3;
28664         _this._basicRotationThreshold = 5e-2;
28665         _this._bounceCoeff = 1e-1;
28666         return _this;
28667     }
28668     BounceHandler.prototype._enable = function () {
28669         var _this = this;
28670         var inTransition$ = this._navigator.stateService.currentState$
28671             .map(function (frame) {
28672             return frame.state.alpha < 1;
28673         });
28674         this._bounceSubscription = Observable_1.Observable
28675             .combineLatest(inTransition$, this._navigator.stateService.inTranslation$, this._container.mouseService.active$, this._container.touchService.active$)
28676             .map(function (noForce) {
28677             return noForce[0] || noForce[1] || noForce[2] || noForce[3];
28678         })
28679             .distinctUntilChanged()
28680             .switchMap(function (noForce) {
28681             return noForce ?
28682                 Observable_1.Observable.empty() :
28683                 Observable_1.Observable.combineLatest(_this._container.renderService.renderCamera$, _this._navigator.stateService.currentTransform$.first());
28684         })
28685             .subscribe(function (args) {
28686             var renderCamera = args[0];
28687             var perspectiveCamera = renderCamera.perspective;
28688             var transform = args[1];
28689             if (!transform.hasValidScale && renderCamera.camera.focal < 0.1) {
28690                 return;
28691             }
28692             if (renderCamera.perspective.aspect === 0 || renderCamera.perspective.aspect === Number.POSITIVE_INFINITY) {
28693                 return;
28694             }
28695             var distanceThreshold = _this._basicDistanceThreshold / Math.pow(2, renderCamera.zoom);
28696             var basicCenter = _this._viewportCoords.viewportToBasic(0, 0, transform, perspectiveCamera);
28697             if (Math.abs(basicCenter[0] - 0.5) < distanceThreshold && Math.abs(basicCenter[1] - 0.5) < distanceThreshold) {
28698                 return;
28699             }
28700             var basicDistances = _this._viewportCoords.getBasicDistances(transform, perspectiveCamera);
28701             var basicX = 0;
28702             var basicY = 0;
28703             if (basicDistances[0] < distanceThreshold && basicDistances[1] < distanceThreshold &&
28704                 basicDistances[2] < distanceThreshold && basicDistances[3] < distanceThreshold) {
28705                 return;
28706             }
28707             if (Math.abs(basicDistances[0] - basicDistances[2]) < distanceThreshold &&
28708                 Math.abs(basicDistances[1] - basicDistances[3]) < distanceThreshold) {
28709                 return;
28710             }
28711             var coeff = _this._bounceCoeff;
28712             if (basicDistances[1] > 0 && basicDistances[3] === 0) {
28713                 basicX = -coeff * basicDistances[1];
28714             }
28715             else if (basicDistances[1] === 0 && basicDistances[3] > 0) {
28716                 basicX = coeff * basicDistances[3];
28717             }
28718             else if (basicDistances[1] > 0 && basicDistances[3] > 0) {
28719                 basicX = coeff * (basicDistances[3] - basicDistances[1]) / 2;
28720             }
28721             if (basicDistances[0] > 0 && basicDistances[2] === 0) {
28722                 basicY = coeff * basicDistances[0];
28723             }
28724             else if (basicDistances[0] === 0 && basicDistances[2] > 0) {
28725                 basicY = -coeff * basicDistances[2];
28726             }
28727             else if (basicDistances[0] > 0 && basicDistances[2] > 0) {
28728                 basicY = coeff * (basicDistances[0] - basicDistances[2]) / 2;
28729             }
28730             var rotationThreshold = _this._basicRotationThreshold;
28731             basicX = _this._spatial.clamp(basicX, -rotationThreshold, rotationThreshold);
28732             basicY = _this._spatial.clamp(basicY, -rotationThreshold, rotationThreshold);
28733             _this._navigator.stateService.rotateBasicUnbounded([basicX, basicY]);
28734         });
28735     };
28736     BounceHandler.prototype._disable = function () {
28737         this._bounceSubscription.unsubscribe();
28738     };
28739     BounceHandler.prototype._getConfiguration = function (enable) {
28740         return {};
28741     };
28742     return BounceHandler;
28743 }(Component_1.HandlerBase));
28744 exports.BounceHandler = BounceHandler;
28745 exports.default = BounceHandler;
28746
28747 },{"../../Component":291,"rxjs/Observable":29}],342:[function(require,module,exports){
28748 "use strict";
28749 var __extends = (this && this.__extends) || (function () {
28750     var extendStatics = Object.setPrototypeOf ||
28751         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28752         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28753     return function (d, b) {
28754         extendStatics(d, b);
28755         function __() { this.constructor = d; }
28756         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28757     };
28758 })();
28759 Object.defineProperty(exports, "__esModule", { value: true });
28760 var Observable_1 = require("rxjs/Observable");
28761 var Component_1 = require("../../Component");
28762 /**
28763  * The `DoubleClickZoomHandler` allows the user to zoom the viewer image at a point by double clicking.
28764  *
28765  * @example
28766  * ```
28767  * var mouseComponent = viewer.getComponent("mouse");
28768  *
28769  * mouseComponent.doubleClickZoom.disable();
28770  * mouseComponent.doubleClickZoom.enable();
28771  *
28772  * var isEnabled = mouseComponent.doubleClickZoom.isEnabled;
28773  * ```
28774  */
28775 var DoubleClickZoomHandler = /** @class */ (function (_super) {
28776     __extends(DoubleClickZoomHandler, _super);
28777     function DoubleClickZoomHandler(component, container, navigator, viewportCoords) {
28778         var _this = _super.call(this, component, container, navigator) || this;
28779         _this._viewportCoords = viewportCoords;
28780         return _this;
28781     }
28782     DoubleClickZoomHandler.prototype._enable = function () {
28783         var _this = this;
28784         this._zoomSubscription = Observable_1.Observable
28785             .merge(this._container.mouseService
28786             .filtered$(this._component.name, this._container.mouseService.dblClick$), this._container.touchService.doubleTap$
28787             .map(function (e) {
28788             var touch = e.touches[0];
28789             return { clientX: touch.clientX, clientY: touch.clientY, shiftKey: e.shiftKey };
28790         }))
28791             .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
28792             .subscribe(function (_a) {
28793             var event = _a[0], render = _a[1], transform = _a[2];
28794             var element = _this._container.element;
28795             var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
28796             var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
28797             var reference = transform.projectBasic(unprojected.toArray());
28798             var delta = !!event.shiftKey ? -1 : 1;
28799             _this._navigator.stateService.zoomIn(delta, reference);
28800         });
28801     };
28802     DoubleClickZoomHandler.prototype._disable = function () {
28803         this._zoomSubscription.unsubscribe();
28804     };
28805     DoubleClickZoomHandler.prototype._getConfiguration = function (enable) {
28806         return { doubleClickZoom: enable };
28807     };
28808     return DoubleClickZoomHandler;
28809 }(Component_1.HandlerBase));
28810 exports.DoubleClickZoomHandler = DoubleClickZoomHandler;
28811 exports.default = DoubleClickZoomHandler;
28812
28813 },{"../../Component":291,"rxjs/Observable":29}],343:[function(require,module,exports){
28814 "use strict";
28815 /// <reference path="../../../typings/index.d.ts" />
28816 var __extends = (this && this.__extends) || (function () {
28817     var extendStatics = Object.setPrototypeOf ||
28818         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
28819         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
28820     return function (d, b) {
28821         extendStatics(d, b);
28822         function __() { this.constructor = d; }
28823         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
28824     };
28825 })();
28826 Object.defineProperty(exports, "__esModule", { value: true });
28827 var THREE = require("three");
28828 var Observable_1 = require("rxjs/Observable");
28829 require("rxjs/add/operator/concat");
28830 require("rxjs/add/operator/sample");
28831 require("rxjs/add/operator/takeWhile");
28832 var Component_1 = require("../../Component");
28833 /**
28834  * The `DragPanHandler` allows the user to pan the viewer image by clicking and dragging the cursor.
28835  *
28836  * @example
28837  * ```
28838  * var mouseComponent = viewer.getComponent("mouse");
28839  *
28840  * mouseComponent.dragPan.disable();
28841  * mouseComponent.dragPan.enable();
28842  *
28843  * var isEnabled = mouseComponent.dragPan.isEnabled;
28844  * ```
28845  */
28846 var DragPanHandler = /** @class */ (function (_super) {
28847     __extends(DragPanHandler, _super);
28848     function DragPanHandler(component, container, navigator, viewportCoords, spatial) {
28849         var _this = _super.call(this, component, container, navigator) || this;
28850         _this._spatial = spatial;
28851         _this._viewportCoords = viewportCoords;
28852         _this._basicRotationThreshold = 5e-2;
28853         _this._forceCoeff = 2e-1;
28854         return _this;
28855     }
28856     DragPanHandler.prototype._enable = function () {
28857         var _this = this;
28858         var draggingStarted$ = this._container.mouseService
28859             .filtered$(this._component.name, this._container.mouseService.mouseDragStart$)
28860             .map(function (event) {
28861             return true;
28862         })
28863             .share();
28864         var draggingStopped$ = this._container.mouseService
28865             .filtered$(this._component.name, this._container.mouseService.mouseDragEnd$)
28866             .map(function (event) {
28867             return false;
28868         })
28869             .share();
28870         this._activeMouseSubscription = Observable_1.Observable
28871             .merge(draggingStarted$, draggingStopped$)
28872             .subscribe(this._container.mouseService.activate$);
28873         this._preventDefaultSubscription = Observable_1.Observable
28874             .merge(draggingStarted$, draggingStopped$)
28875             .switchMap(function (dragging) {
28876             return dragging ?
28877                 _this._container.mouseService.documentMouseMove$ :
28878                 Observable_1.Observable.empty();
28879         })
28880             .merge(this._container.touchService.touchMove$)
28881             .subscribe(function (event) {
28882             event.preventDefault(); // prevent selection of content outside the viewer
28883         });
28884         var touchMovingStarted$ = this._container.touchService.singleTouchDragStart$
28885             .map(function (event) {
28886             return true;
28887         });
28888         var touchMovingStopped$ = this._container.touchService.singleTouchDragEnd$
28889             .map(function (event) {
28890             return false;
28891         });
28892         this._activeTouchSubscription = Observable_1.Observable
28893             .merge(touchMovingStarted$, touchMovingStopped$)
28894             .subscribe(this._container.touchService.activate$);
28895         var basicRotation$ = this._navigator.stateService.currentState$
28896             .map(function (frame) {
28897             return frame.state.currentNode.fullPano || frame.state.nodesAhead < 1;
28898         })
28899             .distinctUntilChanged()
28900             .switchMap(function (enable) {
28901             if (!enable) {
28902                 return Observable_1.Observable.empty();
28903             }
28904             var mouseDrag$ = _this._container.mouseService
28905                 .filtered$(_this._component.name, _this._container.mouseService.mouseDragStart$)
28906                 .switchMap(function (mouseDragStart) {
28907                 return Observable_1.Observable
28908                     .of(mouseDragStart)
28909                     .concat(_this._container.mouseService
28910                     .filtered$(_this._component.name, _this._container.mouseService.mouseDrag$))
28911                     .merge(_this._container.mouseService
28912                     .filtered$(_this._component.name, _this._container.mouseService.mouseDragEnd$)
28913                     .map(function (e) {
28914                     return null;
28915                 }))
28916                     .takeWhile(function (e) {
28917                     return !!e;
28918                 })
28919                     .startWith(null);
28920             })
28921                 .pairwise()
28922                 .filter(function (pair) {
28923                 return pair[0] != null && pair[1] != null;
28924             });
28925             var singleTouchDrag$ = Observable_1.Observable
28926                 .merge(_this._container.touchService.singleTouchDragStart$, _this._container.touchService.singleTouchDrag$, _this._container.touchService.singleTouchDragEnd$.map(function (t) { return null; }))
28927                 .map(function (event) {
28928                 return event != null && event.touches.length > 0 ?
28929                     event.touches[0] : null;
28930             })
28931                 .pairwise()
28932                 .filter(function (pair) {
28933                 return pair[0] != null && pair[1] != null;
28934             });
28935             return Observable_1.Observable
28936                 .merge(mouseDrag$, singleTouchDrag$);
28937         })
28938             .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, this._navigator.stateService.currentCamera$)
28939             .map(function (_a) {
28940             var events = _a[0], render = _a[1], transform = _a[2], c = _a[3];
28941             var camera = c.clone();
28942             var previousEvent = events[0];
28943             var event = events[1];
28944             var movementX = event.clientX - previousEvent.clientX;
28945             var movementY = event.clientY - previousEvent.clientY;
28946             var element = _this._container.element;
28947             var _b = _this._viewportCoords.canvasPosition(event, element), canvasX = _b[0], canvasY = _b[1];
28948             var currentDirection = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective)
28949                 .sub(render.perspective.position);
28950             var directionX = _this._viewportCoords.unprojectFromCanvas(canvasX - movementX, canvasY, element, render.perspective)
28951                 .sub(render.perspective.position);
28952             var directionY = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY - movementY, element, render.perspective)
28953                 .sub(render.perspective.position);
28954             var deltaPhi = (movementX > 0 ? 1 : -1) * directionX.angleTo(currentDirection);
28955             var deltaTheta = (movementY > 0 ? -1 : 1) * directionY.angleTo(currentDirection);
28956             var upQuaternion = new THREE.Quaternion().setFromUnitVectors(camera.up, new THREE.Vector3(0, 0, 1));
28957             var upQuaternionInverse = upQuaternion.clone().inverse();
28958             var offset = new THREE.Vector3();
28959             offset.copy(camera.lookat).sub(camera.position);
28960             offset.applyQuaternion(upQuaternion);
28961             var length = offset.length();
28962             var phi = Math.atan2(offset.y, offset.x);
28963             phi += deltaPhi;
28964             var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z);
28965             theta += deltaTheta;
28966             theta = Math.max(0.01, Math.min(Math.PI - 0.01, theta));
28967             offset.x = Math.sin(theta) * Math.cos(phi);
28968             offset.y = Math.sin(theta) * Math.sin(phi);
28969             offset.z = Math.cos(theta);
28970             offset.applyQuaternion(upQuaternionInverse);
28971             var lookat = new THREE.Vector3().copy(camera.position).add(offset.multiplyScalar(length));
28972             var basic = transform.projectBasic(lookat.toArray());
28973             var original = transform.projectBasic(camera.lookat.toArray());
28974             var x = basic[0] - original[0];
28975             var y = basic[1] - original[1];
28976             if (Math.abs(x) > 1) {
28977                 x = 0;
28978             }
28979             else if (x > 0.5) {
28980                 x = x - 1;
28981             }
28982             else if (x < -0.5) {
28983                 x = x + 1;
28984             }
28985             var rotationThreshold = _this._basicRotationThreshold;
28986             x = _this._spatial.clamp(x, -rotationThreshold, rotationThreshold);
28987             y = _this._spatial.clamp(y, -rotationThreshold, rotationThreshold);
28988             if (transform.fullPano) {
28989                 return [x, y];
28990             }
28991             var pixelDistances = _this._viewportCoords.getPixelDistances(_this._container.element, transform, render.perspective);
28992             var coeff = _this._forceCoeff;
28993             if (pixelDistances[0] > 0 && y < 0 && basic[1] < 0.5) {
28994                 y /= Math.max(1, coeff * pixelDistances[0]);
28995             }
28996             if (pixelDistances[1] > 0 && x > 0 && basic[0] > 0.5) {
28997                 x /= Math.max(1, coeff * pixelDistances[1]);
28998             }
28999             if (pixelDistances[2] > 0 && y > 0 && basic[1] > 0.5) {
29000                 y /= Math.max(1, coeff * pixelDistances[2]);
29001             }
29002             if (pixelDistances[3] > 0 && x < 0 && basic[0] < 0.5) {
29003                 x /= Math.max(1, coeff * pixelDistances[3]);
29004             }
29005             return [x, y];
29006         })
29007             .share();
29008         this._rotateBasicWithoutInertiaSubscription = basicRotation$
29009             .subscribe(function (basicRotation) {
29010             _this._navigator.stateService.rotateBasicWithoutInertia(basicRotation);
29011         });
29012         this._rotateBasicSubscription = basicRotation$
29013             .scan(function (rotationBuffer, rotation) {
29014             _this._drainBuffer(rotationBuffer);
29015             rotationBuffer.push([Date.now(), rotation]);
29016             return rotationBuffer;
29017         }, [])
29018             .sample(Observable_1.Observable
29019             .merge(this._container.mouseService.filtered$(this._component.name, this._container.mouseService.mouseDragEnd$), this._container.touchService.singleTouchDragEnd$))
29020             .map(function (rotationBuffer) {
29021             var drainedBuffer = _this._drainBuffer(rotationBuffer.slice());
29022             var basicRotation = [0, 0];
29023             for (var _i = 0, drainedBuffer_1 = drainedBuffer; _i < drainedBuffer_1.length; _i++) {
29024                 var rotation = drainedBuffer_1[_i];
29025                 basicRotation[0] += rotation[1][0];
29026                 basicRotation[1] += rotation[1][1];
29027             }
29028             var count = drainedBuffer.length;
29029             if (count > 0) {
29030                 basicRotation[0] /= count;
29031                 basicRotation[1] /= count;
29032             }
29033             return basicRotation;
29034         })
29035             .subscribe(function (basicRotation) {
29036             _this._navigator.stateService.rotateBasic(basicRotation);
29037         });
29038     };
29039     DragPanHandler.prototype._disable = function () {
29040         this._activeMouseSubscription.unsubscribe();
29041         this._activeTouchSubscription.unsubscribe();
29042         this._preventDefaultSubscription.unsubscribe();
29043         this._rotateBasicSubscription.unsubscribe();
29044         this._rotateBasicWithoutInertiaSubscription.unsubscribe();
29045         this._activeMouseSubscription = null;
29046         this._activeTouchSubscription = null;
29047         this._preventDefaultSubscription = null;
29048         this._rotateBasicSubscription = null;
29049     };
29050     DragPanHandler.prototype._getConfiguration = function (enable) {
29051         return { dragPan: enable };
29052     };
29053     DragPanHandler.prototype._drainBuffer = function (buffer) {
29054         var cutoff = 50;
29055         var now = Date.now();
29056         while (buffer.length > 0 && now - buffer[0][0] > cutoff) {
29057             buffer.shift();
29058         }
29059         return buffer;
29060     };
29061     return DragPanHandler;
29062 }(Component_1.HandlerBase));
29063 exports.DragPanHandler = DragPanHandler;
29064 exports.default = DragPanHandler;
29065
29066 },{"../../Component":291,"rxjs/Observable":29,"rxjs/add/operator/concat":56,"rxjs/add/operator/sample":77,"rxjs/add/operator/takeWhile":87,"three":241}],344:[function(require,module,exports){
29067 "use strict";
29068 var __extends = (this && this.__extends) || (function () {
29069     var extendStatics = Object.setPrototypeOf ||
29070         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
29071         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
29072     return function (d, b) {
29073         extendStatics(d, b);
29074         function __() { this.constructor = d; }
29075         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
29076     };
29077 })();
29078 Object.defineProperty(exports, "__esModule", { value: true });
29079 require("rxjs/add/observable/merge");
29080 require("rxjs/add/operator/filter");
29081 require("rxjs/add/operator/map");
29082 require("rxjs/add/operator/withLatestFrom");
29083 var Component_1 = require("../../Component");
29084 var Geo_1 = require("../../Geo");
29085 /**
29086  * @class MouseComponent
29087  *
29088  * @classdesc Component handling mouse and touch events for camera movement.
29089  *
29090  * To retrive and use the mouse component
29091  *
29092  * @example
29093  * ```
29094  * var viewer = new Mapillary.Viewer(
29095  *     "<element-id>",
29096  *     "<client-id>",
29097  *     "<my key>");
29098  *
29099  * var mouseComponent = viewer.getComponent("mouse");
29100  * ```
29101  */
29102 var MouseComponent = /** @class */ (function (_super) {
29103     __extends(MouseComponent, _super);
29104     function MouseComponent(name, container, navigator) {
29105         var _this = _super.call(this, name, container, navigator) || this;
29106         var spatial = new Geo_1.Spatial();
29107         var viewportCoords = new Geo_1.ViewportCoords();
29108         _this._bounceHandler = new Component_1.BounceHandler(_this, container, navigator, viewportCoords, spatial);
29109         _this._doubleClickZoomHandler = new Component_1.DoubleClickZoomHandler(_this, container, navigator, viewportCoords);
29110         _this._dragPanHandler = new Component_1.DragPanHandler(_this, container, navigator, viewportCoords, spatial);
29111         _this._scrollZoomHandler = new Component_1.ScrollZoomHandler(_this, container, navigator, viewportCoords);
29112         _this._touchZoomHandler = new Component_1.TouchZoomHandler(_this, container, navigator, viewportCoords);
29113         return _this;
29114     }
29115     Object.defineProperty(MouseComponent.prototype, "doubleClickZoom", {
29116         /**
29117          * Get double click zoom.
29118          *
29119          * @returns {DoubleClickZoomHandler} The double click zoom handler.
29120          */
29121         get: function () {
29122             return this._doubleClickZoomHandler;
29123         },
29124         enumerable: true,
29125         configurable: true
29126     });
29127     Object.defineProperty(MouseComponent.prototype, "dragPan", {
29128         /**
29129          * Get drag pan.
29130          *
29131          * @returns {DragPanHandler} The drag pan handler.
29132          */
29133         get: function () {
29134             return this._dragPanHandler;
29135         },
29136         enumerable: true,
29137         configurable: true
29138     });
29139     Object.defineProperty(MouseComponent.prototype, "scrollZoom", {
29140         /**
29141          * Get scroll zoom.
29142          *
29143          * @returns {ScrollZoomHandler} The scroll zoom handler.
29144          */
29145         get: function () {
29146             return this._scrollZoomHandler;
29147         },
29148         enumerable: true,
29149         configurable: true
29150     });
29151     Object.defineProperty(MouseComponent.prototype, "touchZoom", {
29152         /**
29153          * Get touch zoom.
29154          *
29155          * @returns {TouchZoomHandler} The touch zoom handler.
29156          */
29157         get: function () {
29158             return this._touchZoomHandler;
29159         },
29160         enumerable: true,
29161         configurable: true
29162     });
29163     MouseComponent.prototype._activate = function () {
29164         var _this = this;
29165         this._bounceHandler.enable();
29166         this._configurationSubscription = this._configuration$
29167             .subscribe(function (configuration) {
29168             if (configuration.doubleClickZoom) {
29169                 _this._doubleClickZoomHandler.enable();
29170             }
29171             else {
29172                 _this._doubleClickZoomHandler.disable();
29173             }
29174             if (configuration.dragPan) {
29175                 _this._dragPanHandler.enable();
29176             }
29177             else {
29178                 _this._dragPanHandler.disable();
29179             }
29180             if (configuration.scrollZoom) {
29181                 _this._scrollZoomHandler.enable();
29182             }
29183             else {
29184                 _this._scrollZoomHandler.disable();
29185             }
29186             if (configuration.touchZoom) {
29187                 _this._touchZoomHandler.enable();
29188             }
29189             else {
29190                 _this._touchZoomHandler.disable();
29191             }
29192         });
29193         this._container.mouseService.claimMouse(this._name, 0);
29194     };
29195     MouseComponent.prototype._deactivate = function () {
29196         this._container.mouseService.unclaimMouse(this._name);
29197         this._configurationSubscription.unsubscribe();
29198         this._bounceHandler.disable();
29199         this._doubleClickZoomHandler.disable();
29200         this._dragPanHandler.disable();
29201         this._scrollZoomHandler.disable();
29202         this._touchZoomHandler.disable();
29203     };
29204     MouseComponent.prototype._getDefaultConfiguration = function () {
29205         return { doubleClickZoom: false, dragPan: true, scrollZoom: true, touchZoom: true };
29206     };
29207     /** @inheritdoc */
29208     MouseComponent.componentName = "mouse";
29209     return MouseComponent;
29210 }(Component_1.Component));
29211 exports.MouseComponent = MouseComponent;
29212 Component_1.ComponentService.register(MouseComponent);
29213 exports.default = MouseComponent;
29214
29215 },{"../../Component":291,"../../Geo":294,"rxjs/add/observable/merge":45,"rxjs/add/operator/filter":63,"rxjs/add/operator/map":67,"rxjs/add/operator/withLatestFrom":90}],345:[function(require,module,exports){
29216 "use strict";
29217 var __extends = (this && this.__extends) || (function () {
29218     var extendStatics = Object.setPrototypeOf ||
29219         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
29220         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
29221     return function (d, b) {
29222         extendStatics(d, b);
29223         function __() { this.constructor = d; }
29224         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
29225     };
29226 })();
29227 Object.defineProperty(exports, "__esModule", { value: true });
29228 var Component_1 = require("../../Component");
29229 /**
29230  * The `ScrollZoomHandler` allows the user to zoom the viewer image by scrolling.
29231  *
29232  * @example
29233  * ```
29234  * var mouseComponent = viewer.getComponent("mouse");
29235  *
29236  * mouseComponent.scrollZoom.disable();
29237  * mouseComponent.scrollZoom.enable();
29238  *
29239  * var isEnabled = mouseComponent.scrollZoom.isEnabled;
29240  * ```
29241  */
29242 var ScrollZoomHandler = /** @class */ (function (_super) {
29243     __extends(ScrollZoomHandler, _super);
29244     function ScrollZoomHandler(component, container, navigator, viewportCoords) {
29245         var _this = _super.call(this, component, container, navigator) || this;
29246         _this._viewportCoords = viewportCoords;
29247         return _this;
29248     }
29249     ScrollZoomHandler.prototype._enable = function () {
29250         var _this = this;
29251         this._container.mouseService.claimWheel(this._component.name, 0);
29252         this._preventDefaultSubscription = this._container.mouseService.mouseWheel$
29253             .subscribe(function (event) {
29254             event.preventDefault();
29255         });
29256         this._zoomSubscription = this._container.mouseService
29257             .filteredWheel$(this._component.name, this._container.mouseService.mouseWheel$)
29258             .withLatestFrom(this._navigator.stateService.currentState$, function (w, f) {
29259             return [w, f];
29260         })
29261             .filter(function (args) {
29262             var state = args[1].state;
29263             return state.currentNode.fullPano || state.nodesAhead < 1;
29264         })
29265             .map(function (args) {
29266             return args[0];
29267         })
29268             .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$, function (w, r, t) {
29269             return [w, r, t];
29270         })
29271             .subscribe(function (args) {
29272             var event = args[0];
29273             var render = args[1];
29274             var transform = args[2];
29275             var element = _this._container.element;
29276             var _a = _this._viewportCoords.canvasPosition(event, element), canvasX = _a[0], canvasY = _a[1];
29277             var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
29278             var reference = transform.projectBasic(unprojected.toArray());
29279             var deltaY = event.deltaY;
29280             if (event.deltaMode === 1) {
29281                 deltaY = 40 * deltaY;
29282             }
29283             else if (event.deltaMode === 2) {
29284                 deltaY = 800 * deltaY;
29285             }
29286             var canvasSize = _this._viewportCoords.containerToCanvas(element);
29287             var zoom = -3 * deltaY / canvasSize[1];
29288             _this._navigator.stateService.zoomIn(zoom, reference);
29289         });
29290     };
29291     ScrollZoomHandler.prototype._disable = function () {
29292         this._container.mouseService.unclaimWheel(this._component.name);
29293         this._preventDefaultSubscription.unsubscribe();
29294         this._zoomSubscription.unsubscribe();
29295         this._preventDefaultSubscription = null;
29296         this._zoomSubscription = null;
29297     };
29298     ScrollZoomHandler.prototype._getConfiguration = function (enable) {
29299         return { scrollZoom: enable };
29300     };
29301     return ScrollZoomHandler;
29302 }(Component_1.HandlerBase));
29303 exports.ScrollZoomHandler = ScrollZoomHandler;
29304 exports.default = ScrollZoomHandler;
29305
29306 },{"../../Component":291}],346:[function(require,module,exports){
29307 "use strict";
29308 /// <reference path="../../../typings/index.d.ts" />
29309 var __extends = (this && this.__extends) || (function () {
29310     var extendStatics = Object.setPrototypeOf ||
29311         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
29312         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
29313     return function (d, b) {
29314         extendStatics(d, b);
29315         function __() { this.constructor = d; }
29316         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
29317     };
29318 })();
29319 Object.defineProperty(exports, "__esModule", { value: true });
29320 var Observable_1 = require("rxjs/Observable");
29321 var Component_1 = require("../../Component");
29322 /**
29323  * The `TouchZoomHandler` allows the user to zoom the viewer image by pinching on a touchscreen.
29324  *
29325  * @example
29326  * ```
29327  * var mouseComponent = viewer.getComponent("mouse");
29328  *
29329  * mouseComponent.touchZoom.disable();
29330  * mouseComponent.touchZoom.enable();
29331  *
29332  * var isEnabled = mouseComponent.touchZoom.isEnabled;
29333  * ```
29334  */
29335 var TouchZoomHandler = /** @class */ (function (_super) {
29336     __extends(TouchZoomHandler, _super);
29337     function TouchZoomHandler(component, container, navigator, viewportCoords) {
29338         var _this = _super.call(this, component, container, navigator) || this;
29339         _this._viewportCoords = viewportCoords;
29340         return _this;
29341     }
29342     TouchZoomHandler.prototype._enable = function () {
29343         var _this = this;
29344         this._preventDefaultSubscription = this._container.touchService.pinch$
29345             .subscribe(function (pinch) {
29346             pinch.originalEvent.preventDefault();
29347         });
29348         var pinchStarted$ = this._container.touchService.pinchStart$
29349             .map(function (event) {
29350             return true;
29351         });
29352         var pinchStopped$ = this._container.touchService.pinchEnd$
29353             .map(function (event) {
29354             return false;
29355         });
29356         this._activeSubscription = Observable_1.Observable
29357             .merge(pinchStarted$, pinchStopped$)
29358             .subscribe(this._container.touchService.activate$);
29359         this._zoomSubscription = this._container.touchService.pinch$
29360             .withLatestFrom(this._navigator.stateService.currentState$)
29361             .filter(function (args) {
29362             var state = args[1].state;
29363             return state.currentNode.fullPano || state.nodesAhead < 1;
29364         })
29365             .map(function (args) {
29366             return args[0];
29367         })
29368             .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
29369             .subscribe(function (_a) {
29370             var pinch = _a[0], render = _a[1], transform = _a[2];
29371             var element = _this._container.element;
29372             var _b = _this._viewportCoords.canvasPosition(pinch, element), canvasX = _b[0], canvasY = _b[1];
29373             var unprojected = _this._viewportCoords.unprojectFromCanvas(canvasX, canvasY, element, render.perspective);
29374             var reference = transform.projectBasic(unprojected.toArray());
29375             var _c = _this._viewportCoords.containerToCanvas(element), canvasWidth = _c[0], canvasHeight = _c[1];
29376             var zoom = 3 * pinch.distanceChange / Math.min(canvasWidth, canvasHeight);
29377             _this._navigator.stateService.zoomIn(zoom, reference);
29378         });
29379     };
29380     TouchZoomHandler.prototype._disable = function () {
29381         this._activeSubscription.unsubscribe();
29382         this._preventDefaultSubscription.unsubscribe();
29383         this._zoomSubscription.unsubscribe();
29384         this._preventDefaultSubscription = null;
29385         this._zoomSubscription = null;
29386     };
29387     TouchZoomHandler.prototype._getConfiguration = function (enable) {
29388         return { touchZoom: enable };
29389     };
29390     return TouchZoomHandler;
29391 }(Component_1.HandlerBase));
29392 exports.TouchZoomHandler = TouchZoomHandler;
29393 exports.default = TouchZoomHandler;
29394
29395 },{"../../Component":291,"rxjs/Observable":29}],347:[function(require,module,exports){
29396 "use strict";
29397 Object.defineProperty(exports, "__esModule", { value: true });
29398 var Popup_1 = require("./popup/Popup");
29399 exports.Popup = Popup_1.Popup;
29400 var PopupComponent_1 = require("./PopupComponent");
29401 exports.PopupComponent = PopupComponent_1.PopupComponent;
29402
29403 },{"./PopupComponent":348,"./popup/Popup":349}],348:[function(require,module,exports){
29404 "use strict";
29405 var __extends = (this && this.__extends) || (function () {
29406     var extendStatics = Object.setPrototypeOf ||
29407         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
29408         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
29409     return function (d, b) {
29410         extendStatics(d, b);
29411         function __() { this.constructor = d; }
29412         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
29413     };
29414 })();
29415 Object.defineProperty(exports, "__esModule", { value: true });
29416 var Observable_1 = require("rxjs/Observable");
29417 var Subject_1 = require("rxjs/Subject");
29418 var Component_1 = require("../../Component");
29419 var Utils_1 = require("../../Utils");
29420 /**
29421  * @class PopupComponent
29422  *
29423  * @classdesc Component for showing HTML popup objects.
29424  *
29425  * The `add` method is used for adding new popups. Popups are removed by reference.
29426  *
29427  * It is not possible to update popups in the set by updating any properties
29428  * directly on the popup object. Popups need to be replaced by
29429  * removing them and creating new ones with relevant changed properties and
29430  * adding those instead.
29431  *
29432  * Popups are only relevant to a single image because they are based on
29433  * 2D basic image coordinates. Popups related to a certain image should
29434  * be removed when the viewer is moved to another node.
29435  *
29436  * To retrive and use the popup component
29437  *
29438  * @example
29439  * ```
29440  * var viewer = new Mapillary.Viewer(
29441  *     "<element-id>",
29442  *     "<client-id>",
29443  *     "<my key>",
29444  *     { component: { popup: true } });
29445  *
29446  * var popupComponent = viewer.getComponent("popup");
29447  * ```
29448  */
29449 var PopupComponent = /** @class */ (function (_super) {
29450     __extends(PopupComponent, _super);
29451     function PopupComponent(name, container, navigator, dom) {
29452         var _this = _super.call(this, name, container, navigator) || this;
29453         _this._dom = !!dom ? dom : new Utils_1.DOM();
29454         _this._popups = [];
29455         _this._added$ = new Subject_1.Subject();
29456         _this._popups$ = new Subject_1.Subject();
29457         return _this;
29458     }
29459     /**
29460      * Add popups to the popups set.
29461      *
29462      * @description Adding a new popup never replaces an old one
29463      * because they are stored by reference. Adding an already
29464      * existing popup has no effect.
29465      *
29466      * @param {Array<Popup>} popups - Popups to add.
29467      *
29468      * @example ```popupComponent.add([popup1, popup2]);```
29469      */
29470     PopupComponent.prototype.add = function (popups) {
29471         for (var _i = 0, popups_1 = popups; _i < popups_1.length; _i++) {
29472             var popup = popups_1[_i];
29473             if (this._popups.indexOf(popup) !== -1) {
29474                 continue;
29475             }
29476             this._popups.push(popup);
29477             if (this._activated) {
29478                 popup.setParentContainer(this._popupContainer);
29479             }
29480         }
29481         this._added$.next(popups);
29482         this._popups$.next(this._popups);
29483     };
29484     /**
29485      * Returns an array of all popups.
29486      *
29487      * @example ```var popups = popupComponent.getAll();```
29488      */
29489     PopupComponent.prototype.getAll = function () {
29490         return this._popups.slice();
29491     };
29492     /**
29493      * Remove popups based on reference from the popup set.
29494      *
29495      * @param {Array<Popup>} popups - Popups to remove.
29496      *
29497      * @example ```popupComponent.remove([popup1, popup2]);```
29498      */
29499     PopupComponent.prototype.remove = function (popups) {
29500         for (var _i = 0, popups_2 = popups; _i < popups_2.length; _i++) {
29501             var popup = popups_2[_i];
29502             this._remove(popup);
29503         }
29504         this._popups$.next(this._popups);
29505     };
29506     /**
29507      * Remove all popups from the popup set.
29508      *
29509      * @example ```popupComponent.removeAll();```
29510      */
29511     PopupComponent.prototype.removeAll = function () {
29512         for (var _i = 0, _a = this._popups.slice(); _i < _a.length; _i++) {
29513             var popup = _a[_i];
29514             this._remove(popup);
29515         }
29516         this._popups$.next(this._popups);
29517     };
29518     PopupComponent.prototype._activate = function () {
29519         var _this = this;
29520         this._popupContainer = this._dom.createElement("div", "mapillary-js-popup-container", this._container.element);
29521         for (var _i = 0, _a = this._popups; _i < _a.length; _i++) {
29522             var popup = _a[_i];
29523             popup.setParentContainer(this._popupContainer);
29524         }
29525         this._updateAllSubscription = Observable_1.Observable
29526             .combineLatest(this._container.renderService.renderCamera$, this._container.renderService.size$, this._navigator.stateService.currentTransform$)
29527             .subscribe(function (_a) {
29528             var renderCamera = _a[0], size = _a[1], transform = _a[2];
29529             for (var _i = 0, _b = _this._popups; _i < _b.length; _i++) {
29530                 var popup = _b[_i];
29531                 popup.update(renderCamera, size, transform);
29532             }
29533         });
29534         var changed$ = this._popups$
29535             .startWith(this._popups)
29536             .switchMap(function (popups) {
29537             return Observable_1.Observable
29538                 .from(popups)
29539                 .mergeMap(function (popup) {
29540                 return popup.changed$;
29541             });
29542         })
29543             .map(function (popup) {
29544             return [popup];
29545         });
29546         this._updateAddedChangedSubscription = this._added$
29547             .merge(changed$)
29548             .withLatestFrom(this._container.renderService.renderCamera$, this._container.renderService.size$, this._navigator.stateService.currentTransform$)
29549             .subscribe(function (_a) {
29550             var popups = _a[0], renderCamera = _a[1], size = _a[2], transform = _a[3];
29551             for (var _i = 0, popups_3 = popups; _i < popups_3.length; _i++) {
29552                 var popup = popups_3[_i];
29553                 popup.update(renderCamera, size, transform);
29554             }
29555         });
29556     };
29557     PopupComponent.prototype._deactivate = function () {
29558         this._updateAllSubscription.unsubscribe();
29559         this._updateAddedChangedSubscription.unsubscribe();
29560         for (var _i = 0, _a = this._popups; _i < _a.length; _i++) {
29561             var popup = _a[_i];
29562             popup.remove();
29563         }
29564         this._container.element.removeChild(this._popupContainer);
29565         delete this._popupContainer;
29566     };
29567     PopupComponent.prototype._getDefaultConfiguration = function () {
29568         return {};
29569     };
29570     PopupComponent.prototype._remove = function (popup) {
29571         var index = this._popups.indexOf(popup);
29572         if (index === -1) {
29573             return;
29574         }
29575         var removed = this._popups.splice(index, 1)[0];
29576         if (this._activated) {
29577             removed.remove();
29578         }
29579     };
29580     PopupComponent.componentName = "popup";
29581     return PopupComponent;
29582 }(Component_1.Component));
29583 exports.PopupComponent = PopupComponent;
29584 Component_1.ComponentService.register(PopupComponent);
29585 exports.default = PopupComponent;
29586
29587 },{"../../Component":291,"../../Utils":301,"rxjs/Observable":29,"rxjs/Subject":34}],349:[function(require,module,exports){
29588 "use strict";
29589 /// <reference path="../../../../typings/index.d.ts" />
29590 Object.defineProperty(exports, "__esModule", { value: true });
29591 var Subject_1 = require("rxjs/Subject");
29592 var Geo_1 = require("../../../Geo");
29593 var Utils_1 = require("../../../Utils");
29594 var Viewer_1 = require("../../../Viewer");
29595 /**
29596  * @class Popup
29597  *
29598  * @classdesc Popup instance for rendering custom HTML content
29599  * on top of images. Popups are based on 2D basic image coordinates
29600  * (see the {@link Viewer} class documentation for more information about coordinate
29601  * systems) and a certain popup is therefore only relevant to a single image.
29602  * Popups related to a certain image should be removed when moving
29603  * to another image.
29604  *
29605  * A popup must have both its content and its point or rect set to be
29606  * rendered. Popup options can not be updated after creation but the
29607  * basic point or rect as well as its content can be changed by calling
29608  * the appropriate methods.
29609  *
29610  * To create and add one `Popup` with default configuration
29611  * (tooltip visuals and automatic float) and one with specific options
29612  * use
29613  *
29614  * @example
29615  * ```
29616  * var defaultSpan = document.createElement('span');
29617  * defaultSpan.innerHTML = 'hello default';
29618  *
29619  * var defaultPopup = new Mapillary.PopupComponent.Popup();
29620  * defaultPopup.setDOMContent(defaultSpan);
29621  * defaultPopup.setBasicPoint([0.3, 0.3]);
29622  *
29623  * var cleanSpan = document.createElement('span');
29624  * cleanSpan.innerHTML = 'hello clean';
29625  *
29626  * var cleanPopup = new Mapillary.PopupComponent.Popup({
29627  *     clean: true,
29628  *     float: Mapillary.Alignment.Top,
29629  *     offset: 10,
29630  *     opacity: 0.7,
29631  * });
29632  *
29633  * cleanPopup.setDOMContent(cleanSpan);
29634  * cleanPopup.setBasicPoint([0.6, 0.6]);
29635  *
29636  * popupComponent.add([defaultPopup, cleanPopup]);
29637  * ```
29638  *
29639  * @description Implementation of API methods and API documentation inspired
29640  * by/used from https://github.com/mapbox/mapbox-gl-js/blob/v0.38.0/src/ui/popup.js
29641  */
29642 var Popup = /** @class */ (function () {
29643     function Popup(options, viewportCoords, dom) {
29644         this._options = {};
29645         if (!!options) {
29646             this._options.capturePointer = options.capturePointer == null ? true : options.capturePointer;
29647             this._options.clean = options.clean;
29648             this._options.float = options.float;
29649             this._options.offset = options.offset;
29650             this._options.opacity = options.opacity;
29651             this._options.position = options.position;
29652         }
29653         this._dom = !!dom ? dom : new Utils_1.DOM();
29654         this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
29655         this._notifyChanged$ = new Subject_1.Subject();
29656     }
29657     Object.defineProperty(Popup.prototype, "changed$", {
29658         /**
29659          * @ignore
29660          *
29661          * @description Internal observable used by the component to
29662          * render the popup when its position or content has changed.
29663          */
29664         get: function () {
29665             return this._notifyChanged$;
29666         },
29667         enumerable: true,
29668         configurable: true
29669     });
29670     /**
29671      * @ignore
29672      *
29673      * @description Internal method used by the component to
29674      * remove all references to the popup.
29675      */
29676     Popup.prototype.remove = function () {
29677         if (this._content && this._content.parentNode) {
29678             this._content.parentNode.removeChild(this._content);
29679         }
29680         if (this._container) {
29681             this._container.parentNode.removeChild(this._container);
29682             delete this._container;
29683         }
29684         if (this._parentContainer) {
29685             delete this._parentContainer;
29686         }
29687     };
29688     /**
29689      * Sets a 2D basic image coordinates point to the popup's anchor, and
29690      * moves the popup to it.
29691      *
29692      * @description Overwrites any previously set point or rect.
29693      *
29694      * @param {Array<number>} basicPoint - Point in 2D basic image coordinates.
29695      *
29696      * @example
29697      * ```
29698      * var popup = new Mapillary.PopupComponent.Popup();
29699      * popup.setText('hello image');
29700      * popup.setBasicPoint([0.3, 0.3]);
29701      *
29702      * popupComponent.add([popup]);
29703      * ```
29704      */
29705     Popup.prototype.setBasicPoint = function (basicPoint) {
29706         this._point = basicPoint.slice();
29707         this._rect = null;
29708         this._notifyChanged$.next(this);
29709     };
29710     /**
29711      * Sets a 2D basic image coordinates rect to the popup's anchor, and
29712      * moves the popup to it.
29713      *
29714      * @description Overwrites any previously set point or rect.
29715      *
29716      * @param {Array<number>} basicRect - Rect in 2D basic image
29717      * coordinates ([topLeftX, topLeftY, bottomRightX, bottomRightY]) .
29718      *
29719      * @example
29720      * ```
29721      * var popup = new Mapillary.PopupComponent.Popup();
29722      * popup.setText('hello image');
29723      * popup.setBasicRect([0.3, 0.3, 0.5, 0.6]);
29724      *
29725      * popupComponent.add([popup]);
29726      * ```
29727      */
29728     Popup.prototype.setBasicRect = function (basicRect) {
29729         this._rect = basicRect.slice();
29730         this._point = null;
29731         this._notifyChanged$.next(this);
29732     };
29733     /**
29734      * Sets the popup's content to the element provided as a DOM node.
29735      *
29736      * @param {Node} htmlNode - A DOM node to be used as content for the popup.
29737      *
29738      * @example
29739      * ```
29740      * var div = document.createElement('div');
29741      * div.innerHTML = 'hello image';
29742      *
29743      * var popup = new Mapillary.PopupComponent.Popup();
29744      * popup.setDOMContent(div);
29745      * popup.setBasicPoint([0.3, 0.3]);
29746      *
29747      * popupComponent.add([popup]);
29748      * ```
29749      */
29750     Popup.prototype.setDOMContent = function (htmlNode) {
29751         if (this._content && this._content.parentNode) {
29752             this._content.parentNode.removeChild(this._content);
29753         }
29754         var className = "mapillaryjs-popup-content" +
29755             (this._options.clean === true ? "-clean" : "") +
29756             (this._options.capturePointer === true ? " mapillaryjs-popup-capture-pointer" : "");
29757         this._content = this._dom.createElement("div", className, this._container);
29758         this._content.appendChild(htmlNode);
29759         this._notifyChanged$.next(this);
29760     };
29761     /**
29762      * Sets the popup's content to the HTML provided as a string.
29763      *
29764      * @description This method does not perform HTML filtering or sanitization,
29765      * and must be used only with trusted content. Consider Popup#setText if the
29766      * content is an untrusted text string.
29767      *
29768      * @param {string} html - A string representing HTML content for the popup.
29769      *
29770      * @example
29771      * ```
29772      * var popup = new Mapillary.PopupComponent.Popup();
29773      * popup.setHTML('<div>hello image</div>');
29774      * popup.setBasicPoint([0.3, 0.3]);
29775      *
29776      * popupComponent.add([popup]);
29777      * ```
29778      */
29779     Popup.prototype.setHTML = function (html) {
29780         var frag = this._dom.document.createDocumentFragment();
29781         var temp = this._dom.createElement("body");
29782         var child;
29783         temp.innerHTML = html;
29784         while (true) {
29785             child = temp.firstChild;
29786             if (!child) {
29787                 break;
29788             }
29789             frag.appendChild(child);
29790         }
29791         this.setDOMContent(frag);
29792     };
29793     /**
29794      * Sets the popup's content to a string of text.
29795      *
29796      * @description This function creates a Text node in the DOM, so it cannot insert raw HTML.
29797      * Use this method for security against XSS if the popup content is user-provided.
29798      *
29799      * @param {string} text - Textual content for the popup.
29800      *
29801      * @example
29802      * ```
29803      * var popup = new Mapillary.PopupComponent.Popup();
29804      * popup.setText('hello image');
29805      * popup.setBasicPoint([0.3, 0.3]);
29806      *
29807      * popupComponent.add([popup]);
29808      * ```
29809      */
29810     Popup.prototype.setText = function (text) {
29811         this.setDOMContent(this._dom.document.createTextNode(text));
29812     };
29813     /**
29814      * @ignore
29815      *
29816      * @description Internal method for attaching the popup to
29817      * its parent container so that it is rendered in the DOM tree.
29818      */
29819     Popup.prototype.setParentContainer = function (parentContainer) {
29820         this._parentContainer = parentContainer;
29821     };
29822     /**
29823      * @ignore
29824      *
29825      * @description Internal method for updating the rendered
29826      * position of the popup called by the popup component.
29827      */
29828     Popup.prototype.update = function (renderCamera, size, transform) {
29829         if (!this._parentContainer || !this._content) {
29830             return;
29831         }
29832         if (!this._point && !this._rect) {
29833             return;
29834         }
29835         if (!this._container) {
29836             this._container = this._dom.createElement("div", "mapillaryjs-popup", this._parentContainer);
29837             var showTip = this._options.clean !== true &&
29838                 this._options.float !== Viewer_1.Alignment.Center;
29839             if (showTip) {
29840                 var tipClassName = "mapillaryjs-popup-tip" +
29841                     (this._options.capturePointer === true ? " mapillaryjs-popup-capture-pointer" : "");
29842                 this._tip = this._dom.createElement("div", tipClassName, this._container);
29843                 this._dom.createElement("div", "mapillaryjs-popup-tip-inner", this._tip);
29844             }
29845             this._container.appendChild(this._content);
29846             this._parentContainer.appendChild(this._container);
29847             if (this._options.opacity != null) {
29848                 this._container.style.opacity = this._options.opacity.toString();
29849             }
29850         }
29851         var pointPixel = null;
29852         var position = this._alignmentToPopupAligment(this._options.position);
29853         var float = this._alignmentToPopupAligment(this._options.float);
29854         var classList = this._container.classList;
29855         if (this._point != null) {
29856             pointPixel =
29857                 this._viewportCoords.basicToCanvasSafe(this._point[0], this._point[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective);
29858         }
29859         else {
29860             var alignments = ["center", "top", "bottom", "left", "right", "top-left", "top-right", "bottom-left", "bottom-right"];
29861             var appliedPosition = null;
29862             for (var _i = 0, alignments_1 = alignments; _i < alignments_1.length; _i++) {
29863                 var alignment = alignments_1[_i];
29864                 if (classList.contains("mapillaryjs-popup-float-" + alignment)) {
29865                     appliedPosition = alignment;
29866                     break;
29867                 }
29868             }
29869             _a = this._rectToPixel(this._rect, position, appliedPosition, renderCamera, size, transform), pointPixel = _a[0], position = _a[1];
29870             if (!float) {
29871                 float = position;
29872             }
29873         }
29874         if (pointPixel == null) {
29875             this._container.style.visibility = "hidden";
29876             return;
29877         }
29878         this._container.style.visibility = "visible";
29879         if (!float) {
29880             var width = this._container.offsetWidth;
29881             var height = this._container.offsetHeight;
29882             var floats = this._pixelToFloats(pointPixel, size, width, height);
29883             float = floats.length === 0 ? "top" : floats.join("-");
29884         }
29885         var offset = this._normalizeOffset(this._options.offset);
29886         pointPixel = [pointPixel[0] + offset[float][0], pointPixel[1] + offset[float][1]];
29887         pointPixel = [Math.round(pointPixel[0]), Math.round(pointPixel[1])];
29888         var floatTranslate = {
29889             "bottom": "translate(-50%,0)",
29890             "bottom-left": "translate(-100%,0)",
29891             "bottom-right": "translate(0,0)",
29892             "center": "translate(-50%,-50%)",
29893             "left": "translate(-100%,-50%)",
29894             "right": "translate(0,-50%)",
29895             "top": "translate(-50%,-100%)",
29896             "top-left": "translate(-100%,-100%)",
29897             "top-right": "translate(0,-100%)",
29898         };
29899         for (var key in floatTranslate) {
29900             if (!floatTranslate.hasOwnProperty(key)) {
29901                 continue;
29902             }
29903             classList.remove("mapillaryjs-popup-float-" + key);
29904         }
29905         classList.add("mapillaryjs-popup-float-" + float);
29906         this._container.style.transform = floatTranslate[float] + " translate(" + pointPixel[0] + "px," + pointPixel[1] + "px)";
29907         var _a;
29908     };
29909     Popup.prototype._rectToPixel = function (rect, position, appliedPosition, renderCamera, size, transform) {
29910         if (!position) {
29911             var width = this._container.offsetWidth;
29912             var height = this._container.offsetHeight;
29913             var floatOffsets = {
29914                 "bottom": [0, height / 2],
29915                 "bottom-left": [-width / 2, height / 2],
29916                 "bottom-right": [width / 2, height / 2],
29917                 "left": [-width / 2, 0],
29918                 "right": [width / 2, 0],
29919                 "top": [0, -height / 2],
29920                 "top-left": [-width / 2, -height / 2],
29921                 "top-right": [width / 2, -height / 2],
29922             };
29923             var automaticPositions = ["top", "bottom", "left", "right"];
29924             var largestVisibleArea = [0, null, null];
29925             for (var _i = 0, automaticPositions_1 = automaticPositions; _i < automaticPositions_1.length; _i++) {
29926                 var automaticPosition = automaticPositions_1[_i];
29927                 var autoPointBasic = this._pointFromRectPosition(rect, automaticPosition);
29928                 var autoPointPixel = this._viewportCoords.basicToCanvasSafe(autoPointBasic[0], autoPointBasic[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective);
29929                 if (autoPointPixel == null) {
29930                     continue;
29931                 }
29932                 var floatOffset = floatOffsets[automaticPosition];
29933                 var offsetedPosition = [autoPointPixel[0] + floatOffset[0], autoPointPixel[1] + floatOffset[1]];
29934                 var staticCoeff = appliedPosition != null && appliedPosition === automaticPosition ? 1 : 0.7;
29935                 var floats = this._pixelToFloats(offsetedPosition, size, width / staticCoeff, height / (2 * staticCoeff));
29936                 if (floats.length === 0 &&
29937                     autoPointPixel[0] > 0 &&
29938                     autoPointPixel[0] < size.width &&
29939                     autoPointPixel[1] > 0 &&
29940                     autoPointPixel[1] < size.height) {
29941                     return [autoPointPixel, automaticPosition];
29942                 }
29943                 var minX = Math.max(offsetedPosition[0] - width / 2, 0);
29944                 var maxX = Math.min(offsetedPosition[0] + width / 2, size.width);
29945                 var minY = Math.max(offsetedPosition[1] - height / 2, 0);
29946                 var maxY = Math.min(offsetedPosition[1] + height / 2, size.height);
29947                 var visibleX = Math.max(0, maxX - minX);
29948                 var visibleY = Math.max(0, maxY - minY);
29949                 var visibleArea = staticCoeff * visibleX * visibleY;
29950                 if (visibleArea > largestVisibleArea[0]) {
29951                     largestVisibleArea[0] = visibleArea;
29952                     largestVisibleArea[1] = autoPointPixel;
29953                     largestVisibleArea[2] = automaticPosition;
29954                 }
29955             }
29956             if (largestVisibleArea[0] > 0) {
29957                 return [largestVisibleArea[1], largestVisibleArea[2]];
29958             }
29959         }
29960         var pointBasic = this._pointFromRectPosition(rect, position);
29961         var pointPixel = this._viewportCoords.basicToCanvasSafe(pointBasic[0], pointBasic[1], { offsetHeight: size.height, offsetWidth: size.width }, transform, renderCamera.perspective);
29962         return [pointPixel, position != null ? position : "top"];
29963     };
29964     Popup.prototype._alignmentToPopupAligment = function (float) {
29965         switch (float) {
29966             case Viewer_1.Alignment.Bottom:
29967                 return "bottom";
29968             case Viewer_1.Alignment.BottomLeft:
29969                 return "bottom-left";
29970             case Viewer_1.Alignment.BottomRight:
29971                 return "bottom-right";
29972             case Viewer_1.Alignment.Center:
29973                 return "center";
29974             case Viewer_1.Alignment.Left:
29975                 return "left";
29976             case Viewer_1.Alignment.Right:
29977                 return "right";
29978             case Viewer_1.Alignment.Top:
29979                 return "top";
29980             case Viewer_1.Alignment.TopLeft:
29981                 return "top-left";
29982             case Viewer_1.Alignment.TopRight:
29983                 return "top-right";
29984             default:
29985                 return null;
29986         }
29987     };
29988     Popup.prototype._normalizeOffset = function (offset) {
29989         if (offset == null) {
29990             return this._normalizeOffset(0);
29991         }
29992         if (typeof offset === "number") {
29993             // input specifies a radius
29994             var sideOffset = offset;
29995             var sign = sideOffset >= 0 ? 1 : -1;
29996             var cornerOffset = sign * Math.round(Math.sqrt(0.5 * Math.pow(sideOffset, 2)));
29997             return {
29998                 "bottom": [0, sideOffset],
29999                 "bottom-left": [-cornerOffset, cornerOffset],
30000                 "bottom-right": [cornerOffset, cornerOffset],
30001                 "center": [0, 0],
30002                 "left": [-sideOffset, 0],
30003                 "right": [sideOffset, 0],
30004                 "top": [0, -sideOffset],
30005                 "top-left": [-cornerOffset, -cornerOffset],
30006                 "top-right": [cornerOffset, -cornerOffset],
30007             };
30008         }
30009         else {
30010             // input specifes a value for each position
30011             return {
30012                 "bottom": offset.bottom || [0, 0],
30013                 "bottom-left": offset.bottomLeft || [0, 0],
30014                 "bottom-right": offset.bottomRight || [0, 0],
30015                 "center": offset.center || [0, 0],
30016                 "left": offset.left || [0, 0],
30017                 "right": offset.right || [0, 0],
30018                 "top": offset.top || [0, 0],
30019                 "top-left": offset.topLeft || [0, 0],
30020                 "top-right": offset.topRight || [0, 0],
30021             };
30022         }
30023     };
30024     Popup.prototype._pixelToFloats = function (pointPixel, size, width, height) {
30025         var floats = [];
30026         if (pointPixel[1] < height) {
30027             floats.push("bottom");
30028         }
30029         else if (pointPixel[1] > size.height - height) {
30030             floats.push("top");
30031         }
30032         if (pointPixel[0] < width / 2) {
30033             floats.push("right");
30034         }
30035         else if (pointPixel[0] > size.width - width / 2) {
30036             floats.push("left");
30037         }
30038         return floats;
30039     };
30040     Popup.prototype._pointFromRectPosition = function (rect, position) {
30041         var x0 = rect[0];
30042         var x1 = rect[0] < rect[2] ? rect[2] : rect[2] + 1;
30043         var y0 = rect[1];
30044         var y1 = rect[3];
30045         switch (position) {
30046             case "bottom":
30047                 return [(x0 + x1) / 2, y1];
30048             case "bottom-left":
30049                 return [x0, y1];
30050             case "bottom-right":
30051                 return [x1, y1];
30052             case "center":
30053                 return [(x0 + x1) / 2, (y0 + y1) / 2];
30054             case "left":
30055                 return [x0, (y0 + y1) / 2];
30056             case "right":
30057                 return [x1, (y0 + y1) / 2];
30058             case "top":
30059                 return [(x0 + x1) / 2, y0];
30060             case "top-left":
30061                 return [x0, y0];
30062             case "top-right":
30063                 return [x1, y0];
30064             default:
30065                 return [(x0 + x1) / 2, y1];
30066         }
30067     };
30068     return Popup;
30069 }());
30070 exports.Popup = Popup;
30071 exports.default = Popup;
30072
30073 },{"../../../Geo":294,"../../../Utils":301,"../../../Viewer":302,"rxjs/Subject":34}],350:[function(require,module,exports){
30074 "use strict";
30075 /// <reference path="../../../typings/index.d.ts" />
30076 var __extends = (this && this.__extends) || (function () {
30077     var extendStatics = Object.setPrototypeOf ||
30078         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30079         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30080     return function (d, b) {
30081         extendStatics(d, b);
30082         function __() { this.constructor = d; }
30083         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30084     };
30085 })();
30086 Object.defineProperty(exports, "__esModule", { value: true });
30087 var Observable_1 = require("rxjs/Observable");
30088 var Subject_1 = require("rxjs/Subject");
30089 require("rxjs/add/observable/combineLatest");
30090 require("rxjs/add/observable/of");
30091 require("rxjs/add/observable/concat");
30092 require("rxjs/add/operator/auditTime");
30093 require("rxjs/add/operator/bufferCount");
30094 require("rxjs/add/operator/concat");
30095 require("rxjs/add/operator/distinctUntilChanged");
30096 require("rxjs/add/operator/filter");
30097 require("rxjs/add/operator/finally");
30098 require("rxjs/add/operator/first");
30099 require("rxjs/add/operator/map");
30100 require("rxjs/add/operator/publishReplay");
30101 require("rxjs/add/operator/retry");
30102 require("rxjs/add/operator/scan");
30103 require("rxjs/add/operator/share");
30104 require("rxjs/add/operator/switchMap");
30105 require("rxjs/add/operator/takeUntil");
30106 require("rxjs/add/operator/withLatestFrom");
30107 var Component_1 = require("../../Component");
30108 var Edge_1 = require("../../Edge");
30109 var Graph_1 = require("../../Graph");
30110 /**
30111  * @class SequenceComponent
30112  * @classdesc Component showing navigation arrows for sequence directions
30113  * as well as playing button. Exposes an API to start and stop play.
30114  */
30115 var SequenceComponent = /** @class */ (function (_super) {
30116     __extends(SequenceComponent, _super);
30117     function SequenceComponent(name, container, navigator, renderer, scheduler) {
30118         var _this = _super.call(this, name, container, navigator) || this;
30119         _this._sequenceDOMRenderer = !!renderer ? renderer : new Component_1.SequenceDOMRenderer(container);
30120         _this._scheduler = scheduler;
30121         _this._containerWidth$ = new Subject_1.Subject();
30122         _this._hoveredKeySubject$ = new Subject_1.Subject();
30123         _this._hoveredKey$ = _this._hoveredKeySubject$.share();
30124         _this._navigator.playService.playing$
30125             .skip(1)
30126             .withLatestFrom(_this._configuration$)
30127             .subscribe(function (_a) {
30128             var playing = _a[0], configuration = _a[1];
30129             _this.fire(SequenceComponent.playingchanged, playing);
30130             if (playing === configuration.playing) {
30131                 return;
30132             }
30133             if (playing) {
30134                 _this.play();
30135             }
30136             else {
30137                 _this.stop();
30138             }
30139         });
30140         _this._navigator.playService.direction$
30141             .skip(1)
30142             .withLatestFrom(_this._configuration$)
30143             .subscribe(function (_a) {
30144             var direction = _a[0], configuration = _a[1];
30145             if (direction !== configuration.direction) {
30146                 _this.setDirection(direction);
30147             }
30148         });
30149         return _this;
30150     }
30151     Object.defineProperty(SequenceComponent.prototype, "hoveredKey$", {
30152         /**
30153          * Get hovered key observable.
30154          *
30155          * @description An observable emitting the key of the node for the direction
30156          * arrow that is being hovered. When the mouse leaves a direction arrow null
30157          * is emitted.
30158          *
30159          * @returns {Observable<string>}
30160          */
30161         get: function () {
30162             return this._hoveredKey$;
30163         },
30164         enumerable: true,
30165         configurable: true
30166     });
30167     /**
30168      * Start playing.
30169      *
30170      * @fires PlayerComponent#playingchanged
30171      */
30172     SequenceComponent.prototype.play = function () {
30173         this.configure({ playing: true });
30174     };
30175     /**
30176      * Stop playing.
30177      *
30178      * @fires PlayerComponent#playingchanged
30179      */
30180     SequenceComponent.prototype.stop = function () {
30181         this.configure({ playing: false });
30182     };
30183     /**
30184      * Set the direction to follow when playing.
30185      *
30186      * @param {EdgeDirection} direction - The direction that will be followed when playing.
30187      */
30188     SequenceComponent.prototype.setDirection = function (direction) {
30189         this.configure({ direction: direction });
30190     };
30191     /**
30192      * Set highlight key.
30193      *
30194      * @description The arrow pointing towards the node corresponding to the
30195      * highlight key will be highlighted.
30196      *
30197      * @param {string} highlightKey Key of node to be highlighted if existing.
30198      */
30199     SequenceComponent.prototype.setHighlightKey = function (highlightKey) {
30200         this.configure({ highlightKey: highlightKey });
30201     };
30202     /**
30203      * Set max width of container element.
30204      *
30205      * @description Set max width of the container element holding
30206      * the sequence navigation elements. If the min width is larger than the
30207      * max width the min width value will be used.
30208      *
30209      * The container element is automatically resized when the resize
30210      * method on the Viewer class is called.
30211      *
30212      * @param {number} minWidth
30213      */
30214     SequenceComponent.prototype.setMaxWidth = function (maxWidth) {
30215         this.configure({ maxWidth: maxWidth });
30216     };
30217     /**
30218      * Set min width of container element.
30219      *
30220      * @description Set min width of the container element holding
30221      * the sequence navigation elements. If the min width is larger than the
30222      * max width the min width value will be used.
30223      *
30224      * The container element is automatically resized when the resize
30225      * method on the Viewer class is called.
30226      *
30227      * @param {number} minWidth
30228      */
30229     SequenceComponent.prototype.setMinWidth = function (minWidth) {
30230         this.configure({ minWidth: minWidth });
30231     };
30232     /**
30233      * Set the value indicating whether the sequence UI elements should be visible.
30234      *
30235      * @param {boolean} visible
30236      */
30237     SequenceComponent.prototype.setVisible = function (visible) {
30238         this.configure({ visible: visible });
30239     };
30240     /** @inheritdoc */
30241     SequenceComponent.prototype.resize = function () {
30242         var _this = this;
30243         this._configuration$
30244             .first()
30245             .map(function (configuration) {
30246             return _this._sequenceDOMRenderer.getContainerWidth(_this._container.element, configuration);
30247         })
30248             .subscribe(function (containerWidth) {
30249             _this._containerWidth$.next(containerWidth);
30250         });
30251     };
30252     SequenceComponent.prototype._activate = function () {
30253         var _this = this;
30254         this._sequenceDOMRenderer.activate();
30255         var edgeStatus$ = this._navigator.stateService.currentNode$
30256             .switchMap(function (node) {
30257             return node.sequenceEdges$;
30258         })
30259             .publishReplay(1)
30260             .refCount();
30261         var sequence$ = this._navigator.stateService.currentNode$
30262             .distinctUntilChanged(undefined, function (node) {
30263             return node.sequenceKey;
30264         })
30265             .switchMap(function (node) {
30266             return Observable_1.Observable
30267                 .concat(Observable_1.Observable.of(null), _this._navigator.graphService.cacheSequence$(node.sequenceKey)
30268                 .retry(3)
30269                 .catch(function (e) {
30270                 console.error("Failed to cache sequence", e);
30271                 return Observable_1.Observable.of(null);
30272             }));
30273         })
30274             .startWith(null)
30275             .publishReplay(1)
30276             .refCount();
30277         this._sequenceSubscription = sequence$.subscribe();
30278         var rendererKey$ = this._sequenceDOMRenderer.index$
30279             .withLatestFrom(sequence$)
30280             .map(function (_a) {
30281             var index = _a[0], sequence = _a[1];
30282             return sequence != null ? sequence.keys[index] : null;
30283         })
30284             .filter(function (key) {
30285             return !!key;
30286         })
30287             .distinctUntilChanged()
30288             .publish()
30289             .refCount();
30290         this._moveSubscription = Observable_1.Observable
30291             .merge(rendererKey$.debounceTime(100, this._scheduler), rendererKey$.auditTime(400, this._scheduler))
30292             .distinctUntilChanged()
30293             .switchMap(function (key) {
30294             return _this._navigator.moveToKey$(key)
30295                 .catch(function (e) {
30296                 return Observable_1.Observable.empty();
30297             });
30298         })
30299             .subscribe();
30300         this._setSequenceGraphModeSubscription = this._sequenceDOMRenderer.changingPositionChanged$
30301             .filter(function (changing) {
30302             return changing;
30303         })
30304             .subscribe(function () {
30305             _this._navigator.graphService.setGraphMode(Graph_1.GraphMode.Sequence);
30306         });
30307         this._setSpatialGraphModeSubscription = this._sequenceDOMRenderer.changingPositionChanged$
30308             .filter(function (changing) {
30309             return !changing;
30310         })
30311             .subscribe(function () {
30312             _this._navigator.graphService.setGraphMode(Graph_1.GraphMode.Spatial);
30313         });
30314         this._navigator.graphService.graphMode$
30315             .switchMap(function (mode) {
30316             return mode === Graph_1.GraphMode.Spatial ?
30317                 _this._navigator.stateService.currentNode$
30318                     .take(2) :
30319                 Observable_1.Observable.empty();
30320         })
30321             .filter(function (node) {
30322             return !node.spatialEdges.cached;
30323         })
30324             .switchMap(function (node) {
30325             return _this._navigator.graphService.cacheNode$(node.key)
30326                 .catch(function (e) {
30327                 return Observable_1.Observable.empty();
30328             });
30329         })
30330             .subscribe();
30331         this._stopSubscription = this._sequenceDOMRenderer.changingPositionChanged$
30332             .filter(function (changing) {
30333             return changing;
30334         })
30335             .subscribe(function () {
30336             _this._navigator.playService.stop();
30337         });
30338         this._cacheSequenceNodesSubscription = Observable_1.Observable
30339             .combineLatest(this._navigator.graphService.graphMode$, this._sequenceDOMRenderer.changingPositionChanged$
30340             .startWith(false)
30341             .distinctUntilChanged())
30342             .withLatestFrom(this._navigator.stateService.currentNode$)
30343             .switchMap(function (_a) {
30344             var _b = _a[0], mode = _b[0], changing = _b[1], node = _a[1];
30345             return changing && mode === Graph_1.GraphMode.Sequence ?
30346                 _this._navigator.graphService.cacheSequenceNodes$(node.sequenceKey, node.key)
30347                     .retry(3)
30348                     .catch(function (error) {
30349                     console.error("Failed to cache sequence nodes.", error);
30350                     return Observable_1.Observable.empty();
30351                 }) :
30352                 Observable_1.Observable.empty();
30353         })
30354             .subscribe();
30355         var position$ = sequence$
30356             .switchMap(function (sequence) {
30357             if (!sequence) {
30358                 return Observable_1.Observable.of({ index: null, max: null });
30359             }
30360             var firstCurrentKey = true;
30361             return _this._sequenceDOMRenderer.changingPositionChanged$
30362                 .startWith(false)
30363                 .distinctUntilChanged()
30364                 .switchMap(function (changingPosition) {
30365                 var skip = !changingPosition && firstCurrentKey ? 0 : 1;
30366                 firstCurrentKey = false;
30367                 return changingPosition ?
30368                     rendererKey$ :
30369                     _this._navigator.stateService.currentNode$
30370                         .map(function (node) {
30371                         return node.key;
30372                     })
30373                         .distinctUntilChanged()
30374                         .skip(skip);
30375             })
30376                 .map(function (key) {
30377                 var index = sequence.keys.indexOf(key);
30378                 if (index === -1) {
30379                     return { index: null, max: null };
30380                 }
30381                 return { index: index, max: sequence.keys.length - 1 };
30382             });
30383         });
30384         this._renderSubscription = Observable_1.Observable
30385             .combineLatest(edgeStatus$, this._configuration$, this._containerWidth$, this._sequenceDOMRenderer.changed$.startWith(this._sequenceDOMRenderer), this._navigator.playService.speed$, position$)
30386             .map(function (_a) {
30387             var edgeStatus = _a[0], configuration = _a[1], containerWidth = _a[2], renderer = _a[3], speed = _a[4], position = _a[5];
30388             var vNode = _this._sequenceDOMRenderer
30389                 .render(edgeStatus, configuration, containerWidth, speed, position.index, position.max, _this, _this._navigator);
30390             return { name: _this._name, vnode: vNode };
30391         })
30392             .subscribe(this._container.domRenderer.render$);
30393         this._setSpeedSubscription = this._sequenceDOMRenderer.speed$
30394             .subscribe(function (speed) {
30395             _this._navigator.playService.setSpeed(speed);
30396         });
30397         this._setDirectionSubscription = this._configuration$
30398             .map(function (configuration) {
30399             return configuration.direction;
30400         })
30401             .distinctUntilChanged()
30402             .subscribe(function (direction) {
30403             _this._navigator.playService.setDirection(direction);
30404         });
30405         this._containerWidthSubscription = this._configuration$
30406             .distinctUntilChanged(function (value1, value2) {
30407             return value1[0] === value2[0] && value1[1] === value2[1];
30408         }, function (configuration) {
30409             return [configuration.minWidth, configuration.maxWidth];
30410         })
30411             .map(function (configuration) {
30412             return _this._sequenceDOMRenderer.getContainerWidth(_this._container.element, configuration);
30413         })
30414             .subscribe(this._containerWidth$);
30415         this._playingSubscription = this._configuration$
30416             .map(function (configuration) {
30417             return configuration.playing;
30418         })
30419             .distinctUntilChanged()
30420             .subscribe(function (playing) {
30421             if (playing) {
30422                 _this._navigator.playService.play();
30423             }
30424             else {
30425                 _this._navigator.playService.stop();
30426             }
30427         });
30428         this._hoveredKeySubscription = this._sequenceDOMRenderer.mouseEnterDirection$
30429             .switchMap(function (direction) {
30430             return edgeStatus$
30431                 .map(function (edgeStatus) {
30432                 for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
30433                     var edge = _a[_i];
30434                     if (edge.data.direction === direction) {
30435                         return edge.to;
30436                     }
30437                 }
30438                 return null;
30439             })
30440                 .takeUntil(_this._sequenceDOMRenderer.mouseLeaveDirection$)
30441                 .concat(Observable_1.Observable.of(null));
30442         })
30443             .distinctUntilChanged()
30444             .subscribe(this._hoveredKeySubject$);
30445     };
30446     SequenceComponent.prototype._deactivate = function () {
30447         this._renderSubscription.unsubscribe();
30448         this._playingSubscription.unsubscribe();
30449         this._containerWidthSubscription.unsubscribe();
30450         this._hoveredKeySubscription.unsubscribe();
30451         this._setSpeedSubscription.unsubscribe();
30452         this._setDirectionSubscription.unsubscribe();
30453         this._setSequenceGraphModeSubscription.unsubscribe();
30454         this._setSpatialGraphModeSubscription.unsubscribe();
30455         this._sequenceSubscription.unsubscribe();
30456         this._moveSubscription.unsubscribe();
30457         this._cacheSequenceNodesSubscription.unsubscribe();
30458         this._stopSubscription.unsubscribe();
30459         this._sequenceDOMRenderer.deactivate();
30460     };
30461     SequenceComponent.prototype._getDefaultConfiguration = function () {
30462         return {
30463             direction: Edge_1.EdgeDirection.Next,
30464             maxWidth: 108,
30465             minWidth: 70,
30466             playing: false,
30467             visible: true,
30468         };
30469     };
30470     /** @inheritdoc */
30471     SequenceComponent.componentName = "sequence";
30472     /**
30473      * Event fired when playing starts or stops.
30474      *
30475      * @event PlayerComponent#playingchanged
30476      * @type {boolean} Indicates whether the player is playing.
30477      */
30478     SequenceComponent.playingchanged = "playingchanged";
30479     return SequenceComponent;
30480 }(Component_1.Component));
30481 exports.SequenceComponent = SequenceComponent;
30482 Component_1.ComponentService.register(SequenceComponent);
30483 exports.default = SequenceComponent;
30484
30485 },{"../../Component":291,"../../Edge":292,"../../Graph":295,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/combineLatest":38,"rxjs/add/observable/concat":39,"rxjs/add/observable/of":46,"rxjs/add/operator/auditTime":50,"rxjs/add/operator/bufferCount":52,"rxjs/add/operator/concat":56,"rxjs/add/operator/distinctUntilChanged":60,"rxjs/add/operator/filter":63,"rxjs/add/operator/finally":64,"rxjs/add/operator/first":65,"rxjs/add/operator/map":67,"rxjs/add/operator/publishReplay":74,"rxjs/add/operator/retry":76,"rxjs/add/operator/scan":78,"rxjs/add/operator/share":79,"rxjs/add/operator/switchMap":84,"rxjs/add/operator/takeUntil":86,"rxjs/add/operator/withLatestFrom":90}],351:[function(require,module,exports){
30486 "use strict";
30487 /// <reference path="../../../typings/index.d.ts" />
30488 Object.defineProperty(exports, "__esModule", { value: true });
30489 var vd = require("virtual-dom");
30490 var Observable_1 = require("rxjs/Observable");
30491 var Subject_1 = require("rxjs/Subject");
30492 var Component_1 = require("../../Component");
30493 var Edge_1 = require("../../Edge");
30494 var Error_1 = require("../../Error");
30495 var SequenceDOMRenderer = /** @class */ (function () {
30496     function SequenceDOMRenderer(container) {
30497         this._container = container;
30498         this._minThresholdWidth = 320;
30499         this._maxThresholdWidth = 1480;
30500         this._minThresholdHeight = 240;
30501         this._maxThresholdHeight = 820;
30502         this._stepperDefaultWidth = 108;
30503         this._controlsDefaultWidth = 88;
30504         this._defaultHeight = 30;
30505         this._expandControls = false;
30506         this._mode = Component_1.SequenceMode.Default;
30507         this._speed = 0.5;
30508         this._changingSpeed = false;
30509         this._index = null;
30510         this._changingPosition = false;
30511         this._mouseEnterDirection$ = new Subject_1.Subject();
30512         this._mouseLeaveDirection$ = new Subject_1.Subject();
30513         this._notifyChanged$ = new Subject_1.Subject();
30514         this._notifyChangingPositionChanged$ = new Subject_1.Subject();
30515         this._notifySpeedChanged$ = new Subject_1.Subject();
30516         this._notifyIndexChanged$ = new Subject_1.Subject();
30517     }
30518     Object.defineProperty(SequenceDOMRenderer.prototype, "changed$", {
30519         get: function () {
30520             return this._notifyChanged$;
30521         },
30522         enumerable: true,
30523         configurable: true
30524     });
30525     Object.defineProperty(SequenceDOMRenderer.prototype, "changingPositionChanged$", {
30526         get: function () {
30527             return this._notifyChangingPositionChanged$;
30528         },
30529         enumerable: true,
30530         configurable: true
30531     });
30532     Object.defineProperty(SequenceDOMRenderer.prototype, "speed$", {
30533         get: function () {
30534             return this._notifySpeedChanged$;
30535         },
30536         enumerable: true,
30537         configurable: true
30538     });
30539     Object.defineProperty(SequenceDOMRenderer.prototype, "index$", {
30540         get: function () {
30541             return this._notifyIndexChanged$;
30542         },
30543         enumerable: true,
30544         configurable: true
30545     });
30546     Object.defineProperty(SequenceDOMRenderer.prototype, "mouseEnterDirection$", {
30547         get: function () {
30548             return this._mouseEnterDirection$;
30549         },
30550         enumerable: true,
30551         configurable: true
30552     });
30553     Object.defineProperty(SequenceDOMRenderer.prototype, "mouseLeaveDirection$", {
30554         get: function () {
30555             return this._mouseLeaveDirection$;
30556         },
30557         enumerable: true,
30558         configurable: true
30559     });
30560     SequenceDOMRenderer.prototype.activate = function () {
30561         var _this = this;
30562         if (!!this._changingSubscription) {
30563             return;
30564         }
30565         this._changingSubscription = Observable_1.Observable
30566             .merge(this._container.mouseService.documentMouseUp$, this._container.touchService.touchEnd$
30567             .filter(function (touchEvent) {
30568             return touchEvent.touches.length === 0;
30569         }))
30570             .subscribe(function (event) {
30571             if (_this._changingSpeed) {
30572                 _this._changingSpeed = false;
30573             }
30574             if (_this._changingPosition) {
30575                 _this._setChangingPosition(false);
30576             }
30577         });
30578     };
30579     SequenceDOMRenderer.prototype.deactivate = function () {
30580         if (!this._changingSubscription) {
30581             return;
30582         }
30583         this._changingSpeed = false;
30584         this._changingPosition = false;
30585         this._expandControls = false;
30586         this._mode = Component_1.SequenceMode.Default;
30587         this._changingSubscription.unsubscribe();
30588         this._changingSubscription = null;
30589     };
30590     SequenceDOMRenderer.prototype.render = function (edgeStatus, configuration, containerWidth, speed, index, max, component, navigator) {
30591         if (configuration.visible === false) {
30592             return vd.h("div.SequenceContainer", {}, []);
30593         }
30594         var stepper = this._createStepper(edgeStatus, configuration, containerWidth, component, navigator);
30595         var controls = this._createSequenceControls(containerWidth);
30596         var playback = this._createPlaybackControls(containerWidth, speed, component, configuration);
30597         var timeline = this._createTimelineControls(containerWidth, index, max);
30598         return vd.h("div.SequenceContainer", [stepper, controls, playback, timeline]);
30599     };
30600     SequenceDOMRenderer.prototype.getContainerWidth = function (element, configuration) {
30601         var elementWidth = element.offsetWidth;
30602         var elementHeight = element.offsetHeight;
30603         var minWidth = configuration.minWidth;
30604         var maxWidth = configuration.maxWidth;
30605         if (maxWidth < minWidth) {
30606             maxWidth = minWidth;
30607         }
30608         var relativeWidth = (elementWidth - this._minThresholdWidth) / (this._maxThresholdWidth - this._minThresholdWidth);
30609         var relativeHeight = (elementHeight - this._minThresholdHeight) / (this._maxThresholdHeight - this._minThresholdHeight);
30610         var coeff = Math.max(0, Math.min(1, Math.min(relativeWidth, relativeHeight)));
30611         return minWidth + coeff * (maxWidth - minWidth);
30612     };
30613     SequenceDOMRenderer.prototype._createPositionInput = function (index, max) {
30614         var _this = this;
30615         this._index = index;
30616         var onPosition = function (e) {
30617             _this._index = Number(e.target.value);
30618             _this._notifyIndexChanged$.next(_this._index);
30619         };
30620         var boundingRect = this._container.domContainer.getBoundingClientRect();
30621         var width = Math.max(276, Math.min(410, 5 + 0.8 * boundingRect.width)) - 65;
30622         var onStart = function (e) {
30623             e.stopPropagation();
30624             _this._setChangingPosition(true);
30625         };
30626         var onMove = function (e) {
30627             if (_this._changingPosition === true) {
30628                 e.stopPropagation();
30629             }
30630         };
30631         var onKeyDown = function (e) {
30632             if (e.key === "ArrowDown" || e.key === "ArrowLeft" ||
30633                 e.key === "ArrowRight" || e.key === "ArrowUp") {
30634                 e.preventDefault();
30635             }
30636         };
30637         var positionInputProperties = {
30638             max: max != null ? max : 1,
30639             min: 0,
30640             onchange: onPosition,
30641             oninput: onPosition,
30642             onkeydown: onKeyDown,
30643             onmousedown: onStart,
30644             onmousemove: onMove,
30645             ontouchmove: onMove,
30646             ontouchstart: onStart,
30647             style: {
30648                 width: width + "px",
30649             },
30650             type: "range",
30651             value: index != null ? index : 0,
30652         };
30653         var disabled = index == null || max == null || max <= 1;
30654         if (disabled) {
30655             positionInputProperties.disabled = "true";
30656         }
30657         var positionInput = vd.h("input.SequencePosition", positionInputProperties, []);
30658         var positionContainerClass = disabled ? ".SequencePositionContainerDisabled" : ".SequencePositionContainer";
30659         return vd.h("div" + positionContainerClass, [positionInput]);
30660     };
30661     SequenceDOMRenderer.prototype._createSpeedInput = function (speed) {
30662         var _this = this;
30663         this._speed = speed;
30664         var onSpeed = function (e) {
30665             _this._speed = Number(e.target.value) / 1000;
30666             _this._notifySpeedChanged$.next(_this._speed);
30667         };
30668         var boundingRect = this._container.domContainer.getBoundingClientRect();
30669         var width = Math.max(276, Math.min(410, 5 + 0.8 * boundingRect.width)) - 160;
30670         var onStart = function (e) {
30671             _this._changingSpeed = true;
30672             e.stopPropagation();
30673         };
30674         var onMove = function (e) {
30675             if (_this._changingSpeed === true) {
30676                 e.stopPropagation();
30677             }
30678         };
30679         var onKeyDown = function (e) {
30680             if (e.key === "ArrowDown" || e.key === "ArrowLeft" ||
30681                 e.key === "ArrowRight" || e.key === "ArrowUp") {
30682                 e.preventDefault();
30683             }
30684         };
30685         var speedInput = vd.h("input.SequenceSpeed", {
30686             max: 1000,
30687             min: 0,
30688             onchange: onSpeed,
30689             oninput: onSpeed,
30690             onkeydown: onKeyDown,
30691             onmousedown: onStart,
30692             onmousemove: onMove,
30693             ontouchmove: onMove,
30694             ontouchstart: onStart,
30695             style: {
30696                 width: width + "px",
30697             },
30698             type: "range",
30699             value: 1000 * speed,
30700         }, []);
30701         return vd.h("div.SequenceSpeedContainer", [speedInput]);
30702     };
30703     SequenceDOMRenderer.prototype._createPlaybackControls = function (containerWidth, speed, component, configuration) {
30704         var _this = this;
30705         if (this._mode !== Component_1.SequenceMode.Playback) {
30706             return vd.h("div.SequencePlayback", []);
30707         }
30708         var switchIcon = vd.h("div.SequenceSwitchIcon.SequenceIconVisible", []);
30709         var direction = configuration.direction === Edge_1.EdgeDirection.Next ?
30710             Edge_1.EdgeDirection.Prev : Edge_1.EdgeDirection.Next;
30711         var playing = configuration.playing;
30712         var switchButtonProperties = {
30713             onclick: function () {
30714                 if (!playing) {
30715                     component.setDirection(direction);
30716                 }
30717             },
30718         };
30719         var switchButtonClassName = configuration.playing ? ".SequenceSwitchButtonDisabled" : ".SequenceSwitchButton";
30720         var switchButton = vd.h("div" + switchButtonClassName, switchButtonProperties, [switchIcon]);
30721         var slowIcon = vd.h("div.SequenceSlowIcon.SequenceIconVisible", []);
30722         var slowContainer = vd.h("div.SequenceSlowContainer", [slowIcon]);
30723         var fastIcon = vd.h("div.SequenceFastIconGrey.SequenceIconVisible", []);
30724         var fastContainer = vd.h("div.SequenceFastContainer", [fastIcon]);
30725         var closeIcon = vd.h("div.SequenceCloseIcon.SequenceIconVisible", []);
30726         var closeButtonProperties = {
30727             onclick: function () {
30728                 _this._mode = Component_1.SequenceMode.Default;
30729                 _this._notifyChanged$.next(_this);
30730             },
30731         };
30732         var closeButton = vd.h("div.SequenceCloseButton", closeButtonProperties, [closeIcon]);
30733         var speedInput = this._createSpeedInput(speed);
30734         var playbackChildren = [switchButton, slowContainer, speedInput, fastContainer, closeButton];
30735         var top = Math.round(containerWidth / this._stepperDefaultWidth * this._defaultHeight + 10);
30736         var playbackProperties = { style: { top: top + "px" } };
30737         return vd.h("div.SequencePlayback", playbackProperties, playbackChildren);
30738     };
30739     SequenceDOMRenderer.prototype._createPlayingButton = function (nextKey, prevKey, configuration, component) {
30740         var canPlay = configuration.direction === Edge_1.EdgeDirection.Next && nextKey != null ||
30741             configuration.direction === Edge_1.EdgeDirection.Prev && prevKey != null;
30742         var onclick = configuration.playing ?
30743             function (e) { component.stop(); } :
30744             canPlay ? function (e) { component.play(); } : null;
30745         var buttonProperties = { onclick: onclick };
30746         var iconClass = configuration.playing ?
30747             "Stop" :
30748             canPlay ? "Play" : "PlayDisabled";
30749         var iconProperties = { className: iconClass };
30750         if (configuration.direction === Edge_1.EdgeDirection.Prev) {
30751             iconProperties.style = {
30752                 transform: "rotate(180deg) translate(50%, 50%)",
30753             };
30754         }
30755         var icon = vd.h("div.SequenceComponentIcon", iconProperties, []);
30756         var buttonClass = canPlay ? "SequencePlay" : "SequencePlayDisabled";
30757         return vd.h("div." + buttonClass, buttonProperties, [icon]);
30758     };
30759     SequenceDOMRenderer.prototype._createSequenceControls = function (containerWidth) {
30760         var _this = this;
30761         var borderRadius = Math.round(8 / this._stepperDefaultWidth * containerWidth);
30762         var expanderProperties = {
30763             onclick: function () {
30764                 _this._expandControls = !_this._expandControls;
30765                 _this._mode = Component_1.SequenceMode.Default;
30766                 _this._notifyChanged$.next(_this);
30767             },
30768             style: {
30769                 "border-bottom-right-radius": borderRadius + "px",
30770                 "border-top-right-radius": borderRadius + "px",
30771             },
30772         };
30773         var expanderBar = vd.h("div.SequenceExpanderBar", []);
30774         var expander = vd.h("div.SequenceExpanderButton", expanderProperties, [expanderBar]);
30775         var fastIconClassName = this._mode === Component_1.SequenceMode.Playback ?
30776             ".SequenceFastIconGrey.SequenceIconVisible" : ".SequenceFastIcon";
30777         var fastIcon = vd.h("div" + fastIconClassName, []);
30778         var playbackProperties = {
30779             onclick: function () {
30780                 _this._mode = _this._mode === Component_1.SequenceMode.Playback ?
30781                     Component_1.SequenceMode.Default :
30782                     Component_1.SequenceMode.Playback;
30783                 _this._notifyChanged$.next(_this);
30784             },
30785         };
30786         var playback = vd.h("div.SequencePlaybackButton", playbackProperties, [fastIcon]);
30787         var timelineIconClassName = this._mode === Component_1.SequenceMode.Timeline ?
30788             ".SequenceTimelineIconGrey.SequenceIconVisible" : ".SequenceTimelineIcon";
30789         var timelineIcon = vd.h("div" + timelineIconClassName, []);
30790         var timelineProperties = {
30791             onclick: function () {
30792                 _this._mode = _this._mode === Component_1.SequenceMode.Timeline ?
30793                     Component_1.SequenceMode.Default :
30794                     Component_1.SequenceMode.Timeline;
30795                 _this._notifyChanged$.next(_this);
30796             },
30797         };
30798         var timeline = vd.h("div.SequenceTimelineButton", timelineProperties, [timelineIcon]);
30799         var properties = {
30800             style: {
30801                 height: (this._defaultHeight / this._stepperDefaultWidth * containerWidth) + "px",
30802                 transform: "translate(" + (containerWidth / 2 + 2) + "px, 0)",
30803                 width: (this._controlsDefaultWidth / this._stepperDefaultWidth * containerWidth) + "px",
30804             },
30805         };
30806         var className = ".SequenceControls" +
30807             (this._expandControls ? ".SequenceControlsExpanded" : "");
30808         return vd.h("div" + className, properties, [playback, timeline, expander]);
30809     };
30810     SequenceDOMRenderer.prototype._createSequenceArrows = function (nextKey, prevKey, containerWidth, configuration, navigator) {
30811         var _this = this;
30812         var nextProperties = {
30813             onclick: nextKey != null ?
30814                 function (e) {
30815                     navigator.moveDir$(Edge_1.EdgeDirection.Next)
30816                         .subscribe(undefined, function (error) {
30817                         if (!(error instanceof Error_1.AbortMapillaryError)) {
30818                             console.error(error);
30819                         }
30820                     });
30821                 } :
30822                 null,
30823             onmouseenter: function (e) { _this._mouseEnterDirection$.next(Edge_1.EdgeDirection.Next); },
30824             onmouseleave: function (e) { _this._mouseLeaveDirection$.next(Edge_1.EdgeDirection.Next); },
30825         };
30826         var borderRadius = Math.round(8 / this._stepperDefaultWidth * containerWidth);
30827         var prevProperties = {
30828             onclick: prevKey != null ?
30829                 function (e) {
30830                     navigator.moveDir$(Edge_1.EdgeDirection.Prev)
30831                         .subscribe(undefined, function (error) {
30832                         if (!(error instanceof Error_1.AbortMapillaryError)) {
30833                             console.error(error);
30834                         }
30835                     });
30836                 } :
30837                 null,
30838             onmouseenter: function (e) { _this._mouseEnterDirection$.next(Edge_1.EdgeDirection.Prev); },
30839             onmouseleave: function (e) { _this._mouseLeaveDirection$.next(Edge_1.EdgeDirection.Prev); },
30840             style: {
30841                 "border-bottom-left-radius": borderRadius + "px",
30842                 "border-top-left-radius": borderRadius + "px",
30843             },
30844         };
30845         var nextClass = this._getStepClassName(Edge_1.EdgeDirection.Next, nextKey, configuration.highlightKey);
30846         var prevClass = this._getStepClassName(Edge_1.EdgeDirection.Prev, prevKey, configuration.highlightKey);
30847         var nextIcon = vd.h("div.SequenceComponentIcon", []);
30848         var prevIcon = vd.h("div.SequenceComponentIcon", []);
30849         return [
30850             vd.h("div." + prevClass, prevProperties, [prevIcon]),
30851             vd.h("div." + nextClass, nextProperties, [nextIcon]),
30852         ];
30853     };
30854     SequenceDOMRenderer.prototype._createStepper = function (edgeStatus, configuration, containerWidth, component, navigator) {
30855         var nextKey = null;
30856         var prevKey = null;
30857         for (var _i = 0, _a = edgeStatus.edges; _i < _a.length; _i++) {
30858             var edge = _a[_i];
30859             if (edge.data.direction === Edge_1.EdgeDirection.Next) {
30860                 nextKey = edge.to;
30861             }
30862             if (edge.data.direction === Edge_1.EdgeDirection.Prev) {
30863                 prevKey = edge.to;
30864             }
30865         }
30866         var playingButton = this._createPlayingButton(nextKey, prevKey, configuration, component);
30867         var buttons = this._createSequenceArrows(nextKey, prevKey, containerWidth, configuration, navigator);
30868         buttons.splice(1, 0, playingButton);
30869         var containerProperties = {
30870             oncontextmenu: function (event) { event.preventDefault(); },
30871             style: {
30872                 height: (this._defaultHeight / this._stepperDefaultWidth * containerWidth) + "px",
30873                 width: containerWidth + "px",
30874             },
30875         };
30876         return vd.h("div.SequenceStepper", containerProperties, buttons);
30877     };
30878     SequenceDOMRenderer.prototype._createTimelineControls = function (containerWidth, index, max) {
30879         var _this = this;
30880         if (this._mode !== Component_1.SequenceMode.Timeline) {
30881             return vd.h("div.SequenceTimeline", []);
30882         }
30883         var positionInput = this._createPositionInput(index, max);
30884         var closeIcon = vd.h("div.SequenceCloseIcon.SequenceIconVisible", []);
30885         var closeButtonProperties = {
30886             onclick: function () {
30887                 _this._mode = Component_1.SequenceMode.Default;
30888                 _this._notifyChanged$.next(_this);
30889             },
30890         };
30891         var closeButton = vd.h("div.SequenceCloseButton", closeButtonProperties, [closeIcon]);
30892         var top = Math.round(containerWidth / this._stepperDefaultWidth * this._defaultHeight + 10);
30893         var playbackProperties = { style: { top: top + "px" } };
30894         return vd.h("div.SequenceTimeline", playbackProperties, [positionInput, closeButton]);
30895     };
30896     SequenceDOMRenderer.prototype._getStepClassName = function (direction, key, highlightKey) {
30897         var className = direction === Edge_1.EdgeDirection.Next ?
30898             "SequenceStepNext" :
30899             "SequenceStepPrev";
30900         if (key == null) {
30901             className += "Disabled";
30902         }
30903         else {
30904             if (highlightKey === key) {
30905                 className += "Highlight";
30906             }
30907         }
30908         return className;
30909     };
30910     SequenceDOMRenderer.prototype._setChangingPosition = function (value) {
30911         this._changingPosition = value;
30912         this._notifyChangingPositionChanged$.next(value);
30913     };
30914     return SequenceDOMRenderer;
30915 }());
30916 exports.SequenceDOMRenderer = SequenceDOMRenderer;
30917 exports.default = SequenceDOMRenderer;
30918
30919 },{"../../Component":291,"../../Edge":292,"../../Error":293,"rxjs/Observable":29,"rxjs/Subject":34,"virtual-dom":247}],352:[function(require,module,exports){
30920 "use strict";
30921 Object.defineProperty(exports, "__esModule", { value: true });
30922 var SequenceMode;
30923 (function (SequenceMode) {
30924     SequenceMode[SequenceMode["Default"] = 0] = "Default";
30925     SequenceMode[SequenceMode["Playback"] = 1] = "Playback";
30926     SequenceMode[SequenceMode["Timeline"] = 2] = "Timeline";
30927 })(SequenceMode = exports.SequenceMode || (exports.SequenceMode = {}));
30928 exports.default = SequenceMode;
30929
30930 },{}],353:[function(require,module,exports){
30931 "use strict";
30932 Object.defineProperty(exports, "__esModule", { value: true });
30933 var GeometryTagError_1 = require("./error/GeometryTagError");
30934 exports.GeometryTagError = GeometryTagError_1.GeometryTagError;
30935 var PointGeometry_1 = require("./geometry/PointGeometry");
30936 exports.PointGeometry = PointGeometry_1.PointGeometry;
30937 var RectGeometry_1 = require("./geometry/RectGeometry");
30938 exports.RectGeometry = RectGeometry_1.RectGeometry;
30939 var PolygonGeometry_1 = require("./geometry/PolygonGeometry");
30940 exports.PolygonGeometry = PolygonGeometry_1.PolygonGeometry;
30941 var OutlineTag_1 = require("./tag/OutlineTag");
30942 exports.OutlineTag = OutlineTag_1.OutlineTag;
30943 var SpotTag_1 = require("./tag/SpotTag");
30944 exports.SpotTag = SpotTag_1.SpotTag;
30945 var TagComponent_1 = require("./TagComponent");
30946 exports.TagComponent = TagComponent_1.TagComponent;
30947 var TagMode_1 = require("./TagMode");
30948 exports.TagMode = TagMode_1.TagMode;
30949
30950 },{"./TagComponent":354,"./TagMode":357,"./error/GeometryTagError":361,"./geometry/PointGeometry":363,"./geometry/PolygonGeometry":364,"./geometry/RectGeometry":365,"./tag/OutlineTag":377,"./tag/SpotTag":380}],354:[function(require,module,exports){
30951 "use strict";
30952 /// <reference path="../../../typings/index.d.ts" />
30953 var __extends = (this && this.__extends) || (function () {
30954     var extendStatics = Object.setPrototypeOf ||
30955         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30956         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
30957     return function (d, b) {
30958         extendStatics(d, b);
30959         function __() { this.constructor = d; }
30960         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30961     };
30962 })();
30963 Object.defineProperty(exports, "__esModule", { value: true });
30964 var when = require("when");
30965 var Observable_1 = require("rxjs/Observable");
30966 require("rxjs/add/observable/combineLatest");
30967 require("rxjs/add/observable/empty");
30968 require("rxjs/add/observable/from");
30969 require("rxjs/add/observable/merge");
30970 require("rxjs/add/observable/of");
30971 require("rxjs/add/operator/combineLatest");
30972 require("rxjs/add/operator/concat");
30973 require("rxjs/add/operator/distinctUntilChanged");
30974 require("rxjs/add/operator/do");
30975 require("rxjs/add/operator/filter");
30976 require("rxjs/add/operator/map");
30977 require("rxjs/add/operator/merge");
30978 require("rxjs/add/operator/mergeMap");
30979 require("rxjs/add/operator/publishReplay");
30980 require("rxjs/add/operator/scan");
30981 require("rxjs/add/operator/share");
30982 require("rxjs/add/operator/skip");
30983 require("rxjs/add/operator/skipUntil");
30984 require("rxjs/add/operator/startWith");
30985 require("rxjs/add/operator/switchMap");
30986 require("rxjs/add/operator/take");
30987 require("rxjs/add/operator/takeUntil");
30988 require("rxjs/add/operator/withLatestFrom");
30989 var Component_1 = require("../../Component");
30990 var Geo_1 = require("../../Geo");
30991 var Render_1 = require("../../Render");
30992 /**
30993  * @class TagComponent
30994  *
30995  * @classdesc Component for showing and editing tags with different
30996  * geometries composed from 2D basic image coordinates (see the
30997  * {@link Viewer} class documentation for more information about coordinate
30998  * systems).
30999  *
31000  * The `add` method is used for adding new tags or replacing
31001  * tags already in the set. Tags are removed by id.
31002  *
31003  * If a tag already in the set has the same
31004  * id as one of the tags added, the old tag will be removed and
31005  * the added tag will take its place.
31006  *
31007  * The tag component mode can be set to either be non interactive or
31008  * to be in creating mode of a certain geometry type.
31009  *
31010  * The tag properties can be updated at any time and the change will
31011  * be visibile immediately.
31012  *
31013  * Tags are only relevant to a single image because they are based on
31014  * 2D basic image coordinates. Tags related to a certain image should
31015  * be removed when the viewer is moved to another node.
31016  *
31017  * To retrive and use the tag component
31018  *
31019  * @example
31020  * ```
31021  * var viewer = new Mapillary.Viewer(
31022  *     "<element-id>",
31023  *     "<client-id>",
31024  *     "<my key>",
31025  *     { component: { tag: true } });
31026  *
31027  * var tagComponent = viewer.getComponent("tag");
31028  * ```
31029  */
31030 var TagComponent = /** @class */ (function (_super) {
31031     __extends(TagComponent, _super);
31032     function TagComponent(name, container, navigator) {
31033         var _this = _super.call(this, name, container, navigator) || this;
31034         _this._tagDomRenderer = new Component_1.TagDOMRenderer();
31035         _this._tagScene = new Component_1.TagScene();
31036         _this._tagSet = new Component_1.TagSet();
31037         _this._tagCreator = new Component_1.TagCreator(_this, navigator);
31038         _this._viewportCoords = new Geo_1.ViewportCoords();
31039         _this._createHandlers = {
31040             "CreatePoint": new Component_1.CreatePointHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator),
31041             "CreatePolygon": new Component_1.CreatePolygonHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator),
31042             "CreateRect": new Component_1.CreateRectHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator),
31043             "CreateRectDrag": new Component_1.CreateRectDragHandler(_this, container, navigator, _this._viewportCoords, _this._tagCreator),
31044             "Default": undefined,
31045         };
31046         _this._editVertexHandler = new Component_1.EditVertexHandler(_this, container, navigator, _this._viewportCoords, _this._tagSet);
31047         _this._renderTags$ = _this._tagSet.changed$
31048             .map(function (tagSet) {
31049             var tags = tagSet.getAll();
31050             // ensure that tags are always rendered in the same order
31051             // to avoid hover tracking problems on first resize.
31052             tags.sort(function (t1, t2) {
31053                 var id1 = t1.tag.id;
31054                 var id2 = t2.tag.id;
31055                 if (id1 < id2) {
31056                     return -1;
31057                 }
31058                 if (id1 > id2) {
31059                     return 1;
31060                 }
31061                 return 0;
31062             });
31063             return tags;
31064         })
31065             .share();
31066         _this._tagChanged$ = _this._renderTags$
31067             .switchMap(function (tags) {
31068             return Observable_1.Observable
31069                 .from(tags)
31070                 .mergeMap(function (tag) {
31071                 return Observable_1.Observable
31072                     .merge(tag.tag.changed$, tag.tag.geometryChanged$);
31073             });
31074         })
31075             .share();
31076         _this._renderTagGLChanged$ = _this._renderTags$
31077             .switchMap(function (tags) {
31078             return Observable_1.Observable
31079                 .from(tags)
31080                 .mergeMap(function (tag) {
31081                 return tag.glObjectsChanged$;
31082             });
31083         })
31084             .share();
31085         _this._createGeometryChanged$ = _this._tagCreator.tag$
31086             .switchMap(function (tag) {
31087             return tag != null ?
31088                 tag.geometryChanged$ :
31089                 Observable_1.Observable.empty();
31090         })
31091             .share();
31092         _this._createGLObjectsChanged$ = _this._tagCreator.tag$
31093             .switchMap(function (tag) {
31094             return tag != null ?
31095                 tag.glObjectsChanged$ :
31096                 Observable_1.Observable.empty();
31097         })
31098             .share();
31099         _this._creatingConfiguration$ = _this._configuration$
31100             .distinctUntilChanged(function (c1, c2) {
31101             return c1.mode === c2.mode;
31102         }, function (configuration) {
31103             return {
31104                 createColor: configuration.createColor,
31105                 mode: configuration.mode,
31106             };
31107         })
31108             .publishReplay(1)
31109             .refCount();
31110         _this._creatingConfiguration$
31111             .subscribe(function (configuration) {
31112             _this.fire(TagComponent.modechanged, configuration.mode);
31113         });
31114         return _this;
31115     }
31116     /**
31117      * Add tags to the tag set or replace tags in the tag set.
31118      *
31119      * @description If a tag already in the set has the same
31120      * id as one of the tags added, the old tag will be removed
31121      * the added tag will take its place.
31122      *
31123      * @param {Array<Tag>} tags - Tags to add.
31124      *
31125      * @example ```tagComponent.add([tag1, tag2]);```
31126      */
31127     TagComponent.prototype.add = function (tags) {
31128         var _this = this;
31129         if (this._activated) {
31130             this._navigator.stateService.currentTransform$
31131                 .first()
31132                 .subscribe(function (transform) {
31133                 _this._tagSet.add(tags, transform);
31134                 var renderTags = tags
31135                     .map(function (tag) {
31136                     return _this._tagSet.get(tag.id);
31137                 });
31138                 _this._tagScene.add(renderTags);
31139             });
31140         }
31141         else {
31142             this._tagSet.addDeactivated(tags);
31143         }
31144     };
31145     /**
31146      * Change the current tag mode.
31147      *
31148      * @description Change the tag mode to one of the create modes for creating new geometries.
31149      *
31150      * @param {TagMode} mode - New tag mode.
31151      *
31152      * @fires TagComponent#modechanged
31153      *
31154      * @example ```tagComponent.changeMode(Mapillary.TagComponent.TagMode.CreateRect);```
31155      */
31156     TagComponent.prototype.changeMode = function (mode) {
31157         this.configure({ mode: mode });
31158     };
31159     /**
31160      * Returns the tag in the tag set with the specified id, or
31161      * undefined if the id matches no tag.
31162      *
31163      * @param {string} tagId - Id of the tag.
31164      *
31165      * @example ```var tag = tagComponent.get("tagId");```
31166      */
31167     TagComponent.prototype.get = function (tagId) {
31168         if (this._activated) {
31169             var renderTag = this._tagSet.get(tagId);
31170             return renderTag !== undefined ? renderTag.tag : undefined;
31171         }
31172         else {
31173             return this._tagSet.getDeactivated(tagId);
31174         }
31175     };
31176     /**
31177      * Returns an array of all tags.
31178      *
31179      * @example ```var tags = tagComponent.getAll();```
31180      */
31181     TagComponent.prototype.getAll = function () {
31182         if (this.activated) {
31183             return this._tagSet
31184                 .getAll()
31185                 .map(function (renderTag) {
31186                 return renderTag.tag;
31187             });
31188         }
31189         else {
31190             return this._tagSet.getAllDeactivated();
31191         }
31192     };
31193     /**
31194      * Returns an array of tag ids for tags that contain the specified point.
31195      *
31196      * @description The pixel point must lie inside the polygon or rectangle
31197      * of an added tag for the tag id to be returned. Tag ids for
31198      * tags that do not have a fill will also be returned if the point is inside
31199      * the geometry of the tag. Tags with point geometries can not be retrieved.
31200      *
31201      * No tag ids will be returned for panoramas.
31202      *
31203      * Notice that the pixelPoint argument requires x, y coordinates from pixel space.
31204      *
31205      * With this function, you can use the coordinates provided by mouse
31206      * events to get information out of the tag component.
31207      *
31208      * If no tag at exist the pixel point, an empty array will be returned.
31209      *
31210      * @param {Array<number>} pixelPoint - Pixel coordinates on the viewer element.
31211      * @returns {Array<string>} Ids of the tags that contain the specified pixel point.
31212      *
31213      * @example
31214      * ```
31215      * tagComponent.getTagIdsAt([100, 100])
31216      *     .then((tagIds) => { console.log(tagIds); });
31217      * ```
31218      */
31219     TagComponent.prototype.getTagIdsAt = function (pixelPoint) {
31220         var _this = this;
31221         return when.promise(function (resolve, reject) {
31222             _this._container.renderService.renderCamera$
31223                 .first()
31224                 .map(function (render) {
31225                 var viewport = _this._viewportCoords
31226                     .canvasToViewport(pixelPoint[0], pixelPoint[1], _this._container.element);
31227                 var ids = _this._tagScene.intersectObjects(viewport, render.perspective);
31228                 return ids;
31229             })
31230                 .subscribe(function (ids) {
31231                 resolve(ids);
31232             }, function (error) {
31233                 reject(error);
31234             });
31235         });
31236     };
31237     /**
31238      * Check if a tag exist in the tag set.
31239      *
31240      * @param {string} tagId - Id of the tag.
31241      *
31242      * @example ```var tagExists = tagComponent.has("tagId");```
31243      */
31244     TagComponent.prototype.has = function (tagId) {
31245         return this._activated ? this._tagSet.has(tagId) : this._tagSet.hasDeactivated(tagId);
31246     };
31247     /**
31248      * Remove tags with the specified ids from the tag set.
31249      *
31250      * @param {Array<string>} tagIds - Ids for tags to remove.
31251      *
31252      * @example ```tagComponent.remove(["id-1", "id-2"]);```
31253      */
31254     TagComponent.prototype.remove = function (tagIds) {
31255         if (this._activated) {
31256             this._tagSet.remove(tagIds);
31257             this._tagScene.remove(tagIds);
31258         }
31259         else {
31260             this._tagSet.removeDeactivated(tagIds);
31261         }
31262     };
31263     /**
31264      * Remove all tags from the tag set.
31265      *
31266      * @example ```tagComponent.removeAll();```
31267      */
31268     TagComponent.prototype.removeAll = function () {
31269         if (this._activated) {
31270             this._tagSet.removeAll();
31271             this._tagScene.removeAll();
31272         }
31273         else {
31274             this._tagSet.removeAllDeactivated();
31275         }
31276     };
31277     TagComponent.prototype._activate = function () {
31278         var _this = this;
31279         this._editVertexHandler.enable();
31280         var handlerGeometryCreated$ = Observable_1.Observable
31281             .from(Object.keys(this._createHandlers))
31282             .map(function (key) {
31283             return _this._createHandlers[key];
31284         })
31285             .filter(function (handler) {
31286             return !!handler;
31287         })
31288             .mergeMap(function (handler) {
31289             return handler.geometryCreated$;
31290         })
31291             .share();
31292         this._fireGeometryCreatedSubscription = handlerGeometryCreated$
31293             .subscribe(function (geometry) {
31294             _this.fire(TagComponent.geometrycreated, geometry);
31295         });
31296         this._fireCreateGeometryEventSubscription = this._tagCreator.tag$
31297             .skipWhile(function (tag) {
31298             return tag == null;
31299         })
31300             .distinctUntilChanged()
31301             .subscribe(function (tag) {
31302             var eventType = tag != null ?
31303                 TagComponent.creategeometrystart :
31304                 TagComponent.creategeometryend;
31305             _this.fire(eventType, _this);
31306         });
31307         this._handlerStopCreateSubscription = handlerGeometryCreated$
31308             .subscribe(function () {
31309             _this.changeMode(Component_1.TagMode.Default);
31310         });
31311         this._handlerEnablerSubscription = this._creatingConfiguration$
31312             .subscribe(function (configuration) {
31313             _this._disableCreateHandlers();
31314             var mode = Component_1.TagMode[configuration.mode];
31315             var handler = _this._createHandlers[mode];
31316             if (!!handler) {
31317                 handler.enable();
31318             }
31319         });
31320         this._fireTagsChangedSubscription = this._renderTags$
31321             .subscribe(function (tags) {
31322             _this.fire(TagComponent.tagschanged, _this);
31323         });
31324         this._stopCreateSubscription = this._tagCreator.tag$
31325             .switchMap(function (tag) {
31326             return tag != null ?
31327                 tag.aborted$
31328                     .map(function (t) { return null; }) :
31329                 Observable_1.Observable.empty();
31330         })
31331             .subscribe(function () { _this.changeMode(Component_1.TagMode.Default); });
31332         this._setGLCreateTagSubscription = this._tagCreator.tag$
31333             .subscribe(function (tag) {
31334             if (_this._tagScene.hasCreateTag()) {
31335                 _this._tagScene.removeCreateTag();
31336             }
31337             if (tag != null) {
31338                 _this._tagScene.addCreateTag(tag);
31339             }
31340         });
31341         this._createGLObjectsChangedSubscription = this._createGLObjectsChanged$
31342             .subscribe(function (tag) {
31343             _this._tagScene.updateCreateTagObjects(tag);
31344         });
31345         this._updateGLObjectsSubscription = this._renderTagGLChanged$
31346             .subscribe(function (tag) {
31347             _this._tagScene.updateObjects(tag);
31348         });
31349         this._updateTagSceneSubscription = this._tagChanged$
31350             .subscribe(function (tag) {
31351             _this._tagScene.update();
31352         });
31353         this._domSubscription = this._renderTags$
31354             .startWith([])
31355             .do(function (tags) {
31356             _this._container.domRenderer.render$.next({
31357                 name: _this._name,
31358                 vnode: _this._tagDomRenderer.clear(),
31359             });
31360         })
31361             .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) {
31362             return [rc, atlas, size, renderTags, tag, ct];
31363         })
31364             .map(function (args) {
31365             return {
31366                 name: _this._name,
31367                 vnode: _this._tagDomRenderer.render(args[3], args[5], args[1], args[0].perspective, args[2]),
31368             };
31369         })
31370             .subscribe(this._container.domRenderer.render$);
31371         this._glSubscription = this._navigator.stateService.currentState$
31372             .map(function (frame) {
31373             var tagScene = _this._tagScene;
31374             return {
31375                 name: _this._name,
31376                 render: {
31377                     frameId: frame.id,
31378                     needsRender: tagScene.needsRender,
31379                     render: tagScene.render.bind(tagScene),
31380                     stage: Render_1.GLRenderStage.Foreground,
31381                 },
31382             };
31383         })
31384             .subscribe(this._container.glRenderer.render$);
31385         this._navigator.stateService.currentTransform$
31386             .first()
31387             .subscribe(function (transform) {
31388             _this._tagSet.activate(transform);
31389             _this._tagScene.add(_this._tagSet.getAll());
31390         });
31391     };
31392     TagComponent.prototype._deactivate = function () {
31393         this._editVertexHandler.disable();
31394         this._disableCreateHandlers();
31395         this._tagScene.clear();
31396         this._tagSet.deactivate();
31397         this._tagCreator.delete$.next(null);
31398         this._updateGLObjectsSubscription.unsubscribe();
31399         this._updateTagSceneSubscription.unsubscribe();
31400         this._stopCreateSubscription.unsubscribe();
31401         this._setGLCreateTagSubscription.unsubscribe();
31402         this._createGLObjectsChangedSubscription.unsubscribe();
31403         this._domSubscription.unsubscribe();
31404         this._glSubscription.unsubscribe();
31405         this._fireCreateGeometryEventSubscription.unsubscribe();
31406         this._fireGeometryCreatedSubscription.unsubscribe();
31407         this._fireTagsChangedSubscription.unsubscribe();
31408         this._handlerStopCreateSubscription.unsubscribe();
31409         this._handlerEnablerSubscription.unsubscribe();
31410         this._container.element.classList.remove("component-tag-create");
31411     };
31412     TagComponent.prototype._getDefaultConfiguration = function () {
31413         return {
31414             createColor: 0xFFFFFF,
31415             mode: Component_1.TagMode.Default,
31416         };
31417     };
31418     TagComponent.prototype._disableCreateHandlers = function () {
31419         var createHandlers = this._createHandlers;
31420         for (var key in createHandlers) {
31421             if (!createHandlers.hasOwnProperty(key)) {
31422                 continue;
31423             }
31424             var handler = createHandlers[key];
31425             if (!!handler) {
31426                 handler.disable();
31427             }
31428         }
31429     };
31430     /** @inheritdoc */
31431     TagComponent.componentName = "tag";
31432     /**
31433      * Event fired when an interaction to create a geometry ends.
31434      *
31435      * @description A create interaction can by a geometry being created
31436      * or by the creation being aborted.
31437      *
31438      * @event TagComponent#creategeometryend
31439      * @type {TagComponent} Tag component.
31440      * @example
31441      * ```
31442      * tagComponent.on("creategeometryend", function(component) {
31443      *     console.log(component);
31444      * });
31445      * ```
31446      */
31447     TagComponent.creategeometryend = "creategeometryend";
31448     /**
31449      * Event fired when an interaction to create a geometry starts.
31450      *
31451      * @description A create interaction starts when the first vertex
31452      * is created in the geometry.
31453      *
31454      * @event TagComponent#creategeometrystart
31455      * @type {TagComponent} Tag component.
31456      * @example
31457      * ```
31458      * tagComponent.on("creategeometrystart", function(component) {
31459      *     console.log(component);
31460      * });
31461      * ```
31462      */
31463     TagComponent.creategeometrystart = "creategeometrystart";
31464     /**
31465      * Event fired when the create mode is changed.
31466      *
31467      * @event TagComponent#modechanged
31468      * @type {TagMode} Tag mode
31469      * @example
31470      * ```
31471      * tagComponent.on("modechanged", function(mode) {
31472      *     console.log(mode);
31473      * });
31474      * ```
31475      */
31476     TagComponent.modechanged = "modechanged";
31477     /**
31478      * Event fired when a geometry has been created.
31479      *
31480      * @event TagComponent#geometrycreated
31481      * @type {Geometry} Created geometry.
31482      * @example
31483      * ```
31484      * tagComponent.on("geometrycreated", function(geometry) {
31485      *     console.log(geometry);
31486      * });
31487      * ```
31488      */
31489     TagComponent.geometrycreated = "geometrycreated";
31490     /**
31491      * Event fired when the tags collection has changed.
31492      *
31493      * @event TagComponent#tagschanged
31494      * @type {TagComponent} Tag component.
31495      * @example
31496      * ```
31497      * tagComponent.on("tagschanged", function(component) {
31498      *     console.log(component.getAll());
31499      * });
31500      * ```
31501      */
31502     TagComponent.tagschanged = "tagschanged";
31503     return TagComponent;
31504 }(Component_1.Component));
31505 exports.TagComponent = TagComponent;
31506 Component_1.ComponentService.register(TagComponent);
31507 exports.default = TagComponent;
31508
31509 },{"../../Component":291,"../../Geo":294,"../../Render":297,"rxjs/Observable":29,"rxjs/add/observable/combineLatest":38,"rxjs/add/observable/empty":41,"rxjs/add/observable/from":42,"rxjs/add/observable/merge":45,"rxjs/add/observable/of":46,"rxjs/add/operator/combineLatest":55,"rxjs/add/operator/concat":56,"rxjs/add/operator/distinctUntilChanged":60,"rxjs/add/operator/do":61,"rxjs/add/operator/filter":63,"rxjs/add/operator/map":67,"rxjs/add/operator/merge":68,"rxjs/add/operator/mergeMap":70,"rxjs/add/operator/publishReplay":74,"rxjs/add/operator/scan":78,"rxjs/add/operator/share":79,"rxjs/add/operator/skip":80,"rxjs/add/operator/skipUntil":81,"rxjs/add/operator/startWith":83,"rxjs/add/operator/switchMap":84,"rxjs/add/operator/take":85,"rxjs/add/operator/takeUntil":86,"rxjs/add/operator/withLatestFrom":90,"when":288}],355:[function(require,module,exports){
31510 "use strict";
31511 Object.defineProperty(exports, "__esModule", { value: true });
31512 var Subject_1 = require("rxjs/Subject");
31513 require("rxjs/add/operator/map");
31514 require("rxjs/add/operator/scan");
31515 require("rxjs/add/operator/share");
31516 require("rxjs/add/operator/withLatestFrom");
31517 var Component_1 = require("../../Component");
31518 var TagCreator = /** @class */ (function () {
31519     function TagCreator(component, navigator) {
31520         this._component = component;
31521         this._navigator = navigator;
31522         this._tagOperation$ = new Subject_1.Subject();
31523         this._createPolygon$ = new Subject_1.Subject();
31524         this._createRect$ = new Subject_1.Subject();
31525         this._delete$ = new Subject_1.Subject();
31526         this._tag$ = this._tagOperation$
31527             .scan(function (tag, operation) {
31528             return operation(tag);
31529         }, null)
31530             .share();
31531         this._createRect$
31532             .withLatestFrom(this._component.configuration$, this._navigator.stateService.currentTransform$)
31533             .map(function (_a) {
31534             var coord = _a[0], conf = _a[1], transform = _a[2];
31535             return function (tag) {
31536                 var geometry = new Component_1.RectGeometry([
31537                     coord[0],
31538                     coord[1],
31539                     coord[0],
31540                     coord[1],
31541                 ]);
31542                 return new Component_1.OutlineCreateTag(geometry, { color: conf.createColor }, transform);
31543             };
31544         })
31545             .subscribe(this._tagOperation$);
31546         this._createPolygon$
31547             .withLatestFrom(this._component.configuration$, this._navigator.stateService.currentTransform$)
31548             .map(function (_a) {
31549             var coord = _a[0], conf = _a[1], transform = _a[2];
31550             return function (tag) {
31551                 var geometry = new Component_1.PolygonGeometry([
31552                     [coord[0], coord[1]],
31553                     [coord[0], coord[1]],
31554                     [coord[0], coord[1]],
31555                 ]);
31556                 return new Component_1.OutlineCreateTag(geometry, { color: conf.createColor }, transform);
31557             };
31558         })
31559             .subscribe(this._tagOperation$);
31560         this._delete$
31561             .map(function () {
31562             return function (tag) {
31563                 return null;
31564             };
31565         })
31566             .subscribe(this._tagOperation$);
31567     }
31568     Object.defineProperty(TagCreator.prototype, "createRect$", {
31569         get: function () {
31570             return this._createRect$;
31571         },
31572         enumerable: true,
31573         configurable: true
31574     });
31575     Object.defineProperty(TagCreator.prototype, "createPolygon$", {
31576         get: function () {
31577             return this._createPolygon$;
31578         },
31579         enumerable: true,
31580         configurable: true
31581     });
31582     Object.defineProperty(TagCreator.prototype, "delete$", {
31583         get: function () {
31584             return this._delete$;
31585         },
31586         enumerable: true,
31587         configurable: true
31588     });
31589     Object.defineProperty(TagCreator.prototype, "tag$", {
31590         get: function () {
31591             return this._tag$;
31592         },
31593         enumerable: true,
31594         configurable: true
31595     });
31596     return TagCreator;
31597 }());
31598 exports.TagCreator = TagCreator;
31599 exports.default = TagCreator;
31600
31601 },{"../../Component":291,"rxjs/Subject":34,"rxjs/add/operator/map":67,"rxjs/add/operator/scan":78,"rxjs/add/operator/share":79,"rxjs/add/operator/withLatestFrom":90}],356:[function(require,module,exports){
31602 "use strict";
31603 /// <reference path="../../../typings/index.d.ts" />
31604 Object.defineProperty(exports, "__esModule", { value: true });
31605 var vd = require("virtual-dom");
31606 var TagDOMRenderer = /** @class */ (function () {
31607     function TagDOMRenderer() {
31608     }
31609     TagDOMRenderer.prototype.render = function (tags, createTag, atlas, camera, size) {
31610         var vNodes = [];
31611         for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
31612             var tag = tags_1[_i];
31613             vNodes = vNodes.concat(tag.getDOMObjects(atlas, camera, size));
31614         }
31615         if (createTag != null) {
31616             vNodes = vNodes.concat(createTag.getDOMObjects(camera, size));
31617         }
31618         return vd.h("div.TagContainer", {}, vNodes);
31619     };
31620     TagDOMRenderer.prototype.clear = function () {
31621         return vd.h("div", {}, []);
31622     };
31623     return TagDOMRenderer;
31624 }());
31625 exports.TagDOMRenderer = TagDOMRenderer;
31626
31627 },{"virtual-dom":247}],357:[function(require,module,exports){
31628 "use strict";
31629 Object.defineProperty(exports, "__esModule", { value: true });
31630 /**
31631  * Enumeration for tag modes
31632  * @enum {number}
31633  * @readonly
31634  * @description Modes for the interaction in the tag component.
31635  */
31636 var TagMode;
31637 (function (TagMode) {
31638     /**
31639      * Disables creating tags.
31640      */
31641     TagMode[TagMode["Default"] = 0] = "Default";
31642     /**
31643      * Create a point geometry through a click.
31644      */
31645     TagMode[TagMode["CreatePoint"] = 1] = "CreatePoint";
31646     /**
31647      * Create a polygon geometry through clicks.
31648      */
31649     TagMode[TagMode["CreatePolygon"] = 2] = "CreatePolygon";
31650     /**
31651      * Create a rect geometry through clicks.
31652      */
31653     TagMode[TagMode["CreateRect"] = 3] = "CreateRect";
31654     /**
31655      * Create a rect geometry through drag.
31656      *
31657      * @description Claims the mouse which results in mouse handlers like
31658      * drag pan and scroll zoom becoming inactive.
31659      */
31660     TagMode[TagMode["CreateRectDrag"] = 4] = "CreateRectDrag";
31661 })(TagMode = exports.TagMode || (exports.TagMode = {}));
31662 exports.default = TagMode;
31663
31664 },{}],358:[function(require,module,exports){
31665 "use strict";
31666 Object.defineProperty(exports, "__esModule", { value: true });
31667 var TagOperation;
31668 (function (TagOperation) {
31669     TagOperation[TagOperation["None"] = 0] = "None";
31670     TagOperation[TagOperation["Centroid"] = 1] = "Centroid";
31671     TagOperation[TagOperation["Vertex"] = 2] = "Vertex";
31672 })(TagOperation = exports.TagOperation || (exports.TagOperation = {}));
31673 exports.default = TagOperation;
31674
31675 },{}],359:[function(require,module,exports){
31676 "use strict";
31677 /// <reference path="../../../typings/index.d.ts" />
31678 Object.defineProperty(exports, "__esModule", { value: true });
31679 var THREE = require("three");
31680 var TagScene = /** @class */ (function () {
31681     function TagScene(scene, raycaster) {
31682         this._createTag = null;
31683         this._needsRender = false;
31684         this._raycaster = !!raycaster ? raycaster : new THREE.Raycaster();
31685         this._scene = !!scene ? scene : new THREE.Scene();
31686         this._objectTags = {};
31687         this._retrievableObjects = [];
31688         this._tags = {};
31689     }
31690     Object.defineProperty(TagScene.prototype, "needsRender", {
31691         get: function () {
31692             return this._needsRender;
31693         },
31694         enumerable: true,
31695         configurable: true
31696     });
31697     TagScene.prototype.add = function (tags) {
31698         for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
31699             var tag = tags_1[_i];
31700             if (tag.tag.id in this._tags) {
31701                 this._remove(tag.tag.id);
31702             }
31703             this._add(tag);
31704         }
31705         this._needsRender = true;
31706     };
31707     TagScene.prototype.addCreateTag = function (tag) {
31708         for (var _i = 0, _a = tag.glObjects; _i < _a.length; _i++) {
31709             var object = _a[_i];
31710             this._scene.add(object);
31711         }
31712         this._createTag = { tag: tag, objects: tag.glObjects };
31713         this._needsRender = true;
31714     };
31715     TagScene.prototype.clear = function () {
31716         for (var _i = 0, _a = Object.keys(this._tags); _i < _a.length; _i++) {
31717             var id = _a[_i];
31718             this._remove(id);
31719         }
31720         this._needsRender = false;
31721     };
31722     TagScene.prototype.get = function (id) {
31723         return this.has(id) ? this._tags[id].tag : undefined;
31724     };
31725     TagScene.prototype.has = function (id) {
31726         return id in this._tags;
31727     };
31728     TagScene.prototype.hasCreateTag = function () {
31729         return this._createTag != null;
31730     };
31731     TagScene.prototype.intersectObjects = function (_a, camera) {
31732         var viewportX = _a[0], viewportY = _a[1];
31733         this._raycaster.setFromCamera(new THREE.Vector2(viewportX, viewportY), camera);
31734         var intersects = this._raycaster.intersectObjects(this._retrievableObjects);
31735         var intersectedIds = [];
31736         for (var _i = 0, intersects_1 = intersects; _i < intersects_1.length; _i++) {
31737             var intersect = intersects_1[_i];
31738             if (intersect.object.uuid in this._objectTags) {
31739                 intersectedIds.push(this._objectTags[intersect.object.uuid]);
31740             }
31741         }
31742         return intersectedIds;
31743     };
31744     TagScene.prototype.remove = function (ids) {
31745         for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
31746             var id = ids_1[_i];
31747             this._remove(id);
31748         }
31749         this._needsRender = true;
31750     };
31751     TagScene.prototype.removeAll = function () {
31752         for (var _i = 0, _a = Object.keys(this._tags); _i < _a.length; _i++) {
31753             var id = _a[_i];
31754             this._remove(id);
31755         }
31756         this._needsRender = true;
31757     };
31758     TagScene.prototype.removeCreateTag = function () {
31759         if (this._createTag == null) {
31760             return;
31761         }
31762         for (var _i = 0, _a = this._createTag.objects; _i < _a.length; _i++) {
31763             var object = _a[_i];
31764             this._scene.remove(object);
31765         }
31766         this._createTag.tag.dispose();
31767         this._createTag = null;
31768         this._needsRender = true;
31769     };
31770     TagScene.prototype.render = function (perspectiveCamera, renderer) {
31771         renderer.render(this._scene, perspectiveCamera);
31772         this._needsRender = false;
31773     };
31774     TagScene.prototype.update = function () {
31775         this._needsRender = true;
31776     };
31777     TagScene.prototype.updateCreateTagObjects = function (tag) {
31778         if (this._createTag.tag !== tag) {
31779             throw new Error("Create tags do not have the same reference.");
31780         }
31781         for (var _i = 0, _a = this._createTag.objects; _i < _a.length; _i++) {
31782             var object = _a[_i];
31783             this._scene.remove(object);
31784         }
31785         for (var _b = 0, _c = tag.glObjects; _b < _c.length; _b++) {
31786             var object = _c[_b];
31787             this._scene.add(object);
31788         }
31789         this._createTag.objects = tag.glObjects;
31790         this._needsRender = true;
31791     };
31792     TagScene.prototype.updateObjects = function (tag) {
31793         var id = tag.tag.id;
31794         if (this._tags[id].tag !== tag) {
31795             throw new Error("Tags do not have the same reference.");
31796         }
31797         var tagObjects = this._tags[id];
31798         this._removeObjects(tagObjects);
31799         delete this._tags[id];
31800         this._add(tag);
31801         this._needsRender = true;
31802     };
31803     TagScene.prototype._add = function (tag) {
31804         var id = tag.tag.id;
31805         var tagObjects = { tag: tag, objects: [], retrievableObjects: [] };
31806         this._tags[id] = tagObjects;
31807         for (var _i = 0, _a = tag.getGLObjects(); _i < _a.length; _i++) {
31808             var object = _a[_i];
31809             tagObjects.objects.push(object);
31810             this._scene.add(object);
31811         }
31812         for (var _b = 0, _c = tag.getRetrievableObjects(); _b < _c.length; _b++) {
31813             var retrievableObject = _c[_b];
31814             tagObjects.retrievableObjects.push(retrievableObject);
31815             this._retrievableObjects.push(retrievableObject);
31816             this._objectTags[retrievableObject.uuid] = tag.tag.id;
31817         }
31818     };
31819     TagScene.prototype._remove = function (id) {
31820         var tagObjects = this._tags[id];
31821         this._removeObjects(tagObjects);
31822         tagObjects.tag.dispose();
31823         delete this._tags[id];
31824     };
31825     TagScene.prototype._removeObjects = function (tagObjects) {
31826         for (var _i = 0, _a = tagObjects.objects; _i < _a.length; _i++) {
31827             var object = _a[_i];
31828             this._scene.remove(object);
31829         }
31830         for (var _b = 0, _c = tagObjects.retrievableObjects; _b < _c.length; _b++) {
31831             var retrievableObject = _c[_b];
31832             var index = this._retrievableObjects.indexOf(retrievableObject);
31833             if (index !== -1) {
31834                 this._retrievableObjects.splice(index, 1);
31835             }
31836         }
31837     };
31838     return TagScene;
31839 }());
31840 exports.TagScene = TagScene;
31841 exports.default = TagScene;
31842
31843 },{"three":241}],360:[function(require,module,exports){
31844 "use strict";
31845 Object.defineProperty(exports, "__esModule", { value: true });
31846 var Subject_1 = require("rxjs/Subject");
31847 require("rxjs/add/operator/map");
31848 require("rxjs/add/operator/scan");
31849 require("rxjs/add/operator/share");
31850 var Component_1 = require("../../Component");
31851 var TagSet = /** @class */ (function () {
31852     function TagSet() {
31853         this._active = false;
31854         this._hash = {};
31855         this._hashDeactivated = {};
31856         this._notifyChanged$ = new Subject_1.Subject();
31857     }
31858     Object.defineProperty(TagSet.prototype, "active", {
31859         get: function () {
31860             return this._active;
31861         },
31862         enumerable: true,
31863         configurable: true
31864     });
31865     Object.defineProperty(TagSet.prototype, "changed$", {
31866         get: function () {
31867             return this._notifyChanged$;
31868         },
31869         enumerable: true,
31870         configurable: true
31871     });
31872     TagSet.prototype.activate = function (transform) {
31873         if (this._active) {
31874             return;
31875         }
31876         for (var id in this._hashDeactivated) {
31877             if (!this._hashDeactivated.hasOwnProperty(id)) {
31878                 continue;
31879             }
31880             var tag = this._hashDeactivated[id];
31881             this._add(tag, transform);
31882         }
31883         this._hashDeactivated = {};
31884         this._active = true;
31885         this._notifyChanged$.next(this);
31886     };
31887     TagSet.prototype.deactivate = function () {
31888         if (!this._active) {
31889             return;
31890         }
31891         for (var id in this._hash) {
31892             if (!this._hash.hasOwnProperty(id)) {
31893                 continue;
31894             }
31895             this._hashDeactivated[id] = this._hash[id].tag;
31896         }
31897         this._hash = {};
31898         this._active = false;
31899     };
31900     TagSet.prototype.add = function (tags, transform) {
31901         this._assertActivationState(true);
31902         for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
31903             var tag = tags_1[_i];
31904             this._add(tag, transform);
31905         }
31906         this._notifyChanged$.next(this);
31907     };
31908     TagSet.prototype.addDeactivated = function (tags) {
31909         this._assertActivationState(false);
31910         for (var _i = 0, tags_2 = tags; _i < tags_2.length; _i++) {
31911             var tag = tags_2[_i];
31912             if (!(tag instanceof Component_1.OutlineTag || tag instanceof Component_1.SpotTag)) {
31913                 throw new Error("Tag type not supported");
31914             }
31915             this._hashDeactivated[tag.id] = tag;
31916         }
31917     };
31918     TagSet.prototype.get = function (id) {
31919         return this.has(id) ? this._hash[id] : undefined;
31920     };
31921     TagSet.prototype.getAll = function () {
31922         var hash = this._hash;
31923         return Object.keys(hash)
31924             .map(function (id) {
31925             return hash[id];
31926         });
31927     };
31928     TagSet.prototype.getAllDeactivated = function () {
31929         var hashDeactivated = this._hashDeactivated;
31930         return Object.keys(hashDeactivated)
31931             .map(function (id) {
31932             return hashDeactivated[id];
31933         });
31934     };
31935     TagSet.prototype.getDeactivated = function (id) {
31936         return this.hasDeactivated(id) ? this._hashDeactivated[id] : undefined;
31937     };
31938     TagSet.prototype.has = function (id) {
31939         return id in this._hash;
31940     };
31941     TagSet.prototype.hasDeactivated = function (id) {
31942         return id in this._hashDeactivated;
31943     };
31944     TagSet.prototype.remove = function (ids) {
31945         this._assertActivationState(true);
31946         var hash = this._hash;
31947         for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
31948             var id = ids_1[_i];
31949             if (!(id in hash)) {
31950                 continue;
31951             }
31952             delete hash[id];
31953         }
31954         this._notifyChanged$.next(this);
31955     };
31956     TagSet.prototype.removeAll = function () {
31957         this._assertActivationState(true);
31958         this._hash = {};
31959         this._notifyChanged$.next(this);
31960     };
31961     TagSet.prototype.removeAllDeactivated = function () {
31962         this._assertActivationState(false);
31963         this._hashDeactivated = {};
31964     };
31965     TagSet.prototype.removeDeactivated = function (ids) {
31966         this._assertActivationState(false);
31967         var hashDeactivated = this._hashDeactivated;
31968         for (var _i = 0, ids_2 = ids; _i < ids_2.length; _i++) {
31969             var id = ids_2[_i];
31970             if (!(id in hashDeactivated)) {
31971                 continue;
31972             }
31973             delete hashDeactivated[id];
31974         }
31975     };
31976     TagSet.prototype._add = function (tag, transform) {
31977         if (tag instanceof Component_1.OutlineTag) {
31978             this._hash[tag.id] = new Component_1.OutlineRenderTag(tag, transform);
31979         }
31980         else if (tag instanceof Component_1.SpotTag) {
31981             this._hash[tag.id] = new Component_1.SpotRenderTag(tag, transform);
31982         }
31983         else {
31984             throw new Error("Tag type not supported");
31985         }
31986     };
31987     TagSet.prototype._assertActivationState = function (should) {
31988         if (should !== this._active) {
31989             throw new Error("Tag set not in correct state for operation.");
31990         }
31991     };
31992     return TagSet;
31993 }());
31994 exports.TagSet = TagSet;
31995 exports.default = TagSet;
31996
31997 },{"../../Component":291,"rxjs/Subject":34,"rxjs/add/operator/map":67,"rxjs/add/operator/scan":78,"rxjs/add/operator/share":79}],361:[function(require,module,exports){
31998 "use strict";
31999 var __extends = (this && this.__extends) || (function () {
32000     var extendStatics = Object.setPrototypeOf ||
32001         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32002         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
32003     return function (d, b) {
32004         extendStatics(d, b);
32005         function __() { this.constructor = d; }
32006         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32007     };
32008 })();
32009 Object.defineProperty(exports, "__esModule", { value: true });
32010 var Error_1 = require("../../../Error");
32011 var GeometryTagError = /** @class */ (function (_super) {
32012     __extends(GeometryTagError, _super);
32013     function GeometryTagError(message) {
32014         var _this = _super.call(this, message != null ? message : "The provided geometry value is incorrect") || this;
32015         _this.name = "GeometryTagError";
32016         return _this;
32017     }
32018     return GeometryTagError;
32019 }(Error_1.MapillaryError));
32020 exports.GeometryTagError = GeometryTagError;
32021 exports.default = Error_1.MapillaryError;
32022
32023 },{"../../../Error":293}],362:[function(require,module,exports){
32024 "use strict";
32025 Object.defineProperty(exports, "__esModule", { value: true });
32026 var Subject_1 = require("rxjs/Subject");
32027 /**
32028  * @class Geometry
32029  * @abstract
32030  * @classdesc Represents a geometry.
32031  */
32032 var Geometry = /** @class */ (function () {
32033     /**
32034      * Create a geometry.
32035      *
32036      * @constructor
32037      */
32038     function Geometry() {
32039         this._notifyChanged$ = new Subject_1.Subject();
32040     }
32041     Object.defineProperty(Geometry.prototype, "changed$", {
32042         /**
32043          * Get changed observable.
32044          *
32045          * @description Emits the geometry itself every time the geometry
32046          * has changed.
32047          *
32048          * @returns {Observable<Geometry>} Observable emitting the geometry instance.
32049          * @ignore
32050          */
32051         get: function () {
32052             return this._notifyChanged$;
32053         },
32054         enumerable: true,
32055         configurable: true
32056     });
32057     return Geometry;
32058 }());
32059 exports.Geometry = Geometry;
32060 exports.default = Geometry;
32061
32062 },{"rxjs/Subject":34}],363:[function(require,module,exports){
32063 "use strict";
32064 var __extends = (this && this.__extends) || (function () {
32065     var extendStatics = Object.setPrototypeOf ||
32066         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32067         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
32068     return function (d, b) {
32069         extendStatics(d, b);
32070         function __() { this.constructor = d; }
32071         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32072     };
32073 })();
32074 Object.defineProperty(exports, "__esModule", { value: true });
32075 var Component_1 = require("../../../Component");
32076 /**
32077  * @class PointGeometry
32078  *
32079  * @classdesc Represents a point geometry in the 2D basic image coordinate system.
32080  *
32081  * @example
32082  * ```
32083  * var basicPoint = [0.5, 0.7];
32084  * var pointGeometry = new Mapillary.TagComponent.PointGeometry(basicPoint);
32085  * ```
32086  */
32087 var PointGeometry = /** @class */ (function (_super) {
32088     __extends(PointGeometry, _super);
32089     /**
32090      * Create a point geometry.
32091      *
32092      * @constructor
32093      * @param {Array<number>} point - An array representing the basic coordinates of
32094      * the point.
32095      *
32096      * @throws {GeometryTagError} Point coordinates must be valid basic coordinates.
32097      */
32098     function PointGeometry(point) {
32099         var _this = _super.call(this) || this;
32100         var x = point[0];
32101         var y = point[1];
32102         if (x < 0 || x > 1 || y < 0 || y > 1) {
32103             throw new Component_1.GeometryTagError("Basic coordinates must be on the interval [0, 1].");
32104         }
32105         _this._point = point.slice();
32106         return _this;
32107     }
32108     Object.defineProperty(PointGeometry.prototype, "point", {
32109         /**
32110          * Get point property.
32111          * @returns {Array<number>} Array representing the basic coordinates of the point.
32112          */
32113         get: function () {
32114             return this._point;
32115         },
32116         enumerable: true,
32117         configurable: true
32118     });
32119     /**
32120      * Get the 2D basic coordinates for the centroid of the point, i.e. the 2D
32121      * basic coordinates of the point itself.
32122      *
32123      * @returns {Array<number>} 2D basic coordinates representing the centroid.
32124      */
32125     PointGeometry.prototype.getCentroid2d = function () {
32126         return this._point.slice();
32127     };
32128     /**
32129      * Get the 3D world coordinates for the centroid of the point, i.e. the 3D
32130      * world coordinates of the point itself.
32131      *
32132      * @param {Transform} transform - The transform of the node related to the point.
32133      * @returns {Array<number>} 3D world coordinates representing the centroid.
32134      */
32135     PointGeometry.prototype.getCentroid3d = function (transform) {
32136         return transform.unprojectBasic(this._point, 200);
32137     };
32138     /**
32139      * Set the centroid of the point, i.e. the point coordinates.
32140      *
32141      * @param {Array<number>} value - The new value of the centroid.
32142      * @param {Transform} transform - The transform of the node related to the point.
32143      */
32144     PointGeometry.prototype.setCentroid2d = function (value, transform) {
32145         var changed = [
32146             Math.max(0, Math.min(1, value[0])),
32147             Math.max(0, Math.min(1, value[1])),
32148         ];
32149         this._point[0] = changed[0];
32150         this._point[1] = changed[1];
32151         this._notifyChanged$.next(this);
32152     };
32153     return PointGeometry;
32154 }(Component_1.Geometry));
32155 exports.PointGeometry = PointGeometry;
32156
32157 },{"../../../Component":291}],364:[function(require,module,exports){
32158 "use strict";
32159 var __extends = (this && this.__extends) || (function () {
32160     var extendStatics = Object.setPrototypeOf ||
32161         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32162         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
32163     return function (d, b) {
32164         extendStatics(d, b);
32165         function __() { this.constructor = d; }
32166         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32167     };
32168 })();
32169 Object.defineProperty(exports, "__esModule", { value: true });
32170 var Component_1 = require("../../../Component");
32171 /**
32172  * @class PolygonGeometry
32173  *
32174  * @classdesc Represents a polygon geometry in the 2D basic image coordinate system.
32175  * All polygons and holes provided to the constructor needs to be closed.
32176  *
32177  * @example
32178  * ```
32179  * var basicPolygon = [[0.5, 0.3], [0.7, 0.3], [0.6, 0.5], [0.5, 0.3]];
32180  * var polygonGeometry = new Mapillary.TagComponent.PointGeometry(basicPolygon);
32181  * ```
32182  */
32183 var PolygonGeometry = /** @class */ (function (_super) {
32184     __extends(PolygonGeometry, _super);
32185     /**
32186      * Create a polygon geometry.
32187      *
32188      * @constructor
32189      * @param {Array<Array<number>>} polygon - Array of polygon vertices. Must be closed.
32190      * @param {Array<Array<Array<number>>>} [holes] - Array of arrays of hole vertices.
32191      * Each array of holes vertices must be closed.
32192      *
32193      * @throws {GeometryTagError} Polygon coordinates must be valid basic coordinates.
32194      */
32195     function PolygonGeometry(polygon, holes) {
32196         var _this = _super.call(this) || this;
32197         var polygonLength = polygon.length;
32198         if (polygonLength < 3) {
32199             throw new Component_1.GeometryTagError("A polygon must have three or more positions.");
32200         }
32201         if (polygon[0][0] !== polygon[polygonLength - 1][0] ||
32202             polygon[0][1] !== polygon[polygonLength - 1][1]) {
32203             throw new Component_1.GeometryTagError("First and last positions must be equivalent.");
32204         }
32205         _this._polygon = [];
32206         for (var _i = 0, polygon_1 = polygon; _i < polygon_1.length; _i++) {
32207             var vertex = polygon_1[_i];
32208             if (vertex[0] < 0 || vertex[0] > 1 ||
32209                 vertex[1] < 0 || vertex[1] > 1) {
32210                 throw new Component_1.GeometryTagError("Basic coordinates of polygon must be on the interval [0, 1].");
32211             }
32212             _this._polygon.push(vertex.slice());
32213         }
32214         _this._holes = [];
32215         if (holes == null) {
32216             return _this;
32217         }
32218         for (var i = 0; i < holes.length; i++) {
32219             var hole = holes[i];
32220             var holeLength = hole.length;
32221             if (holeLength < 3) {
32222                 throw new Component_1.GeometryTagError("A polygon hole must have three or more positions.");
32223             }
32224             if (hole[0][0] !== hole[holeLength - 1][0] ||
32225                 hole[0][1] !== hole[holeLength - 1][1]) {
32226                 throw new Component_1.GeometryTagError("First and last positions of hole must be equivalent.");
32227             }
32228             _this._holes.push([]);
32229             for (var _a = 0, hole_1 = hole; _a < hole_1.length; _a++) {
32230                 var vertex = hole_1[_a];
32231                 if (vertex[0] < 0 || vertex[0] > 1 ||
32232                     vertex[1] < 0 || vertex[1] > 1) {
32233                     throw new Component_1.GeometryTagError("Basic coordinates of hole must be on the interval [0, 1].");
32234                 }
32235                 _this._holes[i].push(vertex.slice());
32236             }
32237         }
32238         return _this;
32239     }
32240     Object.defineProperty(PolygonGeometry.prototype, "polygon", {
32241         /**
32242          * Get polygon property.
32243          * @returns {Array<Array<number>>} Closed 2d polygon.
32244          */
32245         get: function () {
32246             return this._polygon;
32247         },
32248         enumerable: true,
32249         configurable: true
32250     });
32251     Object.defineProperty(PolygonGeometry.prototype, "holes", {
32252         /**
32253          * Get holes property.
32254          * @returns {Array<Array<Array<number>>>} Holes of 2d polygon.
32255          */
32256         get: function () {
32257             return this._holes;
32258         },
32259         enumerable: true,
32260         configurable: true
32261     });
32262     /**
32263      * Add a vertex to the polygon by appending it after the last vertex.
32264      *
32265      * @param {Array<number>} vertex - Vertex to add.
32266      */
32267     PolygonGeometry.prototype.addVertex2d = function (vertex) {
32268         var clamped = [
32269             Math.max(0, Math.min(1, vertex[0])),
32270             Math.max(0, Math.min(1, vertex[1])),
32271         ];
32272         this._polygon.splice(this._polygon.length - 1, 0, clamped);
32273         this._notifyChanged$.next(this);
32274     };
32275     /**
32276      * Get the coordinates of a vertex from the polygon representation of the geometry.
32277      *
32278      * @description The first vertex represents the bottom-left corner with the rest of
32279      * the vertices following in clockwise order.
32280      *
32281      * @param {number} index - Vertex index.
32282      * @returns {Array<number>} Array representing the 2D basic coordinates of the vertex.
32283      */
32284     PolygonGeometry.prototype.getVertex2d = function (index) {
32285         return this._polygon[index].slice();
32286     };
32287     /**
32288      * Remove a vertex from the polygon.
32289      *
32290      * @param {number} index - The index of the vertex to remove.
32291      */
32292     PolygonGeometry.prototype.removeVertex2d = function (index) {
32293         if (index < 0 ||
32294             index >= this._polygon.length ||
32295             this._polygon.length < 4) {
32296             throw new Component_1.GeometryTagError("Index for removed vertex must be valid.");
32297         }
32298         if (index > 0 && index < this._polygon.length - 1) {
32299             this._polygon.splice(index, 1);
32300         }
32301         else {
32302             this._polygon.splice(0, 1);
32303             this._polygon.pop();
32304             var closing = this._polygon[0].slice();
32305             this._polygon.push(closing);
32306         }
32307         this._notifyChanged$.next(this);
32308     };
32309     /** @inheritdoc */
32310     PolygonGeometry.prototype.setVertex2d = function (index, value, transform) {
32311         var changed = [
32312             Math.max(0, Math.min(1, value[0])),
32313             Math.max(0, Math.min(1, value[1])),
32314         ];
32315         if (index === 0 || index === this._polygon.length - 1) {
32316             this._polygon[0] = changed.slice();
32317             this._polygon[this._polygon.length - 1] = changed.slice();
32318         }
32319         else {
32320             this._polygon[index] = changed.slice();
32321         }
32322         this._notifyChanged$.next(this);
32323     };
32324     /** @inheritdoc */
32325     PolygonGeometry.prototype.setCentroid2d = function (value, transform) {
32326         var xs = this._polygon.map(function (point) { return point[0]; });
32327         var ys = this._polygon.map(function (point) { return point[1]; });
32328         var minX = Math.min.apply(Math, xs);
32329         var maxX = Math.max.apply(Math, xs);
32330         var minY = Math.min.apply(Math, ys);
32331         var maxY = Math.max.apply(Math, ys);
32332         var centroid = this.getCentroid2d();
32333         var minTranslationX = -minX;
32334         var maxTranslationX = 1 - maxX;
32335         var minTranslationY = -minY;
32336         var maxTranslationY = 1 - maxY;
32337         var translationX = Math.max(minTranslationX, Math.min(maxTranslationX, value[0] - centroid[0]));
32338         var translationY = Math.max(minTranslationY, Math.min(maxTranslationY, value[1] - centroid[1]));
32339         for (var _i = 0, _a = this._polygon; _i < _a.length; _i++) {
32340             var point = _a[_i];
32341             point[0] += translationX;
32342             point[1] += translationY;
32343         }
32344         this._notifyChanged$.next(this);
32345     };
32346     /** @inheritdoc */
32347     PolygonGeometry.prototype.getPoints3d = function (transform) {
32348         return this.getVertices3d(transform);
32349     };
32350     /** @inheritdoc */
32351     PolygonGeometry.prototype.getVertex3d = function (index, transform) {
32352         return transform.unprojectBasic(this._polygon[index], 200);
32353     };
32354     /** @inheritdoc */
32355     PolygonGeometry.prototype.getVertices2d = function () {
32356         return this._polygon.slice();
32357     };
32358     /** @inheritdoc */
32359     PolygonGeometry.prototype.getVertices3d = function (transform) {
32360         return this._polygon
32361             .map(function (point) {
32362             return transform.unprojectBasic(point, 200);
32363         });
32364     };
32365     /**
32366      * Get a polygon representation of the 3D coordinates for the vertices of each hole
32367      * of the geometry.
32368      *
32369      * @param {Transform} transform - The transform of the node related to the geometry.
32370      * @returns {Array<Array<Array<number>>>} Array of hole polygons in 3D world coordinates
32371      * representing the vertices of each hole of the geometry.
32372      */
32373     PolygonGeometry.prototype.getHoleVertices3d = function (transform) {
32374         var holes3d = [];
32375         for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
32376             var hole = _a[_i];
32377             var hole3d = hole
32378                 .map(function (point) {
32379                 return transform.unprojectBasic(point, 200);
32380             });
32381             holes3d.push(hole3d);
32382         }
32383         return holes3d;
32384     };
32385     /** @inheritdoc */
32386     PolygonGeometry.prototype.getCentroid2d = function () {
32387         var polygon = this._polygon;
32388         var area = 0;
32389         var centroidX = 0;
32390         var centroidY = 0;
32391         for (var i = 0; i < polygon.length - 1; i++) {
32392             var xi = polygon[i][0];
32393             var yi = polygon[i][1];
32394             var xi1 = polygon[i + 1][0];
32395             var yi1 = polygon[i + 1][1];
32396             var a = xi * yi1 - xi1 * yi;
32397             area += a;
32398             centroidX += (xi + xi1) * a;
32399             centroidY += (yi + yi1) * a;
32400         }
32401         area /= 2;
32402         centroidX /= 6 * area;
32403         centroidY /= 6 * area;
32404         return [centroidX, centroidY];
32405     };
32406     /** @inheritdoc */
32407     PolygonGeometry.prototype.getCentroid3d = function (transform) {
32408         var centroid2d = this.getCentroid2d();
32409         return transform.unprojectBasic(centroid2d, 200);
32410     };
32411     /** @inheritdoc */
32412     PolygonGeometry.prototype.getTriangles3d = function (transform) {
32413         return this._triangulate(this._polygon, this.getPoints3d(transform), this._holes, this.getHoleVertices3d(transform));
32414     };
32415     /** @inheritdoc */
32416     PolygonGeometry.prototype.getPoleOfAccessibility2d = function () {
32417         return this._getPoleOfInaccessibility2d(this._polygon.slice());
32418     };
32419     /** @inheritdoc */
32420     PolygonGeometry.prototype.getPoleOfAccessibility3d = function (transform) {
32421         var pole2d = this._getPoleOfInaccessibility2d(this._polygon.slice());
32422         return transform.unprojectBasic(pole2d, 200);
32423     };
32424     return PolygonGeometry;
32425 }(Component_1.VertexGeometry));
32426 exports.PolygonGeometry = PolygonGeometry;
32427 exports.default = PolygonGeometry;
32428
32429 },{"../../../Component":291}],365:[function(require,module,exports){
32430 "use strict";
32431 var __extends = (this && this.__extends) || (function () {
32432     var extendStatics = Object.setPrototypeOf ||
32433         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
32434         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
32435     return function (d, b) {
32436         extendStatics(d, b);
32437         function __() { this.constructor = d; }
32438         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32439     };
32440 })();
32441 Object.defineProperty(exports, "__esModule", { value: true });
32442 var Component_1 = require("../../../Component");
32443 /**
32444  * @class RectGeometry
32445  *
32446  * @classdesc Represents a rectangle geometry in the 2D basic image coordinate system.
32447  *
32448  * @example
32449  * ```
32450  * var basicRect = [0.5, 0.3, 0.7, 0.4];
32451  * var rectGeometry = new Mapillary.TagComponent.RectGeometry(basicRect);
32452  * ```
32453  */
32454 var RectGeometry = /** @class */ (function (_super) {
32455     __extends(RectGeometry, _super);
32456     /**
32457      * Create a rectangle geometry.
32458      *
32459      * @constructor
32460      * @param {Array<number>} rect - An array representing the top-left and bottom-right
32461      * corners of the rectangle in basic coordinates. Ordered according to [x0, y0, x1, y1].
32462      *
32463      * @throws {GeometryTagError} Rectangle coordinates must be valid basic coordinates.
32464      */
32465     function RectGeometry(rect) {
32466         var _this = _super.call(this) || this;
32467         if (rect[1] > rect[3]) {
32468             throw new Component_1.GeometryTagError("Basic Y coordinates values can not be inverted.");
32469         }
32470         for (var _i = 0, rect_1 = rect; _i < rect_1.length; _i++) {
32471             var coord = rect_1[_i];
32472             if (coord < 0 || coord > 1) {
32473                 throw new Component_1.GeometryTagError("Basic coordinates must be on the interval [0, 1].");
32474             }
32475         }
32476         _this._anchorIndex = undefined;
32477         _this._rect = rect.slice(0, 4);
32478         _this._inverted = _this._rect[0] > _this._rect[2];
32479         return _this;
32480     }
32481     Object.defineProperty(RectGeometry.prototype, "anchorIndex", {
32482         /**
32483          * Get anchor index property.
32484          *
32485          * @returns {number} Index representing the current anchor property if
32486          * achoring indexing has been initialized. If anchor indexing has not been
32487          * initialized or has been terminated undefined will be returned.
32488          */
32489         get: function () {
32490             return this._anchorIndex;
32491         },
32492         enumerable: true,
32493         configurable: true
32494     });
32495     Object.defineProperty(RectGeometry.prototype, "inverted", {
32496         /**
32497          * Get inverted property.
32498          *
32499          * @returns {boolean} Boolean determining whether the rect geometry is
32500          * inverted. For panoramas the rect geometrye may be inverted.
32501          */
32502         get: function () {
32503             return this._inverted;
32504         },
32505         enumerable: true,
32506         configurable: true
32507     });
32508     Object.defineProperty(RectGeometry.prototype, "rect", {
32509         /**
32510          * Get rect property.
32511          *
32512          * @returns {Array<number>} Array representing the top-left and bottom-right
32513          * corners of the rectangle in basic coordinates.
32514          */
32515         get: function () {
32516             return this._rect;
32517         },
32518         enumerable: true,
32519         configurable: true
32520     });
32521     /**
32522      * Initialize anchor indexing to enable setting opposite vertex.
32523      *
32524      * @param {number} [index] - The index of the vertex to use as anchor.
32525      *
32526      * @throws {Error} If anchor indexing has already been initialized.
32527      * @throws {Error} If index is not valid (0 to 3).
32528      */
32529     RectGeometry.prototype.initializeAnchorIndexing = function (index) {
32530         if (this._anchorIndex !== undefined) {
32531             throw new Error("Anchor indexing is already initialized.");
32532         }
32533         if (index < 0 || index > 3) {
32534             throw new Error("Invalid anchor index: " + index + ".");
32535         }
32536         this._anchorIndex = index === undefined ? 0 : index;
32537     };
32538     /**
32539      * Terminate anchor indexing to disable setting pposite vertex.
32540      */
32541     RectGeometry.prototype.terminateAnchorIndexing = function () {
32542         this._anchorIndex = undefined;
32543     };
32544     /**
32545      * Set the value of the vertex opposite to the anchor in the polygon
32546      * representation of the rectangle.
32547      *
32548      * @description Setting the opposite vertex may change the anchor index.
32549      *
32550      * @param {Array<number>} opposite - The new value of the vertex opposite to the anchor.
32551      * @param {Transform} transform - The transform of the node related to the rectangle.
32552      *
32553      * @throws {Error} When anchor indexing has not been initialized.
32554      */
32555     RectGeometry.prototype.setOppositeVertex2d = function (opposite, transform) {
32556         if (this._anchorIndex === undefined) {
32557             throw new Error("Anchor indexing needs to be initialized.");
32558         }
32559         var changed = [
32560             Math.max(0, Math.min(1, opposite[0])),
32561             Math.max(0, Math.min(1, opposite[1])),
32562         ];
32563         var original = this._rect.slice();
32564         var anchor = this._anchorIndex === 0 ? [original[0], original[3]] :
32565             this._anchorIndex === 1 ? [original[0], original[1]] :
32566                 this._anchorIndex === 2 ? [original[2], original[1]] :
32567                     [original[2], original[3]];
32568         if (transform.fullPano) {
32569             var deltaX = this._anchorIndex < 2 ?
32570                 changed[0] - original[2] :
32571                 changed[0] - original[0];
32572             if (!this._inverted && this._anchorIndex < 2 && changed[0] < 0.25 && original[2] > 0.75 && deltaX < -0.5) {
32573                 // right side passes boundary rightward
32574                 this._inverted = true;
32575                 this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
32576             }
32577             else if (!this._inverted && this._anchorIndex >= 2 && changed[0] < 0.25 && original[2] > 0.75 && deltaX < -0.5) {
32578                 // left side passes right side and boundary rightward
32579                 this._inverted = true;
32580                 this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
32581             }
32582             else if (this._inverted && this._anchorIndex >= 2 && changed[0] < 0.25 && original[0] > 0.75 && deltaX < -0.5) {
32583                 this._inverted = false;
32584                 if (anchor[0] > changed[0]) {
32585                     // left side passes boundary rightward
32586                     this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
32587                 }
32588                 else {
32589                     // left side passes right side and boundary rightward
32590                     this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
32591                 }
32592             }
32593             else if (!this._inverted && this._anchorIndex >= 2 && changed[0] > 0.75 && original[0] < 0.25 && deltaX > 0.5) {
32594                 // left side passes boundary leftward
32595                 this._inverted = true;
32596                 this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
32597             }
32598             else if (!this._inverted && this._anchorIndex < 2 && changed[0] > 0.75 && original[0] < 0.25 && deltaX > 0.5) {
32599                 // right side passes left side and boundary leftward
32600                 this._inverted = true;
32601                 this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
32602             }
32603             else if (this._inverted && this._anchorIndex < 2 && changed[0] > 0.75 && original[2] < 0.25 && deltaX > 0.5) {
32604                 this._inverted = false;
32605                 if (anchor[0] > changed[0]) {
32606                     // right side passes boundary leftward
32607                     this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
32608                 }
32609                 else {
32610                     // right side passes left side and boundary leftward
32611                     this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
32612                 }
32613             }
32614             else if (this._inverted && this._anchorIndex < 2 && changed[0] > original[0]) {
32615                 // inverted and right side passes left side completing a loop
32616                 this._inverted = false;
32617                 this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
32618             }
32619             else if (this._inverted && this._anchorIndex >= 2 && changed[0] < original[2]) {
32620                 // inverted and left side passes right side completing a loop
32621                 this._inverted = false;
32622                 this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
32623             }
32624             else if (this._inverted) {
32625                 // if still inverted only top and bottom can switch
32626                 if (this._anchorIndex < 2) {
32627                     this._anchorIndex = anchor[1] > changed[1] ? 0 : 1;
32628                 }
32629                 else {
32630                     this._anchorIndex = anchor[1] > changed[1] ? 3 : 2;
32631                 }
32632             }
32633             else {
32634                 // if still not inverted treat as non full pano
32635                 if (anchor[0] <= changed[0] && anchor[1] > changed[1]) {
32636                     this._anchorIndex = 0;
32637                 }
32638                 else if (anchor[0] <= changed[0] && anchor[1] <= changed[1]) {
32639                     this._anchorIndex = 1;
32640                 }
32641                 else if (anchor[0] > changed[0] && anchor[1] <= changed[1]) {
32642                     this._anchorIndex = 2;
32643                 }
32644                 else {
32645                     this._anchorIndex = 3;
32646                 }
32647             }
32648             var rect = [];
32649             if (this._anchorIndex === 0) {
32650                 rect[0] = anchor[0];
32651                 rect[1] = changed[1];
32652                 rect[2] = changed[0];
32653                 rect[3] = anchor[1];
32654             }
32655             else if (this._anchorIndex === 1) {
32656                 rect[0] = anchor[0];
32657                 rect[1] = anchor[1];
32658                 rect[2] = changed[0];
32659                 rect[3] = changed[1];
32660             }
32661             else if (this._anchorIndex === 2) {
32662                 rect[0] = changed[0];
32663                 rect[1] = anchor[1];
32664                 rect[2] = anchor[0];
32665                 rect[3] = changed[1];
32666             }
32667             else {
32668                 rect[0] = changed[0];
32669                 rect[1] = changed[1];
32670                 rect[2] = anchor[0];
32671                 rect[3] = anchor[1];
32672             }
32673             if (!this._inverted && rect[0] > rect[2] ||
32674                 this._inverted && rect[0] < rect[2]) {
32675                 rect[0] = original[0];
32676                 rect[2] = original[2];
32677             }
32678             if (rect[1] > rect[3]) {
32679                 rect[1] = original[1];
32680                 rect[3] = original[3];
32681             }
32682             this._rect[0] = rect[0];
32683             this._rect[1] = rect[1];
32684             this._rect[2] = rect[2];
32685             this._rect[3] = rect[3];
32686         }
32687         else {
32688             if (anchor[0] <= changed[0] && anchor[1] > changed[1]) {
32689                 this._anchorIndex = 0;
32690             }
32691             else if (anchor[0] <= changed[0] && anchor[1] <= changed[1]) {
32692                 this._anchorIndex = 1;
32693             }
32694             else if (anchor[0] > changed[0] && anchor[1] <= changed[1]) {
32695                 this._anchorIndex = 2;
32696             }
32697             else {
32698                 this._anchorIndex = 3;
32699             }
32700             var rect = [];
32701             if (this._anchorIndex === 0) {
32702                 rect[0] = anchor[0];
32703                 rect[1] = changed[1];
32704                 rect[2] = changed[0];
32705                 rect[3] = anchor[1];
32706             }
32707             else if (this._anchorIndex === 1) {
32708                 rect[0] = anchor[0];
32709                 rect[1] = anchor[1];
32710                 rect[2] = changed[0];
32711                 rect[3] = changed[1];
32712             }
32713             else if (this._anchorIndex === 2) {
32714                 rect[0] = changed[0];
32715                 rect[1] = anchor[1];
32716                 rect[2] = anchor[0];
32717                 rect[3] = changed[1];
32718             }
32719             else {
32720                 rect[0] = changed[0];
32721                 rect[1] = changed[1];
32722                 rect[2] = anchor[0];
32723                 rect[3] = anchor[1];
32724             }
32725             if (rect[0] > rect[2]) {
32726                 rect[0] = original[0];
32727                 rect[2] = original[2];
32728             }
32729             if (rect[1] > rect[3]) {
32730                 rect[1] = original[1];
32731                 rect[3] = original[3];
32732             }
32733             this._rect[0] = rect[0];
32734             this._rect[1] = rect[1];
32735             this._rect[2] = rect[2];
32736             this._rect[3] = rect[3];
32737         }
32738         this._notifyChanged$.next(this);
32739     };
32740     /**
32741      * Set the value of a vertex in the polygon representation of the rectangle.
32742      *
32743      * @description The polygon is defined to have the first vertex at the
32744      * bottom-left corner with the rest of the vertices following in clockwise order.
32745      *
32746      * @param {number} index - The index of the vertex to be set.
32747      * @param {Array<number>} value - The new value of the vertex.
32748      * @param {Transform} transform - The transform of the node related to the rectangle.
32749      */
32750     RectGeometry.prototype.setVertex2d = function (index, value, transform) {
32751         var original = this._rect.slice();
32752         var changed = [
32753             Math.max(0, Math.min(1, value[0])),
32754             Math.max(0, Math.min(1, value[1])),
32755         ];
32756         var rect = [];
32757         if (index === 0) {
32758             rect[0] = changed[0];
32759             rect[1] = original[1];
32760             rect[2] = original[2];
32761             rect[3] = changed[1];
32762         }
32763         else if (index === 1) {
32764             rect[0] = changed[0];
32765             rect[1] = changed[1];
32766             rect[2] = original[2];
32767             rect[3] = original[3];
32768         }
32769         else if (index === 2) {
32770             rect[0] = original[0];
32771             rect[1] = changed[1];
32772             rect[2] = changed[0];
32773             rect[3] = original[3];
32774         }
32775         else if (index === 3) {
32776             rect[0] = original[0];
32777             rect[1] = original[1];
32778             rect[2] = changed[0];
32779             rect[3] = changed[1];
32780         }
32781         if (transform.fullPano) {
32782             var passingBoundaryLeftward = index < 2 && changed[0] > 0.75 && original[0] < 0.25 ||
32783                 index >= 2 && this._inverted && changed[0] > 0.75 && original[2] < 0.25;
32784             var passingBoundaryRightward = index < 2 && this._inverted && changed[0] < 0.25 && original[0] > 0.75 ||
32785                 index >= 2 && changed[0] < 0.25 && original[2] > 0.75;
32786             if (passingBoundaryLeftward || passingBoundaryRightward) {
32787                 this._inverted = !this._inverted;
32788             }
32789             else {
32790                 if (rect[0] - original[0] < -0.25) {
32791                     rect[0] = original[0];
32792                 }
32793                 if (rect[2] - original[2] > 0.25) {
32794                     rect[2] = original[2];
32795                 }
32796             }
32797             if (!this._inverted && rect[0] > rect[2] ||
32798                 this._inverted && rect[0] < rect[2]) {
32799                 rect[0] = original[0];
32800                 rect[2] = original[2];
32801             }
32802         }
32803         else {
32804             if (rect[0] > rect[2]) {
32805                 rect[0] = original[0];
32806                 rect[2] = original[2];
32807             }
32808         }
32809         if (rect[1] > rect[3]) {
32810             rect[1] = original[1];
32811             rect[3] = original[3];
32812         }
32813         this._rect[0] = rect[0];
32814         this._rect[1] = rect[1];
32815         this._rect[2] = rect[2];
32816         this._rect[3] = rect[3];
32817         this._notifyChanged$.next(this);
32818     };
32819     /** @inheritdoc */
32820     RectGeometry.prototype.setCentroid2d = function (value, transform) {
32821         var original = this._rect.slice();
32822         var x0 = original[0];
32823         var x1 = this._inverted ? original[2] + 1 : original[2];
32824         var y0 = original[1];
32825         var y1 = original[3];
32826         var centerX = x0 + (x1 - x0) / 2;
32827         var centerY = y0 + (y1 - y0) / 2;
32828         var translationX = 0;
32829         if (transform.gpano != null &&
32830             transform.gpano.CroppedAreaImageWidthPixels === transform.gpano.FullPanoWidthPixels) {
32831             translationX = this._inverted ? value[0] + 1 - centerX : value[0] - centerX;
32832         }
32833         else {
32834             var minTranslationX = -x0;
32835             var maxTranslationX = 1 - x1;
32836             translationX = Math.max(minTranslationX, Math.min(maxTranslationX, value[0] - centerX));
32837         }
32838         var minTranslationY = -y0;
32839         var maxTranslationY = 1 - y1;
32840         var translationY = Math.max(minTranslationY, Math.min(maxTranslationY, value[1] - centerY));
32841         this._rect[0] = original[0] + translationX;
32842         this._rect[1] = original[1] + translationY;
32843         this._rect[2] = original[2] + translationX;
32844         this._rect[3] = original[3] + translationY;
32845         if (this._rect[0] < 0) {
32846             this._rect[0] += 1;
32847             this._inverted = !this._inverted;
32848         }
32849         else if (this._rect[0] > 1) {
32850             this._rect[0] -= 1;
32851             this._inverted = !this._inverted;
32852         }
32853         if (this._rect[2] < 0) {
32854             this._rect[2] += 1;
32855             this._inverted = !this._inverted;
32856         }
32857         else if (this._rect[2] > 1) {
32858             this._rect[2] -= 1;
32859             this._inverted = !this._inverted;
32860         }
32861         this._notifyChanged$.next(this);
32862     };
32863     /**
32864      * Get the 3D coordinates for the vertices of the rectangle with
32865      * interpolated points along the lines.
32866      *
32867      * @param {Transform} transform - The transform of the node related to
32868      * the rectangle.
32869      * @returns {Array<Array<number>>} Polygon array of 3D world coordinates
32870      * representing the rectangle.
32871      */
32872     RectGeometry.prototype.getPoints3d = function (transform) {
32873         return this._getPoints2d(transform)
32874             .map(function (point) {
32875             return transform.unprojectBasic(point, 200);
32876         });
32877     };
32878     /**
32879      * Get the coordinates of a vertex from the polygon representation of the geometry.
32880      *
32881      * @description The first vertex represents the bottom-left corner with the rest of
32882      * the vertices following in clockwise order. The method shifts the right side
32883      * coordinates of the rectangle by one unit to ensure that the vertices are ordered
32884      * clockwise.
32885      *
32886      * @param {number} index - Vertex index.
32887      * @returns {Array<number>} Array representing the 2D basic coordinates of the vertex.
32888      */
32889     RectGeometry.prototype.getVertex2d = function (index) {
32890         return this._rectToVertices2d(this._rect)[index];
32891     };
32892     /**
32893      * Get the coordinates of a vertex from the polygon representation of the geometry.
32894      *
32895      * @description The first vertex represents the bottom-left corner with the rest of
32896      * the vertices following in clockwise order. The coordinates will not be shifted
32897      * so they may not appear in clockwise order when layed out on the plane.
32898      *
32899      * @param {number} index - Vertex index.
32900      * @returns {Array<number>} Array representing the 2D basic coordinates of the vertex.
32901      */
32902     RectGeometry.prototype.getNonAdjustedVertex2d = function (index) {
32903         return this._rectToNonAdjustedVertices2d(this._rect)[index];
32904     };
32905     /**
32906      * Get a vertex from the polygon representation of the 3D coordinates for the
32907      * vertices of the geometry.
32908      *
32909      * @description The first vertex represents the bottom-left corner with the rest of
32910      * the vertices following in clockwise order.
32911      *
32912      * @param {number} index - Vertex index.
32913      * @param {Transform} transform - The transform of the node related to the geometry.
32914      * @returns {Array<Array<number>>} Polygon array of 3D world coordinates representing
32915      * the vertices of the geometry.
32916      */
32917     RectGeometry.prototype.getVertex3d = function (index, transform) {
32918         return transform.unprojectBasic(this._rectToVertices2d(this._rect)[index], 200);
32919     };
32920     /**
32921      * Get a polygon representation of the 2D basic coordinates for the vertices of the rectangle.
32922      *
32923      * @description The first vertex represents the bottom-left corner with the rest of
32924      * the vertices following in clockwise order.
32925      *
32926      * @returns {Array<Array<number>>} Polygon array of 2D basic coordinates representing
32927      * the rectangle vertices.
32928      */
32929     RectGeometry.prototype.getVertices2d = function () {
32930         return this._rectToVertices2d(this._rect);
32931     };
32932     /**
32933      * Get a polygon representation of the 3D coordinates for the vertices of the rectangle.
32934      *
32935      * @description The first vertex represents the bottom-left corner with the rest of
32936      * the vertices following in clockwise order.
32937      *
32938      * @param {Transform} transform - The transform of the node related to the rectangle.
32939      * @returns {Array<Array<number>>} Polygon array of 3D world coordinates representing
32940      * the rectangle vertices.
32941      */
32942     RectGeometry.prototype.getVertices3d = function (transform) {
32943         return this._rectToVertices2d(this._rect)
32944             .map(function (vertex) {
32945             return transform.unprojectBasic(vertex, 200);
32946         });
32947     };
32948     /** @inheritdoc */
32949     RectGeometry.prototype.getCentroid2d = function () {
32950         var rect = this._rect;
32951         var x0 = rect[0];
32952         var x1 = this._inverted ? rect[2] + 1 : rect[2];
32953         var y0 = rect[1];
32954         var y1 = rect[3];
32955         var centroidX = x0 + (x1 - x0) / 2;
32956         var centroidY = y0 + (y1 - y0) / 2;
32957         return [centroidX, centroidY];
32958     };
32959     /** @inheritdoc */
32960     RectGeometry.prototype.getCentroid3d = function (transform) {
32961         var centroid2d = this.getCentroid2d();
32962         return transform.unprojectBasic(centroid2d, 200);
32963     };
32964     /** @inheritdoc */
32965     RectGeometry.prototype.getPoleOfAccessibility2d = function () {
32966         return this._getPoleOfInaccessibility2d(this._rectToVertices2d(this._rect));
32967     };
32968     /** @inheritdoc */
32969     RectGeometry.prototype.getPoleOfAccessibility3d = function (transform) {
32970         var pole2d = this._getPoleOfInaccessibility2d(this._rectToVertices2d(this._rect));
32971         return transform.unprojectBasic(pole2d, 200);
32972     };
32973     /** @inheritdoc */
32974     RectGeometry.prototype.getTriangles3d = function (transform) {
32975         return this._triangulate(this._rectToVertices2d(this._rect), this.getVertices3d(transform));
32976     };
32977     /**
32978      * Check if a particular bottom-right value is valid according to the current
32979      * rectangle coordinates.
32980      *
32981      * @param {Array<number>} bottomRight - The bottom-right coordinates to validate
32982      * @returns {boolean} Value indicating whether the provided bottom-right coordinates
32983      * are valid.
32984      */
32985     RectGeometry.prototype.validate = function (bottomRight) {
32986         var rect = this._rect;
32987         if (!this._inverted && bottomRight[0] < rect[0] ||
32988             bottomRight[0] - rect[2] > 0.25 ||
32989             bottomRight[1] < rect[1]) {
32990             return false;
32991         }
32992         return true;
32993     };
32994     /**
32995      * Get the 2D coordinates for the vertices of the rectangle with
32996      * interpolated points along the lines.
32997      *
32998      * @param {Transform} transform - The transform of the node related to
32999      * the rectangle.
33000      * @returns {Array<Array<number>>} Polygon array of 2D basic coordinates
33001      * representing the rectangle.
33002      */
33003     RectGeometry.prototype._getPoints2d = function (transform) {
33004         var vertices2d = this._rectToVertices2d(this._rect);
33005         var sides = vertices2d.length - 1;
33006         var sections = 10;
33007         var points2d = [];
33008         for (var i = 0; i < sides; ++i) {
33009             var startX = vertices2d[i][0];
33010             var startY = vertices2d[i][1];
33011             var endX = vertices2d[i + 1][0];
33012             var endY = vertices2d[i + 1][1];
33013             var intervalX = (endX - startX) / (sections - 1);
33014             var intervalY = (endY - startY) / (sections - 1);
33015             for (var j = 0; j < sections; ++j) {
33016                 var point = [
33017                     startX + j * intervalX,
33018                     startY + j * intervalY,
33019                 ];
33020                 points2d.push(point);
33021             }
33022         }
33023         return points2d;
33024     };
33025     /**
33026      * Convert the top-left, bottom-right representation of a rectangle to a polygon
33027      * representation of the vertices starting at the bottom-left corner going
33028      * clockwise.
33029      *
33030      * @description The method shifts the right side coordinates of the rectangle
33031      * by one unit to ensure that the vertices are ordered clockwise.
33032      *
33033      * @param {Array<number>} rect - Top-left, bottom-right representation of a
33034      * rectangle.
33035      * @returns {Array<Array<number>>} Polygon representation of the vertices of the
33036      * rectangle.
33037      */
33038     RectGeometry.prototype._rectToVertices2d = function (rect) {
33039         return [
33040             [rect[0], rect[3]],
33041             [rect[0], rect[1]],
33042             [this._inverted ? rect[2] + 1 : rect[2], rect[1]],
33043             [this._inverted ? rect[2] + 1 : rect[2], rect[3]],
33044             [rect[0], rect[3]],
33045         ];
33046     };
33047     /**
33048      * Convert the top-left, bottom-right representation of a rectangle to a polygon
33049      * representation of the vertices starting at the bottom-left corner going
33050      * clockwise.
33051      *
33052      * @description The first vertex represents the bottom-left corner with the rest of
33053      * the vertices following in clockwise order. The coordinates will not be shifted
33054      * to ensure that the vertices are ordered clockwise when layed out on the plane.
33055      *
33056      * @param {Array<number>} rect - Top-left, bottom-right representation of a
33057      * rectangle.
33058      * @returns {Array<Array<number>>} Polygon representation of the vertices of the
33059      * rectangle.
33060      */
33061     RectGeometry.prototype._rectToNonAdjustedVertices2d = function (rect) {
33062         return [
33063             [rect[0], rect[3]],
33064             [rect[0], rect[1]],
33065             [rect[2], rect[1]],
33066             [rect[2], rect[3]],
33067             [rect[0], rect[3]],
33068         ];
33069     };
33070     return RectGeometry;
33071 }(Component_1.VertexGeometry));
33072 exports.RectGeometry = RectGeometry;
33073 exports.default = RectGeometry;
33074
33075 },{"../../../Component":291}],366:[function(require,module,exports){
33076 "use strict";
33077 /// <reference path="../../../../typings/index.d.ts" />
33078 var __extends = (this && this.__extends) || (function () {
33079     var extendStatics = Object.setPrototypeOf ||
33080         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33081         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33082     return function (d, b) {
33083         extendStatics(d, b);
33084         function __() { this.constructor = d; }
33085         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33086     };
33087 })();
33088 Object.defineProperty(exports, "__esModule", { value: true });
33089 var earcut = require("earcut");
33090 var polylabel = require("@mapbox/polylabel");
33091 var Component_1 = require("../../../Component");
33092 /**
33093  * @class VertexGeometry
33094  * @abstract
33095  * @classdesc Represents a vertex geometry.
33096  */
33097 var VertexGeometry = /** @class */ (function (_super) {
33098     __extends(VertexGeometry, _super);
33099     /**
33100      * Create a vertex geometry.
33101      *
33102      * @constructor
33103      */
33104     function VertexGeometry() {
33105         return _super.call(this) || this;
33106     }
33107     /**
33108      * Finds the polygon pole of inaccessibility, the most distant internal
33109      * point from the polygon outline.
33110      *
33111      * @param {Array<Array<number>>} points2d - 2d points of outline to triangulate.
33112      * @returns {Array<number>} Point of inaccessibility.
33113      * @ignore
33114      */
33115     VertexGeometry.prototype._getPoleOfInaccessibility2d = function (points2d) {
33116         var pole2d = polylabel([points2d], 3e-2);
33117         return pole2d;
33118     };
33119     /**
33120      * Triangulates a 2d polygon and returns the triangle
33121      * representation as a flattened array of 3d points.
33122      *
33123      * @param {Array<Array<number>>} points2d - 2d points of outline to triangulate.
33124      * @param {Array<Array<number>>} points3d - 3d points of outline corresponding to the 2d points.
33125      * @param {Array<Array<Array<number>>>} [holes2d] - 2d points of holes to triangulate.
33126      * @param {Array<Array<Array<number>>>} [holes3d] - 3d points of holes corresponding to the 2d points.
33127      * @returns {Array<number>} Flattened array of 3d points ordered based on the triangles.
33128      * @ignore
33129      */
33130     VertexGeometry.prototype._triangulate = function (points2d, points3d, holes2d, holes3d) {
33131         var data = [points2d.slice(0, -1)];
33132         for (var _i = 0, _a = holes2d != null ? holes2d : []; _i < _a.length; _i++) {
33133             var hole2d = _a[_i];
33134             data.push(hole2d.slice(0, -1));
33135         }
33136         var points = points3d.slice(0, -1);
33137         for (var _b = 0, _c = holes3d != null ? holes3d : []; _b < _c.length; _b++) {
33138             var hole3d = _c[_b];
33139             points = points.concat(hole3d.slice(0, -1));
33140         }
33141         var flattened = earcut.flatten(data);
33142         var indices = earcut(flattened.vertices, flattened.holes, flattened.dimensions);
33143         var triangles = [];
33144         for (var i = 0; i < indices.length; ++i) {
33145             var point = points[indices[i]];
33146             triangles.push(point[0]);
33147             triangles.push(point[1]);
33148             triangles.push(point[2]);
33149         }
33150         return triangles;
33151     };
33152     return VertexGeometry;
33153 }(Component_1.Geometry));
33154 exports.VertexGeometry = VertexGeometry;
33155 exports.default = VertexGeometry;
33156
33157 },{"../../../Component":291,"@mapbox/polylabel":1,"earcut":8}],367:[function(require,module,exports){
33158 "use strict";
33159 /// <reference path="../../../../typings/index.d.ts" />
33160 var __extends = (this && this.__extends) || (function () {
33161     var extendStatics = Object.setPrototypeOf ||
33162         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33163         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33164     return function (d, b) {
33165         extendStatics(d, b);
33166         function __() { this.constructor = d; }
33167         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33168     };
33169 })();
33170 Object.defineProperty(exports, "__esModule", { value: true });
33171 var Subject_1 = require("rxjs/Subject");
33172 var Component_1 = require("../../../Component");
33173 var CreateHandlerBase = /** @class */ (function (_super) {
33174     __extends(CreateHandlerBase, _super);
33175     function CreateHandlerBase(component, container, navigator, viewportCoords, tagCreator) {
33176         var _this = _super.call(this, component, container, navigator, viewportCoords) || this;
33177         _this._tagCreator = tagCreator;
33178         _this._geometryCreated$ = new Subject_1.Subject();
33179         return _this;
33180     }
33181     Object.defineProperty(CreateHandlerBase.prototype, "geometryCreated$", {
33182         get: function () {
33183             return this._geometryCreated$;
33184         },
33185         enumerable: true,
33186         configurable: true
33187     });
33188     CreateHandlerBase.prototype._enable = function () {
33189         this._enableCreate();
33190         this._container.element.classList.add("component-tag-create");
33191     };
33192     CreateHandlerBase.prototype._disable = function () {
33193         this._container.element.classList.remove("component-tag-create");
33194         this._disableCreate();
33195     };
33196     CreateHandlerBase.prototype._validateBasic = function (basic) {
33197         var x = basic[0];
33198         var y = basic[1];
33199         return 0 <= x && x <= 1 && 0 <= y && y <= 1;
33200     };
33201     CreateHandlerBase.prototype._mouseEventToBasic$ = function (mouseEvent$) {
33202         var _this = this;
33203         return mouseEvent$
33204             .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
33205             .map(function (_a) {
33206             var event = _a[0], camera = _a[1], transform = _a[2];
33207             return _this._mouseEventToBasic(event, _this._container.element, camera, transform);
33208         });
33209     };
33210     return CreateHandlerBase;
33211 }(Component_1.TagHandlerBase));
33212 exports.CreateHandlerBase = CreateHandlerBase;
33213 exports.default = CreateHandlerBase;
33214
33215 },{"../../../Component":291,"rxjs/Subject":34}],368:[function(require,module,exports){
33216 "use strict";
33217 var __extends = (this && this.__extends) || (function () {
33218     var extendStatics = Object.setPrototypeOf ||
33219         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33220         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33221     return function (d, b) {
33222         extendStatics(d, b);
33223         function __() { this.constructor = d; }
33224         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33225     };
33226 })();
33227 Object.defineProperty(exports, "__esModule", { value: true });
33228 var Component_1 = require("../../../Component");
33229 var CreatePointHandler = /** @class */ (function (_super) {
33230     __extends(CreatePointHandler, _super);
33231     function CreatePointHandler() {
33232         return _super !== null && _super.apply(this, arguments) || this;
33233     }
33234     CreatePointHandler.prototype._enableCreate = function () {
33235         this._container.mouseService.deferPixels(this._name, 4);
33236         this._geometryCreatedSubscription = this._mouseEventToBasic$(this._container.mouseService.proximateClick$)
33237             .filter(this._validateBasic)
33238             .map(function (basic) {
33239             return new Component_1.PointGeometry(basic);
33240         })
33241             .subscribe(this._geometryCreated$);
33242     };
33243     CreatePointHandler.prototype._disableCreate = function () {
33244         this._container.mouseService.undeferPixels(this._name);
33245         this._geometryCreatedSubscription.unsubscribe();
33246     };
33247     CreatePointHandler.prototype._getNameExtension = function () {
33248         return "create-point";
33249     };
33250     return CreatePointHandler;
33251 }(Component_1.CreateHandlerBase));
33252 exports.CreatePointHandler = CreatePointHandler;
33253 exports.default = CreatePointHandler;
33254
33255 },{"../../../Component":291}],369:[function(require,module,exports){
33256 "use strict";
33257 var __extends = (this && this.__extends) || (function () {
33258     var extendStatics = Object.setPrototypeOf ||
33259         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33260         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33261     return function (d, b) {
33262         extendStatics(d, b);
33263         function __() { this.constructor = d; }
33264         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33265     };
33266 })();
33267 Object.defineProperty(exports, "__esModule", { value: true });
33268 var Component_1 = require("../../../Component");
33269 var CreatePolygonHandler = /** @class */ (function (_super) {
33270     __extends(CreatePolygonHandler, _super);
33271     function CreatePolygonHandler() {
33272         return _super !== null && _super.apply(this, arguments) || this;
33273     }
33274     CreatePolygonHandler.prototype._addPoint = function (tag, basicPoint) {
33275         tag.addPoint(basicPoint);
33276     };
33277     Object.defineProperty(CreatePolygonHandler.prototype, "_create$", {
33278         get: function () {
33279             return this._tagCreator.createPolygon$;
33280         },
33281         enumerable: true,
33282         configurable: true
33283     });
33284     CreatePolygonHandler.prototype._getNameExtension = function () {
33285         return "create-polygon";
33286     };
33287     CreatePolygonHandler.prototype._setVertex2d = function (tag, basicPoint, transform) {
33288         tag.geometry.setVertex2d(tag.geometry.polygon.length - 2, basicPoint, transform);
33289     };
33290     return CreatePolygonHandler;
33291 }(Component_1.CreateVertexHandler));
33292 exports.CreatePolygonHandler = CreatePolygonHandler;
33293 exports.default = CreatePolygonHandler;
33294
33295 },{"../../../Component":291}],370:[function(require,module,exports){
33296 "use strict";
33297 var __extends = (this && this.__extends) || (function () {
33298     var extendStatics = Object.setPrototypeOf ||
33299         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33300         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33301     return function (d, b) {
33302         extendStatics(d, b);
33303         function __() { this.constructor = d; }
33304         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33305     };
33306 })();
33307 Object.defineProperty(exports, "__esModule", { value: true });
33308 var Observable_1 = require("rxjs/Observable");
33309 var Component_1 = require("../../../Component");
33310 var CreateRectDragHandler = /** @class */ (function (_super) {
33311     __extends(CreateRectDragHandler, _super);
33312     function CreateRectDragHandler() {
33313         return _super !== null && _super.apply(this, arguments) || this;
33314     }
33315     CreateRectDragHandler.prototype._enableCreate = function () {
33316         var _this = this;
33317         this._container.mouseService.claimMouse(this._name, 2);
33318         this._deleteSubscription = this._navigator.stateService.currentTransform$
33319             .map(function (transform) { return null; })
33320             .skip(1)
33321             .subscribe(this._tagCreator.delete$);
33322         this._createSubscription = this._mouseEventToBasic$(this._container.mouseService.filtered$(this._name, this._container.mouseService.mouseDragStart$))
33323             .filter(this._validateBasic)
33324             .subscribe(this._tagCreator.createRect$);
33325         this._initializeAnchorIndexingSubscription = this._tagCreator.tag$
33326             .filter(function (tag) {
33327             return !!tag;
33328         })
33329             .subscribe(function (tag) {
33330             tag.geometry.initializeAnchorIndexing();
33331         });
33332         var basicMouse$ = Observable_1.Observable
33333             .merge(this._container.mouseService.filtered$(this._name, this._container.mouseService.mouseMove$), this._container.mouseService.filtered$(this._name, this._container.mouseService.domMouseMove$))
33334             .combineLatest(this._container.renderService.renderCamera$)
33335             .withLatestFrom(this._navigator.stateService.currentTransform$)
33336             .map(function (_a) {
33337             var _b = _a[0], event = _b[0], camera = _b[1], transform = _a[1];
33338             return _this._mouseEventToBasic(event, _this._container.element, camera, transform);
33339         });
33340         this._setVertexSubscription = this._tagCreator.tag$
33341             .switchMap(function (tag) {
33342             return !!tag ?
33343                 Observable_1.Observable
33344                     .combineLatest(Observable_1.Observable.of(tag), basicMouse$, _this._navigator.stateService.currentTransform$) :
33345                 Observable_1.Observable.empty();
33346         })
33347             .subscribe(function (_a) {
33348             var tag = _a[0], basicPoint = _a[1], transform = _a[2];
33349             tag.geometry.setOppositeVertex2d(basicPoint, transform);
33350         });
33351         var basicMouseDragEnd$ = this._container.mouseService.mouseDragEnd$
33352             .withLatestFrom(this._mouseEventToBasic$(this._container.mouseService.filtered$(this._name, this._container.mouseService.mouseDrag$))
33353             .filter(this._validateBasic), function (event, basicPoint) {
33354             return basicPoint;
33355         })
33356             .share();
33357         this._addPointSubscription = this._tagCreator.tag$
33358             .switchMap(function (tag) {
33359             return !!tag ?
33360                 Observable_1.Observable
33361                     .combineLatest(Observable_1.Observable.of(tag), basicMouseDragEnd$) :
33362                 Observable_1.Observable.empty();
33363         })
33364             .subscribe(function (_a) {
33365             var tag = _a[0], basicPoint = _a[1];
33366             var rectGeometry = tag.geometry;
33367             if (!rectGeometry.validate(basicPoint)) {
33368                 basicPoint = rectGeometry.getNonAdjustedVertex2d(3);
33369             }
33370             tag.addPoint(basicPoint);
33371         });
33372         this._geometryCreatedSubscription = this._tagCreator.tag$
33373             .switchMap(function (tag) {
33374             return !!tag ?
33375                 tag.created$
33376                     .map(function (t) {
33377                     return t.geometry;
33378                 }) :
33379                 Observable_1.Observable.empty();
33380         })
33381             .subscribe(this._geometryCreated$);
33382     };
33383     CreateRectDragHandler.prototype._disableCreate = function () {
33384         this._container.mouseService.unclaimMouse(this._name);
33385         this._tagCreator.delete$.next(null);
33386         this._addPointSubscription.unsubscribe();
33387         this._createSubscription.unsubscribe();
33388         this._deleteSubscription.unsubscribe();
33389         this._geometryCreatedSubscription.unsubscribe();
33390         this._initializeAnchorIndexingSubscription.unsubscribe();
33391         this._setVertexSubscription.unsubscribe();
33392     };
33393     CreateRectDragHandler.prototype._getNameExtension = function () {
33394         return "create-rect-drag";
33395     };
33396     return CreateRectDragHandler;
33397 }(Component_1.CreateHandlerBase));
33398 exports.CreateRectDragHandler = CreateRectDragHandler;
33399 exports.default = CreateRectDragHandler;
33400
33401 },{"../../../Component":291,"rxjs/Observable":29}],371:[function(require,module,exports){
33402 "use strict";
33403 var __extends = (this && this.__extends) || (function () {
33404     var extendStatics = Object.setPrototypeOf ||
33405         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33406         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33407     return function (d, b) {
33408         extendStatics(d, b);
33409         function __() { this.constructor = d; }
33410         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33411     };
33412 })();
33413 Object.defineProperty(exports, "__esModule", { value: true });
33414 var Component_1 = require("../../../Component");
33415 var CreateRectHandler = /** @class */ (function (_super) {
33416     __extends(CreateRectHandler, _super);
33417     function CreateRectHandler() {
33418         return _super !== null && _super.apply(this, arguments) || this;
33419     }
33420     Object.defineProperty(CreateRectHandler.prototype, "_create$", {
33421         get: function () {
33422             return this._tagCreator.createRect$;
33423         },
33424         enumerable: true,
33425         configurable: true
33426     });
33427     CreateRectHandler.prototype._addPoint = function (tag, basicPoint) {
33428         var rectGeometry = tag.geometry;
33429         if (!rectGeometry.validate(basicPoint)) {
33430             basicPoint = rectGeometry.getNonAdjustedVertex2d(3);
33431         }
33432         tag.addPoint(basicPoint);
33433     };
33434     CreateRectHandler.prototype._enable = function () {
33435         _super.prototype._enable.call(this);
33436         this._initializeAnchorIndexingSubscription = this._tagCreator.tag$
33437             .filter(function (tag) {
33438             return !!tag;
33439         })
33440             .subscribe(function (tag) {
33441             tag.geometry.initializeAnchorIndexing();
33442         });
33443     };
33444     CreateRectHandler.prototype._disable = function () {
33445         _super.prototype._disable.call(this);
33446         this._initializeAnchorIndexingSubscription.unsubscribe();
33447     };
33448     CreateRectHandler.prototype._getNameExtension = function () {
33449         return "create-rect";
33450     };
33451     CreateRectHandler.prototype._setVertex2d = function (tag, basicPoint, transform) {
33452         tag.geometry.setOppositeVertex2d(basicPoint, transform);
33453     };
33454     return CreateRectHandler;
33455 }(Component_1.CreateVertexHandler));
33456 exports.CreateRectHandler = CreateRectHandler;
33457 exports.default = CreateRectHandler;
33458
33459 },{"../../../Component":291}],372:[function(require,module,exports){
33460 "use strict";
33461 var __extends = (this && this.__extends) || (function () {
33462     var extendStatics = Object.setPrototypeOf ||
33463         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33464         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33465     return function (d, b) {
33466         extendStatics(d, b);
33467         function __() { this.constructor = d; }
33468         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33469     };
33470 })();
33471 Object.defineProperty(exports, "__esModule", { value: true });
33472 var Observable_1 = require("rxjs/Observable");
33473 var Component_1 = require("../../../Component");
33474 var CreateVertexHandler = /** @class */ (function (_super) {
33475     __extends(CreateVertexHandler, _super);
33476     function CreateVertexHandler() {
33477         return _super !== null && _super.apply(this, arguments) || this;
33478     }
33479     CreateVertexHandler.prototype._enableCreate = function () {
33480         var _this = this;
33481         this._container.mouseService.deferPixels(this._name, 4);
33482         var transformChanged$ = this._navigator.stateService.currentTransform$
33483             .map(function (transform) { })
33484             .publishReplay(1)
33485             .refCount();
33486         this._deleteSubscription = transformChanged$
33487             .skip(1)
33488             .subscribe(this._tagCreator.delete$);
33489         var basicClick$ = this._mouseEventToBasic$(this._container.mouseService.proximateClick$).share();
33490         this._createSubscription = transformChanged$
33491             .switchMap(function () {
33492             return basicClick$
33493                 .filter(_this._validateBasic)
33494                 .take(1);
33495         })
33496             .subscribe(this._create$);
33497         this._setVertexSubscription = this._tagCreator.tag$
33498             .switchMap(function (tag) {
33499             return !!tag ?
33500                 Observable_1.Observable
33501                     .combineLatest(Observable_1.Observable.of(tag), Observable_1.Observable
33502                     .merge(_this._container.mouseService.mouseMove$, _this._container.mouseService.domMouseMove$), _this._container.renderService.renderCamera$, _this._navigator.stateService.currentTransform$) :
33503                 Observable_1.Observable.empty();
33504         })
33505             .subscribe(function (_a) {
33506             var tag = _a[0], event = _a[1], camera = _a[2], transform = _a[3];
33507             var basicPoint = _this._mouseEventToBasic(event, _this._container.element, camera, transform);
33508             _this._setVertex2d(tag, basicPoint, transform);
33509         });
33510         this._addPointSubscription = this._tagCreator.tag$
33511             .switchMap(function (tag) {
33512             return !!tag ?
33513                 Observable_1.Observable
33514                     .combineLatest(Observable_1.Observable.of(tag), basicClick$) :
33515                 Observable_1.Observable.empty();
33516         })
33517             .subscribe(function (_a) {
33518             var tag = _a[0], basicPoint = _a[1];
33519             _this._addPoint(tag, basicPoint);
33520         });
33521         this._geometryCreateSubscription = this._tagCreator.tag$
33522             .switchMap(function (tag) {
33523             return !!tag ?
33524                 tag.created$
33525                     .map(function (t) {
33526                     return t.geometry;
33527                 }) :
33528                 Observable_1.Observable.empty();
33529         })
33530             .subscribe(this._geometryCreated$);
33531     };
33532     CreateVertexHandler.prototype._disableCreate = function () {
33533         this._container.mouseService.undeferPixels(this._name);
33534         this._tagCreator.delete$.next(null);
33535         this._addPointSubscription.unsubscribe();
33536         this._createSubscription.unsubscribe();
33537         this._deleteSubscription.unsubscribe();
33538         this._geometryCreateSubscription.unsubscribe();
33539         this._setVertexSubscription.unsubscribe();
33540     };
33541     return CreateVertexHandler;
33542 }(Component_1.CreateHandlerBase));
33543 exports.CreateVertexHandler = CreateVertexHandler;
33544 exports.default = CreateVertexHandler;
33545
33546 },{"../../../Component":291,"rxjs/Observable":29}],373:[function(require,module,exports){
33547 "use strict";
33548 var __extends = (this && this.__extends) || (function () {
33549     var extendStatics = Object.setPrototypeOf ||
33550         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33551         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33552     return function (d, b) {
33553         extendStatics(d, b);
33554         function __() { this.constructor = d; }
33555         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33556     };
33557 })();
33558 Object.defineProperty(exports, "__esModule", { value: true });
33559 var Observable_1 = require("rxjs/Observable");
33560 var Component_1 = require("../../../Component");
33561 var EditVertexHandler = /** @class */ (function (_super) {
33562     __extends(EditVertexHandler, _super);
33563     function EditVertexHandler(component, container, navigator, viewportCoords, tagSet) {
33564         var _this = _super.call(this, component, container, navigator, viewportCoords) || this;
33565         _this._tagSet = tagSet;
33566         return _this;
33567     }
33568     EditVertexHandler.prototype._enable = function () {
33569         var _this = this;
33570         var interaction$ = this._tagSet.changed$
33571             .map(function (tagSet) {
33572             return tagSet.getAll();
33573         })
33574             .switchMap(function (tags) {
33575             return Observable_1.Observable
33576                 .from(tags)
33577                 .mergeMap(function (tag) {
33578                 return tag.interact$;
33579             });
33580         })
33581             .switchMap(function (interaction) {
33582             return Observable_1.Observable
33583                 .of(interaction)
33584                 .concat(_this._container.mouseService.documentMouseUp$
33585                 .map(function () {
33586                 return { offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: null };
33587             })
33588                 .first());
33589         })
33590             .share();
33591         var mouseMove$ = Observable_1.Observable
33592             .merge(this._container.mouseService.mouseMove$, this._container.mouseService.domMouseMove$)
33593             .share();
33594         this._claimMouseSubscription = interaction$
33595             .switchMap(function (interaction) {
33596             return !!interaction.tag ? _this._container.mouseService.domMouseDragStart$ : Observable_1.Observable.empty();
33597         })
33598             .subscribe(function () {
33599             _this._container.mouseService.claimMouse(_this._name, 3);
33600         });
33601         this._cursorSubscription = interaction$
33602             .map(function (interaction) {
33603             return interaction.cursor;
33604         })
33605             .distinctUntilChanged()
33606             .subscribe(function (cursor) {
33607             var interactionCursors = ["crosshair", "move", "nesw-resize", "nwse-resize"];
33608             for (var _i = 0, interactionCursors_1 = interactionCursors; _i < interactionCursors_1.length; _i++) {
33609                 var interactionCursor = interactionCursors_1[_i];
33610                 _this._container.element.classList.remove("component-tag-edit-" + interactionCursor);
33611             }
33612             if (!!cursor) {
33613                 _this._container.element.classList.add("component-tag-edit-" + cursor);
33614             }
33615         });
33616         this._unclaimMouseSubscription = this._container.mouseService
33617             .filtered$(this._name, this._container.mouseService.domMouseDragEnd$)
33618             .subscribe(function (e) {
33619             _this._container.mouseService.unclaimMouse(_this._name);
33620         });
33621         this._preventDefaultSubscription = interaction$
33622             .switchMap(function (interaction) {
33623             return !!interaction.tag ?
33624                 _this._container.mouseService.documentMouseMove$ :
33625                 Observable_1.Observable.empty();
33626         })
33627             .subscribe(function (event) {
33628             event.preventDefault(); // prevent selection of content outside the viewer
33629         });
33630         this._updateGeometrySubscription = interaction$
33631             .withLatestFrom(mouseMove$)
33632             .switchMap(function (_a) {
33633             var interaction = _a[0], mouseMove = _a[1];
33634             if (interaction.operation === Component_1.TagOperation.None || !interaction.tag) {
33635                 return Observable_1.Observable.empty();
33636             }
33637             var mouseDrag$ = Observable_1.Observable
33638                 .of(mouseMove)
33639                 .concat(_this._container.mouseService
33640                 .filtered$(_this._name, _this._container.mouseService.domMouseDrag$)
33641                 .filter(function (event) {
33642                 return _this._viewportCoords.insideElement(event, _this._container.element);
33643             }));
33644             return Observable_1.Observable
33645                 .combineLatest(mouseDrag$, _this._container.renderService.renderCamera$)
33646                 .withLatestFrom(Observable_1.Observable.of(interaction), _this._navigator.stateService.currentTransform$, function (_a, i, transform) {
33647                 var event = _a[0], render = _a[1];
33648                 return [event, render, i, transform];
33649             });
33650         })
33651             .subscribe(function (_a) {
33652             var mouseEvent = _a[0], renderCamera = _a[1], interaction = _a[2], transform = _a[3];
33653             var basic = _this._mouseEventToBasic(mouseEvent, _this._container.element, renderCamera, transform, interaction.offsetX, interaction.offsetY);
33654             var geometry = interaction.tag.geometry;
33655             if (interaction.operation === Component_1.TagOperation.Centroid) {
33656                 geometry.setCentroid2d(basic, transform);
33657             }
33658             else if (interaction.operation === Component_1.TagOperation.Vertex) {
33659                 geometry.setVertex2d(interaction.vertexIndex, basic, transform);
33660             }
33661         });
33662     };
33663     EditVertexHandler.prototype._disable = function () {
33664         this._claimMouseSubscription.unsubscribe();
33665         this._cursorSubscription.unsubscribe();
33666         this._preventDefaultSubscription.unsubscribe();
33667         this._unclaimMouseSubscription.unsubscribe();
33668         this._updateGeometrySubscription.unsubscribe();
33669     };
33670     EditVertexHandler.prototype._getNameExtension = function () {
33671         return "edit-vertex";
33672     };
33673     return EditVertexHandler;
33674 }(Component_1.TagHandlerBase));
33675 exports.EditVertexHandler = EditVertexHandler;
33676 exports.default = EditVertexHandler;
33677
33678 },{"../../../Component":291,"rxjs/Observable":29}],374:[function(require,module,exports){
33679 "use strict";
33680 /// <reference path="../../../../typings/index.d.ts" />
33681 var __extends = (this && this.__extends) || (function () {
33682     var extendStatics = Object.setPrototypeOf ||
33683         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33684         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33685     return function (d, b) {
33686         extendStatics(d, b);
33687         function __() { this.constructor = d; }
33688         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33689     };
33690 })();
33691 Object.defineProperty(exports, "__esModule", { value: true });
33692 var Component_1 = require("../../../Component");
33693 var TagHandlerBase = /** @class */ (function (_super) {
33694     __extends(TagHandlerBase, _super);
33695     function TagHandlerBase(component, container, navigator, viewportCoords) {
33696         var _this = _super.call(this, component, container, navigator) || this;
33697         _this._name = _this._component.name + "-" + _this._getNameExtension();
33698         _this._viewportCoords = viewportCoords;
33699         return _this;
33700     }
33701     TagHandlerBase.prototype._getConfiguration = function (enable) {
33702         return {};
33703     };
33704     TagHandlerBase.prototype._mouseEventToBasic = function (event, element, camera, transform, offsetX, offsetY) {
33705         offsetX = offsetX != null ? offsetX : 0;
33706         offsetY = offsetY != null ? offsetY : 0;
33707         var _a = this._viewportCoords.canvasPosition(event, element), canvasX = _a[0], canvasY = _a[1];
33708         var basic = this._viewportCoords.canvasToBasic(canvasX - offsetX, canvasY - offsetY, element, transform, camera.perspective);
33709         return basic;
33710     };
33711     return TagHandlerBase;
33712 }(Component_1.HandlerBase));
33713 exports.TagHandlerBase = TagHandlerBase;
33714 exports.default = TagHandlerBase;
33715
33716 },{"../../../Component":291}],375:[function(require,module,exports){
33717 "use strict";
33718 /// <reference path="../../../../typings/index.d.ts" />
33719 Object.defineProperty(exports, "__esModule", { value: true });
33720 var THREE = require("three");
33721 var vd = require("virtual-dom");
33722 var Subject_1 = require("rxjs/Subject");
33723 var Component_1 = require("../../../Component");
33724 var Geo_1 = require("../../../Geo");
33725 var OutlineCreateTag = /** @class */ (function () {
33726     function OutlineCreateTag(geometry, options, transform, viewportCoords) {
33727         var _this = this;
33728         this._geometry = geometry;
33729         this._options = { color: options.color == null ? 0xFFFFFF : options.color };
33730         this._transform = transform;
33731         this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
33732         this._outline = this._createOutine();
33733         this._glObjects = [this._outline];
33734         this._aborted$ = new Subject_1.Subject();
33735         this._created$ = new Subject_1.Subject();
33736         this._glObjectsChanged$ = new Subject_1.Subject();
33737         this._geometryChangedSubscription = this._geometry.changed$
33738             .subscribe(function (vertexGeometry) {
33739             _this._disposeOutline();
33740             _this._outline = _this._createOutine();
33741             _this._glObjects = [_this._outline];
33742             _this._glObjectsChanged$.next(_this);
33743         });
33744     }
33745     Object.defineProperty(OutlineCreateTag.prototype, "geometry", {
33746         get: function () {
33747             return this._geometry;
33748         },
33749         enumerable: true,
33750         configurable: true
33751     });
33752     Object.defineProperty(OutlineCreateTag.prototype, "glObjects", {
33753         get: function () {
33754             return this._glObjects;
33755         },
33756         enumerable: true,
33757         configurable: true
33758     });
33759     Object.defineProperty(OutlineCreateTag.prototype, "aborted$", {
33760         get: function () {
33761             return this._aborted$;
33762         },
33763         enumerable: true,
33764         configurable: true
33765     });
33766     Object.defineProperty(OutlineCreateTag.prototype, "created$", {
33767         get: function () {
33768             return this._created$;
33769         },
33770         enumerable: true,
33771         configurable: true
33772     });
33773     Object.defineProperty(OutlineCreateTag.prototype, "glObjectsChanged$", {
33774         get: function () {
33775             return this._glObjectsChanged$;
33776         },
33777         enumerable: true,
33778         configurable: true
33779     });
33780     Object.defineProperty(OutlineCreateTag.prototype, "geometryChanged$", {
33781         get: function () {
33782             var _this = this;
33783             return this._geometry.changed$
33784                 .map(function (geometry) {
33785                 return _this;
33786             });
33787         },
33788         enumerable: true,
33789         configurable: true
33790     });
33791     OutlineCreateTag.prototype.dispose = function () {
33792         this._disposeOutline();
33793         this._geometryChangedSubscription.unsubscribe();
33794     };
33795     OutlineCreateTag.prototype.getDOMObjects = function (camera, size) {
33796         var _this = this;
33797         var vNodes = [];
33798         var container = {
33799             offsetHeight: size.height, offsetWidth: size.width,
33800         };
33801         var abort = function (e) {
33802             e.stopPropagation();
33803             _this._aborted$.next(_this);
33804         };
33805         if (this._geometry instanceof Component_1.RectGeometry) {
33806             var anchorIndex = this._geometry.anchorIndex;
33807             var vertexIndex = anchorIndex === undefined ? 1 : anchorIndex;
33808             var _a = this._geometry.getVertex2d(vertexIndex), basicX = _a[0], basicY = _a[1];
33809             var canvasPoint = this._viewportCoords.basicToCanvasSafe(basicX, basicY, container, this._transform, camera);
33810             if (canvasPoint != null) {
33811                 var background = this._colorToBackground(this._options.color);
33812                 var transform = this._canvasToTransform(canvasPoint);
33813                 var pointProperties = {
33814                     style: { background: background, transform: transform },
33815                 };
33816                 var completerProperties = {
33817                     onclick: abort,
33818                     style: { transform: transform },
33819                 };
33820                 vNodes.push(vd.h("div.TagInteractor", completerProperties, []));
33821                 vNodes.push(vd.h("div.TagVertex", pointProperties, []));
33822             }
33823         }
33824         else if (this._geometry instanceof Component_1.PolygonGeometry) {
33825             var polygonGeometry_1 = this._geometry;
33826             var _b = polygonGeometry_1.getVertex2d(0), firstVertexBasicX = _b[0], firstVertexBasicY = _b[1];
33827             var firstVertexCanvas = this._viewportCoords.basicToCanvasSafe(firstVertexBasicX, firstVertexBasicY, container, this._transform, camera);
33828             if (firstVertexCanvas != null) {
33829                 var firstOnclick = polygonGeometry_1.polygon.length > 4 ?
33830                     function (e) {
33831                         e.stopPropagation();
33832                         polygonGeometry_1.removeVertex2d(polygonGeometry_1.polygon.length - 2);
33833                         _this._created$.next(_this);
33834                     } :
33835                     abort;
33836                 var transform = this._canvasToTransform(firstVertexCanvas);
33837                 var completerProperties = {
33838                     onclick: firstOnclick,
33839                     style: { transform: transform },
33840                 };
33841                 var firstClass = polygonGeometry_1.polygon.length > 4 ?
33842                     "TagCompleter" :
33843                     "TagInteractor";
33844                 vNodes.push(vd.h("div." + firstClass, completerProperties, []));
33845             }
33846             if (polygonGeometry_1.polygon.length > 3) {
33847                 var _c = polygonGeometry_1.getVertex2d(polygonGeometry_1.polygon.length - 3), lastVertexBasicX = _c[0], lastVertexBasicY = _c[1];
33848                 var lastVertexCanvas = this._viewportCoords.basicToCanvasSafe(lastVertexBasicX, lastVertexBasicY, container, this._transform, camera);
33849                 if (lastVertexCanvas != null) {
33850                     var remove = function (e) {
33851                         e.stopPropagation();
33852                         polygonGeometry_1.removeVertex2d(polygonGeometry_1.polygon.length - 3);
33853                     };
33854                     var transform = this._canvasToTransform(lastVertexCanvas);
33855                     var completerProperties = {
33856                         onclick: remove,
33857                         style: { transform: transform },
33858                     };
33859                     vNodes.push(vd.h("div.TagInteractor", completerProperties, []));
33860                 }
33861             }
33862             var verticesBasic = polygonGeometry_1.polygon.slice();
33863             verticesBasic.splice(-2, 2);
33864             for (var _i = 0, verticesBasic_1 = verticesBasic; _i < verticesBasic_1.length; _i++) {
33865                 var vertexBasic = verticesBasic_1[_i];
33866                 var vertexCanvas = this._viewportCoords.basicToCanvasSafe(vertexBasic[0], vertexBasic[1], container, this._transform, camera);
33867                 if (vertexCanvas != null) {
33868                     var background = this._colorToBackground(this._options.color);
33869                     var transform = this._canvasToTransform(vertexCanvas);
33870                     var pointProperties = {
33871                         style: {
33872                             background: background,
33873                             transform: transform,
33874                         },
33875                     };
33876                     vNodes.push(vd.h("div.TagVertex", pointProperties, []));
33877                 }
33878             }
33879         }
33880         return vNodes;
33881     };
33882     OutlineCreateTag.prototype.addPoint = function (point) {
33883         if (this._geometry instanceof Component_1.RectGeometry) {
33884             var rectGeometry = this._geometry;
33885             if (!rectGeometry.validate(point)) {
33886                 return;
33887             }
33888             this._created$.next(this);
33889         }
33890         else if (this._geometry instanceof Component_1.PolygonGeometry) {
33891             var polygonGeometry = this._geometry;
33892             polygonGeometry.addVertex2d(point);
33893         }
33894     };
33895     OutlineCreateTag.prototype._canvasToTransform = function (canvas) {
33896         var canvasX = Math.round(canvas[0]);
33897         var canvasY = Math.round(canvas[1]);
33898         var transform = "translate(-50%,-50%) translate(" + canvasX + "px," + canvasY + "px)";
33899         return transform;
33900     };
33901     OutlineCreateTag.prototype._colorToBackground = function (color) {
33902         return "#" + ("000000" + color.toString(16)).substr(-6);
33903     };
33904     OutlineCreateTag.prototype._createOutine = function () {
33905         var polygon3d = this._geometry.getPoints3d(this._transform);
33906         var positions = this._getLinePositions(polygon3d);
33907         var geometry = new THREE.BufferGeometry();
33908         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
33909         var material = new THREE.LineBasicMaterial({
33910             color: this._options.color,
33911             linewidth: 1,
33912         });
33913         return new THREE.Line(geometry, material);
33914     };
33915     OutlineCreateTag.prototype._disposeOutline = function () {
33916         if (this._outline == null) {
33917             return;
33918         }
33919         var line = this._outline;
33920         line.geometry.dispose();
33921         line.material.dispose();
33922         this._outline = null;
33923         this._glObjects = [];
33924     };
33925     OutlineCreateTag.prototype._getLinePositions = function (polygon3d) {
33926         var length = polygon3d.length;
33927         var positions = new Float32Array(length * 3);
33928         for (var i = 0; i < length; ++i) {
33929             var index = 3 * i;
33930             var position = polygon3d[i];
33931             positions[index] = position[0];
33932             positions[index + 1] = position[1];
33933             positions[index + 2] = position[2];
33934         }
33935         return positions;
33936     };
33937     return OutlineCreateTag;
33938 }());
33939 exports.OutlineCreateTag = OutlineCreateTag;
33940 exports.default = OutlineCreateTag;
33941
33942 },{"../../../Component":291,"../../../Geo":294,"rxjs/Subject":34,"three":241,"virtual-dom":247}],376:[function(require,module,exports){
33943 "use strict";
33944 /// <reference path="../../../../typings/index.d.ts" />
33945 var __extends = (this && this.__extends) || (function () {
33946     var extendStatics = Object.setPrototypeOf ||
33947         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
33948         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
33949     return function (d, b) {
33950         extendStatics(d, b);
33951         function __() { this.constructor = d; }
33952         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33953     };
33954 })();
33955 Object.defineProperty(exports, "__esModule", { value: true });
33956 var THREE = require("three");
33957 var vd = require("virtual-dom");
33958 var Component_1 = require("../../../Component");
33959 /**
33960  * @class OutlineRenderTag
33961  * @classdesc Tag visualizing the properties of an OutlineTag.
33962  */
33963 var OutlineRenderTag = /** @class */ (function (_super) {
33964     __extends(OutlineRenderTag, _super);
33965     function OutlineRenderTag(tag, transform) {
33966         var _this = _super.call(this, tag, transform) || this;
33967         _this._fill = !transform.gpano ?
33968             _this._createFill() :
33969             null;
33970         _this._holes = _this._tag.lineWidth >= 1 ?
33971             _this._createHoles() :
33972             [];
33973         _this._outline = _this._tag.lineWidth >= 1 ?
33974             _this._createOutline() :
33975             null;
33976         _this._geometryChangedSubscription = _this._tag.geometry.changed$
33977             .subscribe(function (geometry) {
33978             if (_this._fill != null) {
33979                 _this._updateFillGeometry();
33980             }
33981             if (_this._holes.length > 0) {
33982                 _this._updateHoleGeometries();
33983             }
33984             if (_this._outline != null) {
33985                 _this._updateOulineGeometry();
33986             }
33987         });
33988         _this._changedSubscription = _this._tag.changed$
33989             .subscribe(function (changedTag) {
33990             var glObjectsChanged = false;
33991             if (_this._fill != null) {
33992                 _this._updateFillMaterial(_this._fill.material);
33993             }
33994             if (_this._outline == null) {
33995                 if (_this._tag.lineWidth >= 1) {
33996                     _this._holes = _this._createHoles();
33997                     _this._outline = _this._createOutline();
33998                     glObjectsChanged = true;
33999                 }
34000             }
34001             else {
34002                 _this._updateHoleMaterials();
34003                 _this._updateOutlineMaterial();
34004             }
34005             if (glObjectsChanged) {
34006                 _this._glObjectsChanged$.next(_this);
34007             }
34008         });
34009         return _this;
34010     }
34011     OutlineRenderTag.prototype.dispose = function () {
34012         this._disposeFill();
34013         this._disposeHoles();
34014         this._disposeOutline();
34015         this._changedSubscription.unsubscribe();
34016         this._geometryChangedSubscription.unsubscribe();
34017     };
34018     OutlineRenderTag.prototype.getDOMObjects = function (atlas, camera, size) {
34019         var _this = this;
34020         var vNodes = [];
34021         var isRect = this._tag.geometry instanceof Component_1.RectGeometry;
34022         var isPerspective = !this._transform.gpano;
34023         var container = {
34024             offsetHeight: size.height, offsetWidth: size.width,
34025         };
34026         if (this._tag.icon != null && (isRect || isPerspective)) {
34027             var _a = this._tag.geometry instanceof Component_1.RectGeometry ?
34028                 this._tag.geometry.getVertex2d(this._tag.iconIndex) :
34029                 this._tag.geometry.getPoleOfAccessibility2d(), iconBasicX = _a[0], iconBasicY = _a[1];
34030             var iconCanvas = this._viewportCoords.basicToCanvasSafe(iconBasicX, iconBasicY, container, this._transform, camera);
34031             if (iconCanvas != null) {
34032                 var interact = function (e) {
34033                     _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
34034                 };
34035                 if (atlas.loaded) {
34036                     var sprite = atlas.getDOMSprite(this._tag.icon, this._tag.iconFloat);
34037                     var iconCanvasX = Math.round(iconCanvas[0]);
34038                     var iconCanvasY = Math.round(iconCanvas[1]);
34039                     var transform = "translate(" + iconCanvasX + "px," + iconCanvasY + "px)";
34040                     var click = function (e) {
34041                         e.stopPropagation();
34042                         _this._tag.click$.next(_this._tag);
34043                     };
34044                     var properties = {
34045                         onclick: click,
34046                         onmousedown: interact,
34047                         style: { transform: transform },
34048                     };
34049                     vNodes.push(vd.h("div.TagSymbol", properties, [sprite]));
34050                 }
34051             }
34052         }
34053         else if (this._tag.text != null && (isRect || isPerspective)) {
34054             var _b = this._tag.geometry instanceof Component_1.RectGeometry ?
34055                 this._tag.geometry.getVertex2d(3) :
34056                 this._tag.geometry.getPoleOfAccessibility2d(), textBasicX = _b[0], textBasicY = _b[1];
34057             var textCanvas = this._viewportCoords.basicToCanvasSafe(textBasicX, textBasicY, container, this._transform, camera);
34058             if (textCanvas != null) {
34059                 var textCanvasX = Math.round(textCanvas[0]);
34060                 var textCanvasY = Math.round(textCanvas[1]);
34061                 var transform = this._tag.geometry instanceof Component_1.RectGeometry ?
34062                     "translate(" + textCanvasX + "px," + textCanvasY + "px)" :
34063                     "translate(-50%, -50%) translate(" + textCanvasX + "px," + textCanvasY + "px)";
34064                 var interact = function (e) {
34065                     _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: _this._tag });
34066                 };
34067                 var properties = {
34068                     onmousedown: interact,
34069                     style: {
34070                         color: this._colorToCss(this._tag.textColor),
34071                         transform: transform,
34072                     },
34073                     textContent: this._tag.text,
34074                 };
34075                 vNodes.push(vd.h("span.TagSymbol", properties, []));
34076             }
34077         }
34078         if (!this._tag.editable) {
34079             return vNodes;
34080         }
34081         var lineColor = this._colorToCss(this._tag.lineColor);
34082         if (this._tag.geometry instanceof Component_1.RectGeometry) {
34083             var _c = this._tag.geometry.getCentroid2d(), centroidBasicX = _c[0], centroidBasicY = _c[1];
34084             var centroidCanvas = this._viewportCoords.basicToCanvasSafe(centroidBasicX, centroidBasicY, container, this._transform, camera);
34085             if (centroidCanvas != null) {
34086                 var interact = this._interact(Component_1.TagOperation.Centroid, "move");
34087                 var centroidCanvasX = Math.round(centroidCanvas[0]);
34088                 var centroidCanvasY = Math.round(centroidCanvas[1]);
34089                 var transform = "translate(-50%, -50%) translate(" + centroidCanvasX + "px," + centroidCanvasY + "px)";
34090                 var properties = {
34091                     onmousedown: interact,
34092                     style: { background: lineColor, transform: transform },
34093                 };
34094                 vNodes.push(vd.h("div.TagMover", properties, []));
34095             }
34096         }
34097         var vertices2d = this._tag.geometry.getVertices2d();
34098         for (var i = 0; i < vertices2d.length - 1; i++) {
34099             if (isRect &&
34100                 ((this._tag.icon != null && i === this._tag.iconIndex) ||
34101                     (this._tag.icon == null && this._tag.text != null && i === 3))) {
34102                 continue;
34103             }
34104             var _d = vertices2d[i], vertexBasicX = _d[0], vertexBasicY = _d[1];
34105             var vertexCanvas = this._viewportCoords.basicToCanvasSafe(vertexBasicX, vertexBasicY, container, this._transform, camera);
34106             if (vertexCanvas == null) {
34107                 continue;
34108             }
34109             var cursor = isRect ?
34110                 i % 2 === 0 ? "nesw-resize" : "nwse-resize" :
34111                 "crosshair";
34112             var interact = this._interact(Component_1.TagOperation.Vertex, cursor, i);
34113             var vertexCanvasX = Math.round(vertexCanvas[0]);
34114             var vertexCanvasY = Math.round(vertexCanvas[1]);
34115             var transform = "translate(-50%, -50%) translate(" + vertexCanvasX + "px," + vertexCanvasY + "px)";
34116             var properties = {
34117                 onmousedown: interact,
34118                 style: { background: lineColor, transform: transform, cursor: cursor },
34119             };
34120             vNodes.push(vd.h("div.TagResizer", properties, []));
34121             if (!this._tag.indicateVertices) {
34122                 continue;
34123             }
34124             var pointProperties = {
34125                 style: { background: lineColor, transform: transform },
34126             };
34127             vNodes.push(vd.h("div.TagVertex", pointProperties, []));
34128         }
34129         return vNodes;
34130     };
34131     OutlineRenderTag.prototype.getGLObjects = function () {
34132         var glObjects = [];
34133         if (this._fill != null) {
34134             glObjects.push(this._fill);
34135         }
34136         for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
34137             var hole = _a[_i];
34138             glObjects.push(hole);
34139         }
34140         if (this._outline != null) {
34141             glObjects.push(this._outline);
34142         }
34143         return glObjects;
34144     };
34145     OutlineRenderTag.prototype.getRetrievableObjects = function () {
34146         return this._fill != null ? [this._fill] : [];
34147     };
34148     OutlineRenderTag.prototype._colorToCss = function (color) {
34149         return "#" + ("000000" + color.toString(16)).substr(-6);
34150     };
34151     OutlineRenderTag.prototype._createFill = function () {
34152         var triangles = this._tag.geometry.getTriangles3d(this._transform);
34153         var positions = new Float32Array(triangles);
34154         var geometry = new THREE.BufferGeometry();
34155         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
34156         geometry.computeBoundingSphere();
34157         var material = new THREE.MeshBasicMaterial({ side: THREE.DoubleSide, transparent: true });
34158         this._updateFillMaterial(material);
34159         return new THREE.Mesh(geometry, material);
34160     };
34161     OutlineRenderTag.prototype._createHoles = function () {
34162         var holes = [];
34163         if (this._tag.geometry instanceof Component_1.PolygonGeometry) {
34164             var polygonGeometry = this._tag.geometry;
34165             var holes3d = polygonGeometry.getHoleVertices3d(this._transform);
34166             for (var _i = 0, holes3d_1 = holes3d; _i < holes3d_1.length; _i++) {
34167                 var holePoints3d = holes3d_1[_i];
34168                 var hole = this._createLine(holePoints3d);
34169                 holes.push(hole);
34170             }
34171         }
34172         return holes;
34173     };
34174     OutlineRenderTag.prototype._createLine = function (points3d) {
34175         var positions = this._getLinePositions(points3d);
34176         var geometry = new THREE.BufferGeometry();
34177         geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
34178         geometry.computeBoundingSphere();
34179         var material = new THREE.LineBasicMaterial();
34180         this._updateLineBasicMaterial(material);
34181         var line = new THREE.Line(geometry, material);
34182         line.renderOrder = 1;
34183         return line;
34184     };
34185     OutlineRenderTag.prototype._createOutline = function () {
34186         var points3d = this._tag.geometry.getPoints3d(this._transform);
34187         return this._createLine(points3d);
34188     };
34189     OutlineRenderTag.prototype._disposeFill = function () {
34190         if (this._fill == null) {
34191             return;
34192         }
34193         this._fill.geometry.dispose();
34194         this._fill.material.dispose();
34195         this._fill = null;
34196     };
34197     OutlineRenderTag.prototype._disposeHoles = function () {
34198         for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
34199             var hole = _a[_i];
34200             hole.geometry.dispose();
34201             hole.material.dispose();
34202         }
34203         this._holes = [];
34204     };
34205     OutlineRenderTag.prototype._disposeOutline = function () {
34206         if (this._outline == null) {
34207             return;
34208         }
34209         this._outline.geometry.dispose();
34210         this._outline.material.dispose();
34211         this._outline = null;
34212     };
34213     OutlineRenderTag.prototype._getLinePositions = function (points3d) {
34214         var length = points3d.length;
34215         var positions = new Float32Array(length * 3);
34216         for (var i = 0; i < length; ++i) {
34217             var index = 3 * i;
34218             var position = points3d[i];
34219             positions[index + 0] = position[0];
34220             positions[index + 1] = position[1];
34221             positions[index + 2] = position[2];
34222         }
34223         return positions;
34224     };
34225     OutlineRenderTag.prototype._interact = function (operation, cursor, vertexIndex) {
34226         var _this = this;
34227         return function (e) {
34228             var offsetX = e.offsetX - e.target.offsetWidth / 2;
34229             var offsetY = e.offsetY - e.target.offsetHeight / 2;
34230             _this._interact$.next({
34231                 cursor: cursor,
34232                 offsetX: offsetX,
34233                 offsetY: offsetY,
34234                 operation: operation,
34235                 tag: _this._tag,
34236                 vertexIndex: vertexIndex,
34237             });
34238         };
34239     };
34240     OutlineRenderTag.prototype._updateFillGeometry = function () {
34241         var triangles = this._tag.geometry.getTriangles3d(this._transform);
34242         var positions = new Float32Array(triangles);
34243         var geometry = this._fill.geometry;
34244         var attribute = geometry.getAttribute("position");
34245         if (attribute.array.length === positions.length) {
34246             attribute.set(positions);
34247             attribute.needsUpdate = true;
34248         }
34249         else {
34250             geometry.removeAttribute("position");
34251             geometry.addAttribute("position", new THREE.BufferAttribute(positions, 3));
34252         }
34253         geometry.computeBoundingSphere();
34254     };
34255     OutlineRenderTag.prototype._updateFillMaterial = function (material) {
34256         material.color = new THREE.Color(this._tag.fillColor);
34257         material.opacity = this._tag.fillOpacity;
34258         material.needsUpdate = true;
34259     };
34260     OutlineRenderTag.prototype._updateHoleGeometries = function () {
34261         var polygonGeometry = this._tag.geometry;
34262         var holes3d = polygonGeometry.getHoleVertices3d(this._transform);
34263         if (holes3d.length !== this._holes.length) {
34264             throw new Error("Changing the number of holes is not supported.");
34265         }
34266         for (var i = 0; i < this._holes.length; i++) {
34267             var holePoints3d = holes3d[i];
34268             var hole = this._holes[i];
34269             this._updateLine(hole, holePoints3d);
34270         }
34271     };
34272     OutlineRenderTag.prototype._updateHoleMaterials = function () {
34273         for (var _i = 0, _a = this._holes; _i < _a.length; _i++) {
34274             var hole = _a[_i];
34275             var material = hole.material;
34276             this._updateLineBasicMaterial(material);
34277         }
34278     };
34279     OutlineRenderTag.prototype._updateLine = function (line, points3d) {
34280         var positions = this._getLinePositions(points3d);
34281         var geometry = line.geometry;
34282         var attribute = geometry.getAttribute("position");
34283         attribute.set(positions);
34284         attribute.needsUpdate = true;
34285         geometry.computeBoundingSphere();
34286     };
34287     OutlineRenderTag.prototype._updateOulineGeometry = function () {
34288         var points3d = this._tag.geometry.getPoints3d(this._transform);
34289         this._updateLine(this._outline, points3d);
34290     };
34291     OutlineRenderTag.prototype._updateOutlineMaterial = function () {
34292         var material = this._outline.material;
34293         this._updateLineBasicMaterial(material);
34294     };
34295     OutlineRenderTag.prototype._updateLineBasicMaterial = function (material) {
34296         material.color = new THREE.Color(this._tag.lineColor);
34297         material.linewidth = Math.max(this._tag.lineWidth, 1);
34298         material.visible = this._tag.lineWidth >= 1 && this._tag.lineOpacity > 0;
34299         material.opacity = this._tag.lineOpacity;
34300         material.transparent = this._tag.lineOpacity < 1;
34301         material.needsUpdate = true;
34302     };
34303     return OutlineRenderTag;
34304 }(Component_1.RenderTag));
34305 exports.OutlineRenderTag = OutlineRenderTag;
34306
34307 },{"../../../Component":291,"three":241,"virtual-dom":247}],377:[function(require,module,exports){
34308 "use strict";
34309 var __extends = (this && this.__extends) || (function () {
34310     var extendStatics = Object.setPrototypeOf ||
34311         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34312         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
34313     return function (d, b) {
34314         extendStatics(d, b);
34315         function __() { this.constructor = d; }
34316         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34317     };
34318 })();
34319 Object.defineProperty(exports, "__esModule", { value: true });
34320 var Subject_1 = require("rxjs/Subject");
34321 var Component_1 = require("../../../Component");
34322 var Viewer_1 = require("../../../Viewer");
34323 /**
34324  * @class OutlineTag
34325  *
34326  * @classdesc Tag holding properties for visualizing a geometry outline.
34327  *
34328  * @example
34329  * ```
34330  * var geometry = new Mapillary.TagComponent.RectGeometry([0.3, 0.3, 0.5, 0.4]);
34331  * var tag = new Mapillary.TagComponent.OutlineTag(
34332  *     "id-1",
34333  *     geometry
34334  *     { editable: true, lineColor: 0xff0000 });
34335  *
34336  * tagComponent.add([tag]);
34337  * ```
34338  */
34339 var OutlineTag = /** @class */ (function (_super) {
34340     __extends(OutlineTag, _super);
34341     /**
34342      * Create an outline tag.
34343      *
34344      * @override
34345      * @constructor
34346      * @param {string} id - Unique identifier of the tag.
34347      * @param {VertexGeometry} geometry - Geometry defining vertices of tag.
34348      * @param {IOutlineTagOptions} options - Options defining the visual appearance and
34349      * behavior of the outline tag.
34350      */
34351     function OutlineTag(id, geometry, options) {
34352         var _this = _super.call(this, id, geometry) || this;
34353         options = !!options ? options : {};
34354         _this._editable = options.editable == null ? false : options.editable;
34355         _this._fillColor = options.fillColor == null ? 0xFFFFFF : options.fillColor;
34356         _this._fillOpacity = options.fillOpacity == null ? 0.0 : options.fillOpacity;
34357         _this._icon = options.icon === undefined ? null : options.icon;
34358         _this._iconFloat = options.iconFloat == null ? Viewer_1.Alignment.Center : options.iconFloat;
34359         _this._iconIndex = options.iconIndex == null ? 3 : options.iconIndex;
34360         _this._indicateVertices = options.indicateVertices == null ? true : options.indicateVertices;
34361         _this._lineColor = options.lineColor == null ? 0xFFFFFF : options.lineColor;
34362         _this._lineOpacity = options.lineOpacity == null ? 1 : options.lineOpacity;
34363         _this._lineWidth = options.lineWidth == null ? 1 : options.lineWidth;
34364         _this._text = options.text === undefined ? null : options.text;
34365         _this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor;
34366         _this._click$ = new Subject_1.Subject();
34367         _this._click$
34368             .subscribe(function (t) {
34369             _this.fire(OutlineTag.click, _this);
34370         });
34371         return _this;
34372     }
34373     Object.defineProperty(OutlineTag.prototype, "click$", {
34374         /**
34375          * Click observable.
34376          *
34377          * @description An observable emitting the tag when the icon of the
34378          * tag has been clicked.
34379          *
34380          * @returns {Observable<Tag>}
34381          */
34382         get: function () {
34383             return this._click$;
34384         },
34385         enumerable: true,
34386         configurable: true
34387     });
34388     Object.defineProperty(OutlineTag.prototype, "editable", {
34389         /**
34390          * Get editable property.
34391          * @returns {boolean} Value indicating if tag is editable.
34392          */
34393         get: function () {
34394             return this._editable;
34395         },
34396         /**
34397          * Set editable property.
34398          * @param {boolean}
34399          *
34400          * @fires Tag#changed
34401          */
34402         set: function (value) {
34403             this._editable = value;
34404             this._notifyChanged$.next(this);
34405         },
34406         enumerable: true,
34407         configurable: true
34408     });
34409     Object.defineProperty(OutlineTag.prototype, "fillColor", {
34410         /**
34411          * Get fill color property.
34412          * @returns {number}
34413          */
34414         get: function () {
34415             return this._fillColor;
34416         },
34417         /**
34418          * Set fill color property.
34419          * @param {number}
34420          *
34421          * @fires Tag#changed
34422          */
34423         set: function (value) {
34424             this._fillColor = value;
34425             this._notifyChanged$.next(this);
34426         },
34427         enumerable: true,
34428         configurable: true
34429     });
34430     Object.defineProperty(OutlineTag.prototype, "fillOpacity", {
34431         /**
34432          * Get fill opacity property.
34433          * @returns {number}
34434          */
34435         get: function () {
34436             return this._fillOpacity;
34437         },
34438         /**
34439          * Set fill opacity property.
34440          * @param {number}
34441          *
34442          * @fires Tag#changed
34443          */
34444         set: function (value) {
34445             this._fillOpacity = value;
34446             this._notifyChanged$.next(this);
34447         },
34448         enumerable: true,
34449         configurable: true
34450     });
34451     Object.defineProperty(OutlineTag.prototype, "geometry", {
34452         /** @inheritdoc */
34453         get: function () {
34454             return this._geometry;
34455         },
34456         enumerable: true,
34457         configurable: true
34458     });
34459     Object.defineProperty(OutlineTag.prototype, "icon", {
34460         /**
34461          * Get icon property.
34462          * @returns {string}
34463          */
34464         get: function () {
34465             return this._icon;
34466         },
34467         /**
34468          * Set icon property.
34469          * @param {string}
34470          *
34471          * @fires Tag#changed
34472          */
34473         set: function (value) {
34474             this._icon = value;
34475             this._notifyChanged$.next(this);
34476         },
34477         enumerable: true,
34478         configurable: true
34479     });
34480     Object.defineProperty(OutlineTag.prototype, "iconFloat", {
34481         /**
34482          * Get icon float property.
34483          * @returns {Alignment}
34484          */
34485         get: function () {
34486             return this._iconFloat;
34487         },
34488         /**
34489          * Set icon float property.
34490          * @param {Alignment}
34491          *
34492          * @fires Tag#changed
34493          */
34494         set: function (value) {
34495             this._iconFloat = value;
34496             this._notifyChanged$.next(this);
34497         },
34498         enumerable: true,
34499         configurable: true
34500     });
34501     Object.defineProperty(OutlineTag.prototype, "iconIndex", {
34502         /**
34503          * Get icon index property.
34504          * @returns {number}
34505          */
34506         get: function () {
34507             return this._iconIndex;
34508         },
34509         /**
34510          * Set icon index property.
34511          * @param {number}
34512          *
34513          * @fires Tag#changed
34514          */
34515         set: function (value) {
34516             this._iconIndex = value;
34517             this._notifyChanged$.next(this);
34518         },
34519         enumerable: true,
34520         configurable: true
34521     });
34522     Object.defineProperty(OutlineTag.prototype, "indicateVertices", {
34523         /**
34524          * Get indicate vertices property.
34525          * @returns {boolean} Value indicating if vertices should be indicated
34526          * when tag is editable.
34527          */
34528         get: function () {
34529             return this._indicateVertices;
34530         },
34531         /**
34532          * Set indicate vertices property.
34533          * @param {boolean}
34534          *
34535          * @fires Tag#changed
34536          */
34537         set: function (value) {
34538             this._indicateVertices = value;
34539             this._notifyChanged$.next(this);
34540         },
34541         enumerable: true,
34542         configurable: true
34543     });
34544     Object.defineProperty(OutlineTag.prototype, "lineColor", {
34545         /**
34546          * Get line color property.
34547          * @returns {number}
34548          */
34549         get: function () {
34550             return this._lineColor;
34551         },
34552         /**
34553          * Set line color property.
34554          * @param {number}
34555          *
34556          * @fires Tag#changed
34557          */
34558         set: function (value) {
34559             this._lineColor = value;
34560             this._notifyChanged$.next(this);
34561         },
34562         enumerable: true,
34563         configurable: true
34564     });
34565     Object.defineProperty(OutlineTag.prototype, "lineOpacity", {
34566         /**
34567          * Get line opacity property.
34568          * @returns {number}
34569          */
34570         get: function () {
34571             return this._lineOpacity;
34572         },
34573         /**
34574          * Set line opacity property.
34575          * @param {number}
34576          *
34577          * @fires Tag#changed
34578          */
34579         set: function (value) {
34580             this._lineOpacity = value;
34581             this._notifyChanged$.next(this);
34582         },
34583         enumerable: true,
34584         configurable: true
34585     });
34586     Object.defineProperty(OutlineTag.prototype, "lineWidth", {
34587         /**
34588          * Get line width property.
34589          * @returns {number}
34590          */
34591         get: function () {
34592             return this._lineWidth;
34593         },
34594         /**
34595          * Set line width property.
34596          * @param {number}
34597          *
34598          * @fires Tag#changed
34599          */
34600         set: function (value) {
34601             this._lineWidth = value;
34602             this._notifyChanged$.next(this);
34603         },
34604         enumerable: true,
34605         configurable: true
34606     });
34607     Object.defineProperty(OutlineTag.prototype, "text", {
34608         /**
34609          * Get text property.
34610          * @returns {string}
34611          */
34612         get: function () {
34613             return this._text;
34614         },
34615         /**
34616          * Set text property.
34617          * @param {string}
34618          *
34619          * @fires Tag#changed
34620          */
34621         set: function (value) {
34622             this._text = value;
34623             this._notifyChanged$.next(this);
34624         },
34625         enumerable: true,
34626         configurable: true
34627     });
34628     Object.defineProperty(OutlineTag.prototype, "textColor", {
34629         /**
34630          * Get text color property.
34631          * @returns {number}
34632          */
34633         get: function () {
34634             return this._textColor;
34635         },
34636         /**
34637          * Set text color property.
34638          * @param {number}
34639          *
34640          * @fires Tag#changed
34641          */
34642         set: function (value) {
34643             this._textColor = value;
34644             this._notifyChanged$.next(this);
34645         },
34646         enumerable: true,
34647         configurable: true
34648     });
34649     /**
34650      * Set options for tag.
34651      *
34652      * @description Sets all the option properties provided and keeps
34653      * the rest of the values as is.
34654      *
34655      * @param {IOutlineTagOptions} options - Outline tag options
34656      *
34657      * @fires {Tag#changed}
34658      */
34659     OutlineTag.prototype.setOptions = function (options) {
34660         this._editable = options.editable == null ? this._editable : options.editable;
34661         this._icon = options.icon === undefined ? this._icon : options.icon;
34662         this._iconFloat = options.iconFloat == null ? this._iconFloat : options.iconFloat;
34663         this._iconIndex = options.iconIndex == null ? this._iconIndex : options.iconIndex;
34664         this._indicateVertices = options.indicateVertices == null ? this._indicateVertices : options.indicateVertices;
34665         this._lineColor = options.lineColor == null ? this._lineColor : options.lineColor;
34666         this._lineWidth = options.lineWidth == null ? this._lineWidth : options.lineWidth;
34667         this._fillColor = options.fillColor == null ? this._fillColor : options.fillColor;
34668         this._fillOpacity = options.fillOpacity == null ? this._fillOpacity : options.fillOpacity;
34669         this._text = options.text === undefined ? this._text : options.text;
34670         this._textColor = options.textColor == null ? this._textColor : options.textColor;
34671         this._notifyChanged$.next(this);
34672     };
34673     /**
34674      * Event fired when the icon of the outline tag is clicked.
34675      *
34676      * @event OutlineTag#click
34677      * @type {OutlineTag} The tag instance that was clicked.
34678      */
34679     OutlineTag.click = "click";
34680     return OutlineTag;
34681 }(Component_1.Tag));
34682 exports.OutlineTag = OutlineTag;
34683 exports.default = OutlineTag;
34684
34685 },{"../../../Component":291,"../../../Viewer":302,"rxjs/Subject":34}],378:[function(require,module,exports){
34686 "use strict";
34687 /// <reference path="../../../../typings/index.d.ts" />
34688 Object.defineProperty(exports, "__esModule", { value: true });
34689 var Subject_1 = require("rxjs/Subject");
34690 var Geo_1 = require("../../../Geo");
34691 var RenderTag = /** @class */ (function () {
34692     function RenderTag(tag, transform, viewportCoords) {
34693         this._tag = tag;
34694         this._transform = transform;
34695         this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
34696         this._glObjectsChanged$ = new Subject_1.Subject();
34697         this._interact$ = new Subject_1.Subject();
34698     }
34699     Object.defineProperty(RenderTag.prototype, "glObjectsChanged$", {
34700         get: function () {
34701             return this._glObjectsChanged$;
34702         },
34703         enumerable: true,
34704         configurable: true
34705     });
34706     Object.defineProperty(RenderTag.prototype, "interact$", {
34707         get: function () {
34708             return this._interact$;
34709         },
34710         enumerable: true,
34711         configurable: true
34712     });
34713     Object.defineProperty(RenderTag.prototype, "tag", {
34714         get: function () {
34715             return this._tag;
34716         },
34717         enumerable: true,
34718         configurable: true
34719     });
34720     return RenderTag;
34721 }());
34722 exports.RenderTag = RenderTag;
34723 exports.default = RenderTag;
34724
34725 },{"../../../Geo":294,"rxjs/Subject":34}],379:[function(require,module,exports){
34726 "use strict";
34727 /// <reference path="../../../../typings/index.d.ts" />
34728 var __extends = (this && this.__extends) || (function () {
34729     var extendStatics = Object.setPrototypeOf ||
34730         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34731         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
34732     return function (d, b) {
34733         extendStatics(d, b);
34734         function __() { this.constructor = d; }
34735         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34736     };
34737 })();
34738 Object.defineProperty(exports, "__esModule", { value: true });
34739 var vd = require("virtual-dom");
34740 var Component_1 = require("../../../Component");
34741 var Viewer_1 = require("../../../Viewer");
34742 /**
34743  * @class SpotRenderTag
34744  * @classdesc Tag visualizing the properties of a SpotTag.
34745  */
34746 var SpotRenderTag = /** @class */ (function (_super) {
34747     __extends(SpotRenderTag, _super);
34748     function SpotRenderTag() {
34749         return _super !== null && _super.apply(this, arguments) || this;
34750     }
34751     SpotRenderTag.prototype.dispose = function () { };
34752     SpotRenderTag.prototype.getDOMObjects = function (atlas, camera, size) {
34753         var _this = this;
34754         var tag = this._tag;
34755         var container = {
34756             offsetHeight: size.height, offsetWidth: size.width,
34757         };
34758         var vNodes = [];
34759         var _a = tag.geometry.getCentroid2d(), centroidBasicX = _a[0], centroidBasicY = _a[1];
34760         var centroidCanvas = this._viewportCoords.basicToCanvasSafe(centroidBasicX, centroidBasicY, container, this._transform, camera);
34761         if (centroidCanvas != null) {
34762             var interactNone = function (e) {
34763                 _this._interact$.next({ offsetX: 0, offsetY: 0, operation: Component_1.TagOperation.None, tag: tag });
34764             };
34765             var canvasX = Math.round(centroidCanvas[0]);
34766             var canvasY = Math.round(centroidCanvas[1]);
34767             if (tag.icon != null) {
34768                 if (atlas.loaded) {
34769                     var sprite = atlas.getDOMSprite(tag.icon, Viewer_1.Alignment.Bottom);
34770                     var iconTransform = "translate(" + canvasX + "px," + (canvasY + 8) + "px)";
34771                     var properties = {
34772                         onmousedown: interactNone,
34773                         style: {
34774                             pointerEvents: "all",
34775                             transform: iconTransform,
34776                         },
34777                     };
34778                     vNodes.push(vd.h("div", properties, [sprite]));
34779                 }
34780             }
34781             else if (tag.text != null) {
34782                 var textTransform = "translate(-50%,0%) translate(" + canvasX + "px," + (canvasY + 8) + "px)";
34783                 var properties = {
34784                     onmousedown: interactNone,
34785                     style: {
34786                         color: this._colorToCss(tag.textColor),
34787                         transform: textTransform,
34788                     },
34789                     textContent: tag.text,
34790                 };
34791                 vNodes.push(vd.h("span.TagSymbol", properties, []));
34792             }
34793             var interact = this._interact(Component_1.TagOperation.Centroid, tag, "move");
34794             var background = this._colorToCss(tag.color);
34795             var transform = "translate(-50%,-50%) translate(" + canvasX + "px," + canvasY + "px)";
34796             if (tag.editable) {
34797                 var interactorProperties = {
34798                     onmousedown: interact,
34799                     style: {
34800                         background: background,
34801                         transform: transform,
34802                     },
34803                 };
34804                 vNodes.push(vd.h("div.TagSpotInteractor", interactorProperties, []));
34805             }
34806             var pointProperties = {
34807                 style: {
34808                     background: background,
34809                     transform: transform,
34810                 },
34811             };
34812             vNodes.push(vd.h("div.TagVertex", pointProperties, []));
34813         }
34814         return vNodes;
34815     };
34816     SpotRenderTag.prototype.getGLObjects = function () { return []; };
34817     SpotRenderTag.prototype.getRetrievableObjects = function () { return []; };
34818     SpotRenderTag.prototype._colorToCss = function (color) {
34819         return "#" + ("000000" + color.toString(16)).substr(-6);
34820     };
34821     SpotRenderTag.prototype._interact = function (operation, tag, cursor, vertexIndex) {
34822         var _this = this;
34823         return function (e) {
34824             var offsetX = e.offsetX - e.target.offsetWidth / 2;
34825             var offsetY = e.offsetY - e.target.offsetHeight / 2;
34826             _this._interact$.next({
34827                 cursor: cursor,
34828                 offsetX: offsetX,
34829                 offsetY: offsetY,
34830                 operation: operation,
34831                 tag: tag,
34832                 vertexIndex: vertexIndex,
34833             });
34834         };
34835     };
34836     return SpotRenderTag;
34837 }(Component_1.RenderTag));
34838 exports.SpotRenderTag = SpotRenderTag;
34839
34840 },{"../../../Component":291,"../../../Viewer":302,"virtual-dom":247}],380:[function(require,module,exports){
34841 "use strict";
34842 var __extends = (this && this.__extends) || (function () {
34843     var extendStatics = Object.setPrototypeOf ||
34844         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
34845         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
34846     return function (d, b) {
34847         extendStatics(d, b);
34848         function __() { this.constructor = d; }
34849         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34850     };
34851 })();
34852 Object.defineProperty(exports, "__esModule", { value: true });
34853 var Component_1 = require("../../../Component");
34854 /**
34855  * @class SpotTag
34856  *
34857  * @classdesc Tag holding properties for visualizing the centroid of a geometry.
34858  *
34859  * @example
34860  * ```
34861  * var geometry = new Mapillary.TagComponent.PointGeometry([0.3, 0.3]);
34862  * var tag = new Mapillary.TagComponent.SpotTag(
34863  *     "id-1",
34864  *     geometry
34865  *     { editable: true, color: 0xff0000 });
34866  *
34867  * tagComponent.add([tag]);
34868  * ```
34869  */
34870 var SpotTag = /** @class */ (function (_super) {
34871     __extends(SpotTag, _super);
34872     /**
34873      * Create a spot tag.
34874      *
34875      * @override
34876      * @constructor
34877      * @param {string} id
34878      * @param {Geometry} geometry
34879      * @param {IOutlineTagOptions} options - Options defining the visual appearance and
34880      * behavior of the spot tag.
34881      */
34882     function SpotTag(id, geometry, options) {
34883         var _this = _super.call(this, id, geometry) || this;
34884         options = !!options ? options : {};
34885         _this._color = options.color == null ? 0xFFFFFF : options.color;
34886         _this._editable = options.editable == null ? false : options.editable;
34887         _this._icon = options.icon === undefined ? null : options.icon;
34888         _this._text = options.text === undefined ? null : options.text;
34889         _this._textColor = options.textColor == null ? 0xFFFFFF : options.textColor;
34890         return _this;
34891     }
34892     Object.defineProperty(SpotTag.prototype, "color", {
34893         /**
34894          * Get color property.
34895          * @returns {number} The color of the spot as a hexagonal number;
34896          */
34897         get: function () {
34898             return this._color;
34899         },
34900         /**
34901          * Set color property.
34902          * @param {number}
34903          *
34904          * @fires Tag#changed
34905          */
34906         set: function (value) {
34907             this._color = value;
34908             this._notifyChanged$.next(this);
34909         },
34910         enumerable: true,
34911         configurable: true
34912     });
34913     Object.defineProperty(SpotTag.prototype, "editable", {
34914         /**
34915          * Get editable property.
34916          * @returns {boolean} Value indicating if tag is editable.
34917          */
34918         get: function () {
34919             return this._editable;
34920         },
34921         /**
34922          * Set editable property.
34923          * @param {boolean}
34924          *
34925          * @fires Tag#changed
34926          */
34927         set: function (value) {
34928             this._editable = value;
34929             this._notifyChanged$.next(this);
34930         },
34931         enumerable: true,
34932         configurable: true
34933     });
34934     Object.defineProperty(SpotTag.prototype, "icon", {
34935         /**
34936          * Get icon property.
34937          * @returns {string}
34938          */
34939         get: function () {
34940             return this._icon;
34941         },
34942         /**
34943          * Set icon property.
34944          * @param {string}
34945          *
34946          * @fires Tag#changed
34947          */
34948         set: function (value) {
34949             this._icon = value;
34950             this._notifyChanged$.next(this);
34951         },
34952         enumerable: true,
34953         configurable: true
34954     });
34955     Object.defineProperty(SpotTag.prototype, "text", {
34956         /**
34957          * Get text property.
34958          * @returns {string}
34959          */
34960         get: function () {
34961             return this._text;
34962         },
34963         /**
34964          * Set text property.
34965          * @param {string}
34966          *
34967          * @fires Tag#changed
34968          */
34969         set: function (value) {
34970             this._text = value;
34971             this._notifyChanged$.next(this);
34972         },
34973         enumerable: true,
34974         configurable: true
34975     });
34976     Object.defineProperty(SpotTag.prototype, "textColor", {
34977         /**
34978          * Get text color property.
34979          * @returns {number}
34980          */
34981         get: function () {
34982             return this._textColor;
34983         },
34984         /**
34985          * Set text color property.
34986          * @param {number}
34987          *
34988          * @fires Tag#changed
34989          */
34990         set: function (value) {
34991             this._textColor = value;
34992             this._notifyChanged$.next(this);
34993         },
34994         enumerable: true,
34995         configurable: true
34996     });
34997     /**
34998      * Set options for tag.
34999      *
35000      * @description Sets all the option properties provided and keps
35001      * the rest of the values as is.
35002      *
35003      * @param {ISpotTagOptions} options - Spot tag options
35004      *
35005      * @fires {Tag#changed}
35006      */
35007     SpotTag.prototype.setOptions = function (options) {
35008         this._color = options.color == null ? this._color : options.color;
35009         this._editable = options.editable == null ? this._editable : options.editable;
35010         this._icon = options.icon === undefined ? this._icon : options.icon;
35011         this._text = options.text === undefined ? this._text : options.text;
35012         this._textColor = options.textColor == null ? this._textColor : options.textColor;
35013         this._notifyChanged$.next(this);
35014     };
35015     return SpotTag;
35016 }(Component_1.Tag));
35017 exports.SpotTag = SpotTag;
35018 exports.default = SpotTag;
35019
35020 },{"../../../Component":291}],381:[function(require,module,exports){
35021 "use strict";
35022 var __extends = (this && this.__extends) || (function () {
35023     var extendStatics = Object.setPrototypeOf ||
35024         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
35025         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
35026     return function (d, b) {
35027         extendStatics(d, b);
35028         function __() { this.constructor = d; }
35029         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
35030     };
35031 })();
35032 Object.defineProperty(exports, "__esModule", { value: true });
35033 var Subject_1 = require("rxjs/Subject");
35034 require("rxjs/add/operator/map");
35035 require("rxjs/add/operator/share");
35036 var Utils_1 = require("../../../Utils");
35037 /**
35038  * @class Tag
35039  * @abstract
35040  * @classdesc Abstract class representing the basic functionality of for a tag.
35041  */
35042 var Tag = /** @class */ (function (_super) {
35043     __extends(Tag, _super);
35044     /**
35045      * Create a tag.
35046      *
35047      * @constructor
35048      * @param {string} id
35049      * @param {Geometry} geometry
35050      */
35051     function Tag(id, geometry) {
35052         var _this = _super.call(this) || this;
35053         _this._id = id;
35054         _this._geometry = geometry;
35055         _this._notifyChanged$ = new Subject_1.Subject();
35056         _this._notifyChanged$
35057             .subscribe(function (t) {
35058             _this.fire(Tag.changed, _this);
35059         });
35060         _this._geometry.changed$
35061             .subscribe(function (g) {
35062             _this.fire(Tag.geometrychanged, _this);
35063         });
35064         return _this;
35065     }
35066     Object.defineProperty(Tag.prototype, "id", {
35067         /**
35068          * Get id property.
35069          * @returns {string}
35070          */
35071         get: function () {
35072             return this._id;
35073         },
35074         enumerable: true,
35075         configurable: true
35076     });
35077     Object.defineProperty(Tag.prototype, "geometry", {
35078         /**
35079          * Get geometry property.
35080          * @returns {Geometry} The geometry of the tag.
35081          */
35082         get: function () {
35083             return this._geometry;
35084         },
35085         enumerable: true,
35086         configurable: true
35087     });
35088     Object.defineProperty(Tag.prototype, "changed$", {
35089         /**
35090          * Get changed observable.
35091          * @returns {Observable<Tag>}
35092          * @ignore
35093          */
35094         get: function () {
35095             return this._notifyChanged$;
35096         },
35097         enumerable: true,
35098         configurable: true
35099     });
35100     Object.defineProperty(Tag.prototype, "geometryChanged$", {
35101         /**
35102          * Get geometry changed observable.
35103          * @returns {Observable<Tag>}
35104          * @ignore
35105          */
35106         get: function () {
35107             var _this = this;
35108             return this._geometry.changed$
35109                 .map(function (geometry) {
35110                 return _this;
35111             })
35112                 .share();
35113         },
35114         enumerable: true,
35115         configurable: true
35116     });
35117     /**
35118      * Event fired when a property related to the visual appearance of the
35119      * tag has changed.
35120      *
35121      * @event Tag#changed
35122      * @type {Tag} The tag instance that has changed.
35123      */
35124     Tag.changed = "changed";
35125     /**
35126      * Event fired when the geometry of the tag has changed.
35127      *
35128      * @event Tag#geometrychanged
35129      * @type {Tag} The tag instance whose geometry has changed.
35130      */
35131     Tag.geometrychanged = "geometrychanged";
35132     return Tag;
35133 }(Utils_1.EventEmitter));
35134 exports.Tag = Tag;
35135 exports.default = Tag;
35136
35137 },{"../../../Utils":301,"rxjs/Subject":34,"rxjs/add/operator/map":67,"rxjs/add/operator/share":79}],382:[function(require,module,exports){
35138 "use strict";
35139 Object.defineProperty(exports, "__esModule", { value: true });
35140 var HandlerBase = /** @class */ (function () {
35141     function HandlerBase(component, container, navigator) {
35142         this._component = component;
35143         this._container = container;
35144         this._navigator = navigator;
35145         this._enabled = false;
35146     }
35147     Object.defineProperty(HandlerBase.prototype, "isEnabled", {
35148         /**
35149          * Returns a Boolean indicating whether the interaction is enabled.
35150          *
35151          * @returns {boolean} `true` if the interaction is enabled.
35152          */
35153         get: function () {
35154             return this._enabled;
35155         },
35156         enumerable: true,
35157         configurable: true
35158     });
35159     /**
35160      * Enables the interaction.
35161      *
35162      * @example ```<component-name>.<handler-name>.enable();```
35163      */
35164     HandlerBase.prototype.enable = function () {
35165         if (this._enabled || !this._component.activated) {
35166             return;
35167         }
35168         this._enable();
35169         this._enabled = true;
35170         this._component.configure(this._getConfiguration(true));
35171     };
35172     /**
35173      * Disables the interaction.
35174      *
35175      * @example ```<component-name>.<handler-name>.disable();```
35176      */
35177     HandlerBase.prototype.disable = function () {
35178         if (!this._enabled) {
35179             return;
35180         }
35181         this._disable();
35182         this._enabled = false;
35183         if (this._component.activated) {
35184             this._component.configure(this._getConfiguration(false));
35185         }
35186     };
35187     return HandlerBase;
35188 }());
35189 exports.HandlerBase = HandlerBase;
35190 exports.default = HandlerBase;
35191
35192 },{}],383:[function(require,module,exports){
35193 "use strict";
35194 var __extends = (this && this.__extends) || (function () {
35195     var extendStatics = Object.setPrototypeOf ||
35196         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
35197         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
35198     return function (d, b) {
35199         extendStatics(d, b);
35200         function __() { this.constructor = d; }
35201         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
35202     };
35203 })();
35204 Object.defineProperty(exports, "__esModule", { value: true });
35205 var MapillaryError_1 = require("./MapillaryError");
35206 var AbortMapillaryError = /** @class */ (function (_super) {
35207     __extends(AbortMapillaryError, _super);
35208     function AbortMapillaryError(message) {
35209         var _this = _super.call(this, message != null ? message : "The request was aborted.") || this;
35210         Object.setPrototypeOf(_this, AbortMapillaryError.prototype);
35211         _this.name = "AbortMapillaryError";
35212         return _this;
35213     }
35214     return AbortMapillaryError;
35215 }(MapillaryError_1.MapillaryError));
35216 exports.AbortMapillaryError = AbortMapillaryError;
35217 exports.default = AbortMapillaryError;
35218
35219 },{"./MapillaryError":386}],384:[function(require,module,exports){
35220 "use strict";
35221 var __extends = (this && this.__extends) || (function () {
35222     var extendStatics = Object.setPrototypeOf ||
35223         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
35224         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
35225     return function (d, b) {
35226         extendStatics(d, b);
35227         function __() { this.constructor = d; }
35228         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
35229     };
35230 })();
35231 Object.defineProperty(exports, "__esModule", { value: true });
35232 var MapillaryError_1 = require("./MapillaryError");
35233 var ArgumentMapillaryError = /** @class */ (function (_super) {
35234     __extends(ArgumentMapillaryError, _super);
35235     function ArgumentMapillaryError(message) {
35236         var _this = _super.call(this, message != null ? message : "The argument is not valid.") || this;
35237         Object.setPrototypeOf(_this, ArgumentMapillaryError.prototype);
35238         _this.name = "ArgumentMapillaryError";
35239         return _this;
35240     }
35241     return ArgumentMapillaryError;
35242 }(MapillaryError_1.MapillaryError));
35243 exports.ArgumentMapillaryError = ArgumentMapillaryError;
35244 exports.default = ArgumentMapillaryError;
35245
35246 },{"./MapillaryError":386}],385:[function(require,module,exports){
35247 "use strict";
35248 var __extends = (this && this.__extends) || (function () {
35249     var extendStatics = Object.setPrototypeOf ||
35250         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
35251         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
35252     return function (d, b) {
35253         extendStatics(d, b);
35254         function __() { this.constructor = d; }
35255         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
35256     };
35257 })();
35258 Object.defineProperty(exports, "__esModule", { value: true });
35259 var MapillaryError_1 = require("./MapillaryError");
35260 var GraphMapillaryError = /** @class */ (function (_super) {
35261     __extends(GraphMapillaryError, _super);
35262     function GraphMapillaryError(message) {
35263         var _this = _super.call(this, message) || this;
35264         Object.setPrototypeOf(_this, GraphMapillaryError.prototype);
35265         _this.name = "GraphMapillaryError";
35266         return _this;
35267     }
35268     return GraphMapillaryError;
35269 }(MapillaryError_1.MapillaryError));
35270 exports.GraphMapillaryError = GraphMapillaryError;
35271 exports.default = GraphMapillaryError;
35272
35273 },{"./MapillaryError":386}],386:[function(require,module,exports){
35274 "use strict";
35275 var __extends = (this && this.__extends) || (function () {
35276     var extendStatics = Object.setPrototypeOf ||
35277         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
35278         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
35279     return function (d, b) {
35280         extendStatics(d, b);
35281         function __() { this.constructor = d; }
35282         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
35283     };
35284 })();
35285 Object.defineProperty(exports, "__esModule", { value: true });
35286 var MapillaryError = /** @class */ (function (_super) {
35287     __extends(MapillaryError, _super);
35288     function MapillaryError(message) {
35289         var _this = _super.call(this, message) || this;
35290         Object.setPrototypeOf(_this, MapillaryError.prototype);
35291         _this.name = "MapillaryError";
35292         return _this;
35293     }
35294     return MapillaryError;
35295 }(Error));
35296 exports.MapillaryError = MapillaryError;
35297 exports.default = MapillaryError;
35298
35299 },{}],387:[function(require,module,exports){
35300 "use strict";
35301 /// <reference path="../../typings/index.d.ts" />
35302 Object.defineProperty(exports, "__esModule", { value: true });
35303 var THREE = require("three");
35304 /**
35305  * @class Camera
35306  *
35307  * @classdesc Holds information about a camera.
35308  */
35309 var Camera = /** @class */ (function () {
35310     /**
35311      * Create a new camera instance.
35312      * @param {Transform} [transform] - Optional transform instance.
35313      */
35314     function Camera(transform) {
35315         if (transform != null) {
35316             this._position = new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 0));
35317             this._lookat = new THREE.Vector3().fromArray(transform.unprojectSfM([0, 0], 10));
35318             this._up = transform.upVector();
35319             this._focal = this._getFocal(transform);
35320         }
35321         else {
35322             this._position = new THREE.Vector3(0, 0, 0);
35323             this._lookat = new THREE.Vector3(0, 0, 1);
35324             this._up = new THREE.Vector3(0, -1, 0);
35325             this._focal = 1;
35326         }
35327     }
35328     Object.defineProperty(Camera.prototype, "position", {
35329         /**
35330          * Get position.
35331          * @returns {THREE.Vector3} The position vector.
35332          */
35333         get: function () {
35334             return this._position;
35335         },
35336         enumerable: true,
35337         configurable: true
35338     });
35339     Object.defineProperty(Camera.prototype, "lookat", {
35340         /**
35341          * Get lookat.
35342          * @returns {THREE.Vector3} The lookat vector.
35343          */
35344         get: function () {
35345             return this._lookat;
35346         },
35347         enumerable: true,
35348         configurable: true
35349     });
35350     Object.defineProperty(Camera.prototype, "up", {
35351         /**
35352          * Get up.
35353          * @returns {THREE.Vector3} The up vector.
35354          */
35355         get: function () {
35356             return this._up;
35357         },
35358         enumerable: true,
35359         configurable: true
35360     });
35361     Object.defineProperty(Camera.prototype, "focal", {
35362         /**
35363          * Get focal.
35364          * @returns {number} The focal length.
35365          */
35366         get: function () {
35367             return this._focal;
35368         },
35369         /**
35370          * Set focal.
35371          */
35372         set: function (value) {
35373             this._focal = value;
35374         },
35375         enumerable: true,
35376         configurable: true
35377     });
35378     /**
35379      * Update this camera to the linearly interpolated value of two other cameras.
35380      *
35381      * @param {Camera} a - First camera.
35382      * @param {Camera} b - Second camera.
35383      * @param {number} alpha - Interpolation value on the interval [0, 1].
35384      */
35385     Camera.prototype.lerpCameras = function (a, b, alpha) {
35386         this._position.subVectors(b.position, a.position).multiplyScalar(alpha).add(a.position);
35387         this._lookat.subVectors(b.lookat, a.lookat).multiplyScalar(alpha).add(a.lookat);
35388         this._up.subVectors(b.up, a.up).multiplyScalar(alpha).add(a.up);
35389         this._focal = (1 - alpha) * a.focal + alpha * b.focal;
35390     };
35391     /**
35392      * Copy the properties of another camera to this camera.
35393      *
35394      * @param {Camera} other - Another camera.
35395      */
35396     Camera.prototype.copy = function (other) {
35397         this._position.copy(other.position);
35398         this._lookat.copy(other.lookat);
35399         this._up.copy(other.up);
35400         this._focal = other.focal;
35401     };
35402     /**
35403      * Clone this camera.
35404      *
35405      * @returns {Camera} A camera with cloned properties equal to this camera.
35406      */
35407     Camera.prototype.clone = function () {
35408         var camera = new Camera();
35409         camera.position.copy(this._position);
35410         camera.lookat.copy(this._lookat);
35411         camera.up.copy(this._up);
35412         camera.focal = this._focal;
35413         return camera;
35414     };
35415     /**
35416      * Determine the distance between this camera and another camera.
35417      *
35418      * @param {Camera} other - Another camera.
35419      * @returns {number} The distance between the cameras.
35420      */
35421     Camera.prototype.diff = function (other) {
35422         var pd = this._position.distanceToSquared(other.position);
35423         var ld = this._lookat.distanceToSquared(other.lookat);
35424         var ud = this._up.distanceToSquared(other.up);
35425         var fd = 100 * Math.abs(this._focal - other.focal);
35426         return Math.max(pd, ld, ud, fd);
35427     };
35428     /**
35429      * Get the focal length based on the transform.
35430      *
35431      * @description Returns the focal length of the transform if gpano info is not available.
35432      * Returns a focal length corresponding to a vertical fov clamped to [45, 90] degrees based on
35433      * the gpano information if available.
35434      *
35435      * @returns {number} Focal length.
35436      */
35437     Camera.prototype._getFocal = function (transform) {
35438         if (transform.gpano == null) {
35439             return transform.focal;
35440         }
35441         var vFov = Math.PI * transform.gpano.CroppedAreaImageHeightPixels / transform.gpano.FullPanoHeightPixels;
35442         var focal = 0.5 / Math.tan(vFov / 2);
35443         return Math.min(1 / (2 * (Math.sqrt(2) - 1)), Math.max(0.5, focal));
35444     };
35445     return Camera;
35446 }());
35447 exports.Camera = Camera;
35448
35449 },{"three":241}],388:[function(require,module,exports){
35450 "use strict";
35451 Object.defineProperty(exports, "__esModule", { value: true });
35452 /**
35453  * @class GeoCoords
35454  *
35455  * @classdesc Converts coordinates between the geodetic (WGS84),
35456  * Earth-Centered, Earth-Fixed (ECEF) and local topocentric
35457  * East, North, Up (ENU) reference frames.
35458  *
35459  * The WGS84 has latitude (degrees), longitude (degrees) and
35460  * altitude (meters) values.
35461  *
35462  * The ECEF Z-axis pierces the north pole and the
35463  * XY-axis defines the equatorial plane. The X-axis extends
35464  * from the geocenter to the intersection of the Equator and
35465  * the Greenwich Meridian. All values in meters.
35466  *
35467  * The WGS84 parameters are:
35468  *
35469  * a = 6378137
35470  * b = a * (1 - f)
35471  * f = 1 / 298.257223563
35472  * e = Math.sqrt((a^2 - b^2) / a^2)
35473  * e' = Math.sqrt((a^2 - b^2) / b^2)
35474  *
35475  * The WGS84 to ECEF conversion is performed using the following:
35476  *
35477  * X = (N - h) * cos(phi) * cos(lambda)
35478  * Y = (N + h) * cos(phi) * sin(lambda)
35479  * Z = (b^2 * N / a^2 + h) * sin(phi)
35480  *
35481  * where
35482  *
35483  * phi = latitude
35484  * lambda = longitude
35485  * h = height above ellipsoid (altitude)
35486  * N = Radius of curvature (meters)
35487  *   = a / Math.sqrt(1 - e^2 * sin(phi)^2)
35488  *
35489  * The ECEF to WGS84 conversion is performed using the following:
35490  *
35491  * phi = arctan((Z + e'^2 * b * sin(theta)^3) / (p - e^2 * a * cos(theta)^3))
35492  * lambda = arctan(Y / X)
35493  * h = p / cos(phi) - N
35494  *
35495  * where
35496  *
35497  * p = Math.sqrt(X^2 + Y^2)
35498  * theta = arctan(Z * a / p * b)
35499  *
35500  * In the ENU reference frame the x-axis points to the
35501  * East, the y-axis to the North and the z-axis Up. All values
35502  * in meters.
35503  *
35504  * The ECEF to ENU conversion is performed using the following:
35505  *
35506  * | x |   |       -sin(lambda_r)                cos(lambda_r)             0      | | X - X_r |
35507  * | y | = | -sin(phi_r) * cos(lambda_r)  -sin(phi_r) * sin(lambda_r)  cos(phi_r) | | Y - Y_r |
35508  * | z |   |  cos(phi_r) * cos(lambda_r)   cos(phi_r) * sin(lambda_r)  sin(phi_r) | | Z - Z_r |
35509  *
35510  * where
35511  *
35512  * phi_r = latitude of reference
35513  * lambda_r = longitude of reference
35514  * X_r, Y_r, Z_r = ECEF coordinates of reference
35515  *
35516  * The ENU to ECEF conversion is performed by solving the above equation for X, Y, Z.
35517  *
35518  * WGS84 to ENU and ENU to WGS84 are two step conversions with ECEF calculated in
35519  * the first step for both conversions.
35520  */
35521 var GeoCoords = /** @class */ (function () {
35522     function GeoCoords() {
35523         this._wgs84a = 6378137.0;
35524         this._wgs84b = 6356752.31424518;
35525     }
35526     /**
35527      * Convert coordinates from geodetic (WGS84) reference to local topocentric
35528      * (ENU) reference.
35529      *
35530      * @param {number} lat Latitude in degrees.
35531      * @param {number} lon Longitude in degrees.
35532      * @param {number} alt Altitude in meters.
35533      * @param {number} refLat Reference latitude in degrees.
35534      * @param {number} refLon Reference longitude in degrees.
35535      * @param {number} refAlt Reference altitude in meters.
35536      * @returns {Array<number>} The x, y, z local topocentric ENU coordinates.
35537      */
35538     GeoCoords.prototype.geodeticToEnu = function (lat, lon, alt, refLat, refLon, refAlt) {
35539         var ecef = this.geodeticToEcef(lat, lon, alt);
35540         return this.ecefToEnu(ecef[0], ecef[1], ecef[2], refLat, refLon, refAlt);
35541     };
35542     /**
35543      * Convert coordinates from local topocentric (ENU) reference to
35544      * geodetic (WGS84) reference.
35545      *
35546      * @param {number} x Topocentric ENU coordinate in East direction.
35547      * @param {number} y Topocentric ENU coordinate in North direction.
35548      * @param {number} z Topocentric ENU coordinate in Up direction.
35549      * @param {number} refLat Reference latitude in degrees.
35550      * @param {number} refLon Reference longitude in degrees.
35551      * @param {number} refAlt Reference altitude in meters.
35552      * @returns {Array<number>} The latitude and longitude in degrees
35553      *                          as well as altitude in meters.
35554      */
35555     GeoCoords.prototype.enuToGeodetic = function (x, y, z, refLat, refLon, refAlt) {
35556         var ecef = this.enuToEcef(x, y, z, refLat, refLon, refAlt);
35557         return this.ecefToGeodetic(ecef[0], ecef[1], ecef[2]);
35558     };
35559     /**
35560      * Convert coordinates from Earth-Centered, Earth-Fixed (ECEF) reference
35561      * to local topocentric (ENU) reference.
35562      *
35563      * @param {number} X ECEF X-value.
35564      * @param {number} Y ECEF Y-value.
35565      * @param {number} Z ECEF Z-value.
35566      * @param {number} refLat Reference latitude in degrees.
35567      * @param {number} refLon Reference longitude in degrees.
35568      * @param {number} refAlt Reference altitude in meters.
35569      * @returns {Array<number>} The x, y, z topocentric ENU coordinates in East, North
35570      * and Up directions respectively.
35571      */
35572     GeoCoords.prototype.ecefToEnu = function (X, Y, Z, refLat, refLon, refAlt) {
35573         var refEcef = this.geodeticToEcef(refLat, refLon, refAlt);
35574         var V = [X - refEcef[0], Y - refEcef[1], Z - refEcef[2]];
35575         refLat = refLat * Math.PI / 180.0;
35576         refLon = refLon * Math.PI / 180.0;
35577         var cosLat = Math.cos(refLat);
35578         var sinLat = Math.sin(refLat);
35579         var cosLon = Math.cos(refLon);
35580         var sinLon = Math.sin(refLon);
35581         var x = -sinLon * V[0] + cosLon * V[1];
35582         var y = -sinLat * cosLon * V[0] - sinLat * sinLon * V[1] + cosLat * V[2];
35583         var z = cosLat * cosLon * V[0] + cosLat * sinLon * V[1] + sinLat * V[2];
35584         return [x, y, z];
35585     };
35586     /**
35587      * Convert coordinates from local topocentric (ENU) reference
35588      * to Earth-Centered, Earth-Fixed (ECEF) reference.
35589      *
35590      * @param {number} x Topocentric ENU coordinate in East direction.
35591      * @param {number} y Topocentric ENU coordinate in North direction.
35592      * @param {number} z Topocentric ENU coordinate in Up direction.
35593      * @param {number} refLat Reference latitude in degrees.
35594      * @param {number} refLon Reference longitude in degrees.
35595      * @param {number} refAlt Reference altitude in meters.
35596      * @returns {Array<number>} The X, Y, Z ECEF coordinates.
35597      */
35598     GeoCoords.prototype.enuToEcef = function (x, y, z, refLat, refLon, refAlt) {
35599         var refEcef = this.geodeticToEcef(refLat, refLon, refAlt);
35600         refLat = refLat * Math.PI / 180.0;
35601         refLon = refLon * Math.PI / 180.0;
35602         var cosLat = Math.cos(refLat);
35603         var sinLat = Math.sin(refLat);
35604         var cosLon = Math.cos(refLon);
35605         var sinLon = Math.sin(refLon);
35606         var X = -sinLon * x - sinLat * cosLon * y + cosLat * cosLon * z + refEcef[0];
35607         var Y = cosLon * x - sinLat * sinLon * y + cosLat * sinLon * z + refEcef[1];
35608         var Z = cosLat * y + sinLat * z + refEcef[2];
35609         return [X, Y, Z];
35610     };
35611     /**
35612      * Convert coordinates from geodetic reference (WGS84) to Earth-Centered,
35613      * Earth-Fixed (ECEF) reference.
35614      *
35615      * @param {number} lat Latitude in degrees.
35616      * @param {number} lon Longitude in degrees.
35617      * @param {number} alt Altitude in meters.
35618      * @returns {Array<number>} The X, Y, Z ECEF coordinates.
35619      */
35620     GeoCoords.prototype.geodeticToEcef = function (lat, lon, alt) {
35621         var a = this._wgs84a;
35622         var b = this._wgs84b;
35623         lat = lat * Math.PI / 180.0;
35624         lon = lon * Math.PI / 180.0;
35625         var cosLat = Math.cos(lat);
35626         var sinLat = Math.sin(lat);
35627         var cosLon = Math.cos(lon);
35628         var sinLon = Math.sin(lon);
35629         var a2 = a * a;
35630         var b2 = b * b;
35631         var L = 1.0 / Math.sqrt(a2 * cosLat * cosLat + b2 * sinLat * sinLat);
35632         var nhcl = (a2 * L + alt) * cosLat;
35633         var X = nhcl * cosLon;
35634         var Y = nhcl * sinLon;
35635         var Z = (b2 * L + alt) * sinLat;
35636         return [X, Y, Z];
35637     };
35638     /**
35639      * Convert coordinates from Earth-Centered, Earth-Fixed (ECEF) reference
35640      * to geodetic reference (WGS84).
35641      *
35642      * @param {number} X ECEF X-value.
35643      * @param {number} Y ECEF Y-value.
35644      * @param {number} Z ECEF Z-value.
35645      * @returns {Array<number>} The latitude and longitude in degrees
35646      *                          as well as altitude in meters.
35647      */
35648     GeoCoords.prototype.ecefToGeodetic = function (X, Y, Z) {
35649         var a = this._wgs84a;
35650         var b = this._wgs84b;
35651         var a2 = a * a;
35652         var b2 = b * b;
35653         var a2mb2 = a2 - b2;
35654         var ea = Math.sqrt(a2mb2 / a2);
35655         var eb = Math.sqrt(a2mb2 / b2);
35656         var p = Math.sqrt(X * X + Y * Y);
35657         var theta = Math.atan2(Z * a, p * b);
35658         var sinTheta = Math.sin(theta);
35659         var cosTheta = Math.cos(theta);
35660         var lon = Math.atan2(Y, X);
35661         var lat = Math.atan2(Z + eb * eb * b * sinTheta * sinTheta * sinTheta, p - ea * ea * a * cosTheta * cosTheta * cosTheta);
35662         var sinLat = Math.sin(lat);
35663         var cosLat = Math.cos(lat);
35664         var N = a / Math.sqrt(1 - ea * ea * sinLat * sinLat);
35665         var alt = p / cosLat - N;
35666         return [lat * 180.0 / Math.PI, lon * 180.0 / Math.PI, alt];
35667     };
35668     return GeoCoords;
35669 }());
35670 exports.GeoCoords = GeoCoords;
35671 exports.default = GeoCoords;
35672
35673 },{}],389:[function(require,module,exports){
35674 "use strict";
35675 /// <reference path="../../typings/index.d.ts" />
35676 Object.defineProperty(exports, "__esModule", { value: true });
35677 var THREE = require("three");
35678 /**
35679  * @class Spatial
35680  *
35681  * @classdesc Provides methods for scalar, vector and matrix calculations.
35682  */
35683 var Spatial = /** @class */ (function () {
35684     function Spatial() {
35685         this._epsilon = 1e-9;
35686     }
35687     /**
35688      * Converts azimuthal phi rotation (counter-clockwise with origin on X-axis) to
35689      * bearing (clockwise with origin at north or Y-axis).
35690      *
35691      * @param {number} phi - Azimuthal phi angle in radians.
35692      * @returns {number} Bearing in radians.
35693      */
35694     Spatial.prototype.azimuthalToBearing = function (phi) {
35695         return -phi + Math.PI / 2;
35696     };
35697     /**
35698      * Converts degrees to radians.
35699      *
35700      * @param {number} deg - Degrees.
35701      * @returns {number} Radians.
35702      */
35703     Spatial.prototype.degToRad = function (deg) {
35704         return Math.PI * deg / 180;
35705     };
35706     /**
35707      * Converts radians to degrees.
35708      *
35709      * @param {number} rad - Radians.
35710      * @returns {number} Degrees.
35711      */
35712     Spatial.prototype.radToDeg = function (rad) {
35713         return 180 * rad / Math.PI;
35714     };
35715     /**
35716      * Creates a rotation matrix from an angle-axis vector.
35717      *
35718      * @param {Array<number>} angleAxis - Angle-axis representation of a rotation.
35719      * @returns {THREE.Matrix4} Rotation matrix.
35720      */
35721     Spatial.prototype.rotationMatrix = function (angleAxis) {
35722         var axis = new THREE.Vector3(angleAxis[0], angleAxis[1], angleAxis[2]);
35723         var angle = axis.length();
35724         if (angle > 0) {
35725             axis.normalize();
35726         }
35727         return new THREE.Matrix4().makeRotationAxis(axis, angle);
35728     };
35729     /**
35730      * Rotates a vector according to a angle-axis rotation vector.
35731      *
35732      * @param {Array<number>} vector - Vector to rotate.
35733      * @param {Array<number>} angleAxis - Angle-axis representation of a rotation.
35734      * @returns {THREE.Vector3} Rotated vector.
35735      */
35736     Spatial.prototype.rotate = function (vector, angleAxis) {
35737         var v = new THREE.Vector3(vector[0], vector[1], vector[2]);
35738         var rotationMatrix = this.rotationMatrix(angleAxis);
35739         v.applyMatrix4(rotationMatrix);
35740         return v;
35741     };
35742     /**
35743      * Calculates the optical center from a rotation vector
35744      * on the angle-axis representation and a translation vector
35745      * according to C = -R^T t.
35746      *
35747      * @param {Array<number>} rotation - Angle-axis representation of a rotation.
35748      * @param {Array<number>} translation - Translation vector.
35749      * @returns {THREE.Vector3} Optical center.
35750      */
35751     Spatial.prototype.opticalCenter = function (rotation, translation) {
35752         var angleAxis = [-rotation[0], -rotation[1], -rotation[2]];
35753         var vector = [-translation[0], -translation[1], -translation[2]];
35754         return this.rotate(vector, angleAxis);
35755     };
35756     /**
35757      * Calculates the viewing direction from a rotation vector
35758      * on the angle-axis representation.
35759      *
35760      * @param {number[]} rotation - Angle-axis representation of a rotation.
35761      * @returns {THREE.Vector3} Viewing direction.
35762      */
35763     Spatial.prototype.viewingDirection = function (rotation) {
35764         var angleAxis = [-rotation[0], -rotation[1], -rotation[2]];
35765         return this.rotate([0, 0, 1], angleAxis);
35766     };
35767     /**
35768      * Wrap a number on the interval [min, max].
35769      *
35770      * @param {number} value - Value to wrap.
35771      * @param {number} min - Lower endpoint of interval.
35772      * @param {number} max - Upper endpoint of interval.
35773      * @returns {number} The wrapped number.
35774      */
35775     Spatial.prototype.wrap = function (value, min, max) {
35776         if (max < min) {
35777             throw new Error("Invalid arguments: max must be larger than min.");
35778         }
35779         var interval = (max - min);
35780         while (value > max || value < min) {
35781             if (value > max) {
35782                 value = value - interval;
35783             }
35784             else if (value < min) {
35785                 value = value + interval;
35786             }
35787         }
35788         return value;
35789     };
35790     /**
35791      * Wrap an angle on the interval [-Pi, Pi].
35792      *
35793      * @param {number} angle - Value to wrap.
35794      * @returns {number} Wrapped angle.
35795      */
35796     Spatial.prototype.wrapAngle = function (angle) {
35797         return this.wrap(angle, -Math.PI, Math.PI);
35798     };
35799     /**
35800      * Limit the value to the interval [min, max] by changing the value to
35801      * the nearest available one when it is outside the interval.
35802      *
35803      * @param {number} value - Value to clamp.
35804      * @param {number} min - Minimum of the interval.
35805      * @param {number} max - Maximum of the interval.
35806      * @returns {number} Clamped value.
35807      */
35808     Spatial.prototype.clamp = function (value, min, max) {
35809         if (value < min) {
35810             return min;
35811         }
35812         if (value > max) {
35813             return max;
35814         }
35815         return value;
35816     };
35817     /**
35818      * Calculates the counter-clockwise angle from the first
35819      * vector (x1, y1)^T to the second (x2, y2)^T.
35820      *
35821      * @param {number} x1 - X coordinate of first vector.
35822      * @param {number} y1 - Y coordinate of first vector.
35823      * @param {number} x2 - X coordinate of second vector.
35824      * @param {number} y2 - Y coordinate of second vector.
35825      * @returns {number} Counter clockwise angle between the vectors.
35826      */
35827     Spatial.prototype.angleBetweenVector2 = function (x1, y1, x2, y2) {
35828         var angle = Math.atan2(y2, x2) - Math.atan2(y1, x1);
35829         return this.wrapAngle(angle);
35830     };
35831     /**
35832      * Calculates the minimum (absolute) angle change for rotation
35833      * from one angle to another on the [-Pi, Pi] interval.
35834      *
35835      * @param {number} angle1 - Start angle.
35836      * @param {number} angle2 - Destination angle.
35837      * @returns {number} Absolute angle change between angles.
35838      */
35839     Spatial.prototype.angleDifference = function (angle1, angle2) {
35840         var angle = angle2 - angle1;
35841         return this.wrapAngle(angle);
35842     };
35843     /**
35844      * Calculates the relative rotation angle between two
35845      * angle-axis vectors.
35846      *
35847      * @param {number} rotation1 - First angle-axis vector.
35848      * @param {number} rotation2 - Second angle-axis vector.
35849      * @returns {number} Relative rotation angle.
35850      */
35851     Spatial.prototype.relativeRotationAngle = function (rotation1, rotation2) {
35852         var R1T = this.rotationMatrix([-rotation1[0], -rotation1[1], -rotation1[2]]);
35853         var R2 = this.rotationMatrix(rotation2);
35854         var R = R1T.multiply(R2);
35855         var elements = R.elements;
35856         // from Tr(R) = 1 + 2*cos(theta)
35857         var theta = Math.acos((elements[0] + elements[5] + elements[10] - 1) / 2);
35858         return theta;
35859     };
35860     /**
35861      * Calculates the angle from a vector to a plane.
35862      *
35863      * @param {Array<number>} vector - The vector.
35864      * @param {Array<number>} planeNormal - Normal of the plane.
35865      * @returns {number} Angle from between plane and vector.
35866      */
35867     Spatial.prototype.angleToPlane = function (vector, planeNormal) {
35868         var v = new THREE.Vector3().fromArray(vector);
35869         var norm = v.length();
35870         if (norm < this._epsilon) {
35871             return 0;
35872         }
35873         var projection = v.dot(new THREE.Vector3().fromArray(planeNormal));
35874         return Math.asin(projection / norm);
35875     };
35876     /**
35877      * Calculates the distance between two coordinates
35878      * (latitude longitude pairs) in meters according to
35879      * the haversine formula.
35880      *
35881      * @param {number} lat1 - Latitude of the first coordinate in degrees.
35882      * @param {number} lon1 - Longitude of the first coordinate in degrees.
35883      * @param {number} lat2 - Latitude of the second coordinate in degrees.
35884      * @param {number} lon2 - Longitude of the second coordinate in degrees.
35885      * @returns {number} Distance between lat lon positions in meters.
35886      */
35887     Spatial.prototype.distanceFromLatLon = function (lat1, lon1, lat2, lon2) {
35888         var r = 6371000;
35889         var dLat = this.degToRad(lat2 - lat1);
35890         var dLon = this.degToRad(lon2 - lon1);
35891         var hav = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
35892             Math.cos(this.degToRad(lat1)) * Math.cos(this.degToRad(lat2)) *
35893                 Math.sin(dLon / 2) * Math.sin(dLon / 2);
35894         var d = 2 * r * Math.atan2(Math.sqrt(hav), Math.sqrt(1 - hav));
35895         return d;
35896     };
35897     return Spatial;
35898 }());
35899 exports.Spatial = Spatial;
35900 exports.default = Spatial;
35901
35902 },{"three":241}],390:[function(require,module,exports){
35903 "use strict";
35904 /// <reference path="../../typings/index.d.ts" />
35905 Object.defineProperty(exports, "__esModule", { value: true });
35906 var THREE = require("three");
35907 /**
35908  * @class Transform
35909  *
35910  * @classdesc Class used for calculating coordinate transformations
35911  * and projections.
35912  */
35913 var Transform = /** @class */ (function () {
35914     /**
35915      * Create a new transform instance.
35916      * @param {Node} apiNavImIm - Node properties.
35917      * @param {HTMLImageElement} image - Node image.
35918      * @param {Array<number>} translation - Node translation vector in three dimensions.
35919      */
35920     function Transform(node, image, translation) {
35921         this._orientation = this._getValue(node.orientation, 1);
35922         var imageWidth = image != null ? image.width : 4;
35923         var imageHeight = image != null ? image.height : 3;
35924         var keepOrientation = this._orientation < 5;
35925         this._width = this._getValue(node.width, keepOrientation ? imageWidth : imageHeight);
35926         this._height = this._getValue(node.height, keepOrientation ? imageHeight : imageWidth);
35927         this._basicAspect = keepOrientation ?
35928             this._width / this._height :
35929             this._height / this._width;
35930         this._basicWidth = keepOrientation ? node.width : node.height;
35931         this._basicHeight = keepOrientation ? node.height : node.width;
35932         this._focal = this._getValue(node.focal, 1);
35933         this._scale = this._getValue(node.scale, 0);
35934         this._gpano = node.gpano != null ? node.gpano : null;
35935         this._rt = this._getRt(node.rotation, translation);
35936         this._srt = this._getSrt(this._rt, this._scale);
35937     }
35938     Object.defineProperty(Transform.prototype, "basicAspect", {
35939         /**
35940          * Get basic aspect.
35941          * @returns {number} The orientation adjusted aspect ratio.
35942          */
35943         get: function () {
35944             return this._basicAspect;
35945         },
35946         enumerable: true,
35947         configurable: true
35948     });
35949     Object.defineProperty(Transform.prototype, "basicHeight", {
35950         /**
35951          * Get basic height.
35952          *
35953          * @description Does not fall back to node image height but
35954          * uses original value from API so can be faulty.
35955          *
35956          * @returns {number} The height of the basic version image
35957          * (adjusted for orientation).
35958          */
35959         get: function () {
35960             return this._basicHeight;
35961         },
35962         enumerable: true,
35963         configurable: true
35964     });
35965     Object.defineProperty(Transform.prototype, "basicWidth", {
35966         /**
35967          * Get basic width.
35968          *
35969          * @description Does not fall back to node image width but
35970          * uses original value from API so can be faulty.
35971          *
35972          * @returns {number} The width of the basic version image
35973          * (adjusted for orientation).
35974          */
35975         get: function () {
35976             return this._basicWidth;
35977         },
35978         enumerable: true,
35979         configurable: true
35980     });
35981     Object.defineProperty(Transform.prototype, "focal", {
35982         /**
35983          * Get focal.
35984          * @returns {number} The node focal length.
35985          */
35986         get: function () {
35987             return this._focal;
35988         },
35989         enumerable: true,
35990         configurable: true
35991     });
35992     Object.defineProperty(Transform.prototype, "fullPano", {
35993         /**
35994          * Get fullPano.
35995          *
35996          * @returns {boolean} Value indicating whether the node is a complete
35997          * 360 panorama.
35998          */
35999         get: function () {
36000             return this._gpano != null &&
36001                 this._gpano.CroppedAreaLeftPixels === 0 &&
36002                 this._gpano.CroppedAreaTopPixels === 0 &&
36003                 this._gpano.CroppedAreaImageWidthPixels === this._gpano.FullPanoWidthPixels &&
36004                 this._gpano.CroppedAreaImageHeightPixels === this._gpano.FullPanoHeightPixels;
36005         },
36006         enumerable: true,
36007         configurable: true
36008     });
36009     Object.defineProperty(Transform.prototype, "gpano", {
36010         /**
36011          * Get gpano.
36012          * @returns {number} The node gpano information.
36013          */
36014         get: function () {
36015             return this._gpano;
36016         },
36017         enumerable: true,
36018         configurable: true
36019     });
36020     Object.defineProperty(Transform.prototype, "height", {
36021         /**
36022          * Get height.
36023          *
36024          * @description Falls back to the node image height if
36025          * the API data is faulty.
36026          *
36027          * @returns {number} The orientation adjusted image height.
36028          */
36029         get: function () {
36030             return this._height;
36031         },
36032         enumerable: true,
36033         configurable: true
36034     });
36035     Object.defineProperty(Transform.prototype, "orientation", {
36036         /**
36037          * Get orientation.
36038          * @returns {number} The image orientation.
36039          */
36040         get: function () {
36041             return this._orientation;
36042         },
36043         enumerable: true,
36044         configurable: true
36045     });
36046     Object.defineProperty(Transform.prototype, "rt", {
36047         /**
36048          * Get rt.
36049          * @returns {THREE.Matrix4} The extrinsic camera matrix.
36050          */
36051         get: function () {
36052             return this._rt;
36053         },
36054         enumerable: true,
36055         configurable: true
36056     });
36057     Object.defineProperty(Transform.prototype, "srt", {
36058         /**
36059          * Get srt.
36060          * @returns {THREE.Matrix4} The scaled extrinsic camera matrix.
36061          */
36062         get: function () {
36063             return this._srt;
36064         },
36065         enumerable: true,
36066         configurable: true
36067     });
36068     Object.defineProperty(Transform.prototype, "scale", {
36069         /**
36070          * Get scale.
36071          * @returns {number} The node atomic reconstruction scale.
36072          */
36073         get: function () {
36074             return this._scale;
36075         },
36076         enumerable: true,
36077         configurable: true
36078     });
36079     Object.defineProperty(Transform.prototype, "hasValidScale", {
36080         /**
36081          * Get has valid scale.
36082          * @returns {boolean} Value indicating if the scale of the transform is valid.
36083          */
36084         get: function () {
36085             return this._scale > 1e-2 && this._scale < 50;
36086         },
36087         enumerable: true,
36088         configurable: true
36089     });
36090     Object.defineProperty(Transform.prototype, "width", {
36091         /**
36092          * Get width.
36093          *
36094          * @description Falls back to the node image width if
36095          * the API data is faulty.
36096          *
36097          * @returns {number} The orientation adjusted image width.
36098          */
36099         get: function () {
36100             return this._width;
36101         },
36102         enumerable: true,
36103         configurable: true
36104     });
36105     /**
36106      * Calculate the up vector for the node transform.
36107      *
36108      * @returns {THREE.Vector3} Normalized and orientation adjusted up vector.
36109      */
36110     Transform.prototype.upVector = function () {
36111         var rte = this._rt.elements;
36112         switch (this._orientation) {
36113             case 1:
36114                 return new THREE.Vector3(-rte[1], -rte[5], -rte[9]);
36115             case 3:
36116                 return new THREE.Vector3(rte[1], rte[5], rte[9]);
36117             case 6:
36118                 return new THREE.Vector3(-rte[0], -rte[4], -rte[8]);
36119             case 8:
36120                 return new THREE.Vector3(rte[0], rte[4], rte[8]);
36121             default:
36122                 return new THREE.Vector3(-rte[1], -rte[5], -rte[9]);
36123         }
36124     };
36125     /**
36126      * Calculate projector matrix for projecting 3D points to texture map
36127      * coordinates (u and v).
36128      *
36129      * @returns {THREE.Matrix4} Projection matrix for 3D point to texture
36130      * map coordinate calculations.
36131      */
36132     Transform.prototype.projectorMatrix = function () {
36133         var projector = this._normalizedToTextureMatrix();
36134         var f = this._focal;
36135         var projection = new THREE.Matrix4().set(f, 0, 0, 0, 0, f, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0);
36136         projector.multiply(projection);
36137         projector.multiply(this._rt);
36138         return projector;
36139     };
36140     /**
36141      * Project 3D world coordinates to basic coordinates.
36142      *
36143      * @param {Array<number>} point3d - 3D world coordinates.
36144      * @return {Array<number>} 2D basic coordinates.
36145      */
36146     Transform.prototype.projectBasic = function (point3d) {
36147         var sfm = this.projectSfM(point3d);
36148         return this._sfmToBasic(sfm);
36149     };
36150     /**
36151      * Unproject basic coordinates to 3D world coordinates.
36152      *
36153      * @param {Array<number>} basic - 2D basic coordinates.
36154      * @param {Array<number>} distance - Depth to unproject from camera center.
36155      * @returns {Array<number>} Unprojected 3D world coordinates.
36156      */
36157     Transform.prototype.unprojectBasic = function (basic, distance) {
36158         var sfm = this._basicToSfm(basic);
36159         return this.unprojectSfM(sfm, distance);
36160     };
36161     /**
36162      * Project 3D world coordinates to SfM coordinates.
36163      *
36164      * @param {Array<number>} point3d - 3D world coordinates.
36165      * @return {Array<number>} 2D SfM coordinates.
36166      */
36167     Transform.prototype.projectSfM = function (point3d) {
36168         var v = new THREE.Vector4(point3d[0], point3d[1], point3d[2], 1);
36169         v.applyMatrix4(this._rt);
36170         return this._bearingToSfm([v.x, v.y, v.z]);
36171     };
36172     /**
36173      * Unproject SfM coordinates to a 3D world coordinates.
36174      *
36175      * @param {Array<number>} sfm - 2D SfM coordinates.
36176      * @param {Array<number>} distance - Depth to unproject from camera center.
36177      * @returns {Array<number>} Unprojected 3D world coordinates.
36178      */
36179     Transform.prototype.unprojectSfM = function (sfm, distance) {
36180         var bearing = this._sfmToBearing(sfm);
36181         var v = new THREE.Vector4(distance * bearing[0], distance * bearing[1], distance * bearing[2], 1);
36182         v.applyMatrix4(new THREE.Matrix4().getInverse(this._rt));
36183         return [v.x / v.w, v.y / v.w, v.z / v.w];
36184     };
36185     /**
36186      * Transform SfM coordinates to bearing vector (3D cartesian
36187      * coordinates on the unit sphere).
36188      *
36189      * @param {Array<number>} sfm - 2D SfM coordinates.
36190      * @returns {Array<number>} Bearing vector (3D cartesian coordinates
36191      * on the unit sphere).
36192      */
36193     Transform.prototype._sfmToBearing = function (sfm) {
36194         if (this._fullPano()) {
36195             var lon = sfm[0] * 2 * Math.PI;
36196             var lat = -sfm[1] * 2 * Math.PI;
36197             var x = Math.cos(lat) * Math.sin(lon);
36198             var y = -Math.sin(lat);
36199             var z = Math.cos(lat) * Math.cos(lon);
36200             return [x, y, z];
36201         }
36202         else if (this._gpano) {
36203             var size = Math.max(this.gpano.CroppedAreaImageWidthPixels, this.gpano.CroppedAreaImageHeightPixels);
36204             var fullPanoPixel = [
36205                 sfm[0] * size + this.gpano.CroppedAreaImageWidthPixels / 2 + this.gpano.CroppedAreaLeftPixels,
36206                 sfm[1] * size + this.gpano.CroppedAreaImageHeightPixels / 2 + this.gpano.CroppedAreaTopPixels,
36207             ];
36208             var lon = 2 * Math.PI * (fullPanoPixel[0] / this.gpano.FullPanoWidthPixels - 0.5);
36209             var lat = -Math.PI * (fullPanoPixel[1] / this.gpano.FullPanoHeightPixels - 0.5);
36210             var x = Math.cos(lat) * Math.sin(lon);
36211             var y = -Math.sin(lat);
36212             var z = Math.cos(lat) * Math.cos(lon);
36213             return [x, y, z];
36214         }
36215         else {
36216             var v = new THREE.Vector3(sfm[0], sfm[1], this._focal);
36217             v.normalize();
36218             return [v.x, v.y, v.z];
36219         }
36220     };
36221     /**
36222      * Transform bearing vector (3D cartesian coordiantes on the unit sphere) to
36223      * SfM coordinates.
36224      *
36225      * @param {Array<number>} bearing - Bearing vector (3D cartesian coordinates on the
36226      * unit sphere).
36227      * @returns {Array<number>} 2D SfM coordinates.
36228      */
36229     Transform.prototype._bearingToSfm = function (bearing) {
36230         if (this._fullPano()) {
36231             var x = bearing[0];
36232             var y = bearing[1];
36233             var z = bearing[2];
36234             var lon = Math.atan2(x, z);
36235             var lat = Math.atan2(-y, Math.sqrt(x * x + z * z));
36236             return [lon / (2 * Math.PI), -lat / (2 * Math.PI)];
36237         }
36238         else if (this._gpano) {
36239             var x = bearing[0];
36240             var y = bearing[1];
36241             var z = bearing[2];
36242             var lon = Math.atan2(x, z);
36243             var lat = Math.atan2(-y, Math.sqrt(x * x + z * z));
36244             var fullPanoPixel = [
36245                 (lon / (2 * Math.PI) + 0.5) * this.gpano.FullPanoWidthPixels,
36246                 (-lat / Math.PI + 0.5) * this.gpano.FullPanoHeightPixels,
36247             ];
36248             var size = Math.max(this.gpano.CroppedAreaImageWidthPixels, this.gpano.CroppedAreaImageHeightPixels);
36249             return [
36250                 (fullPanoPixel[0] - this.gpano.CroppedAreaLeftPixels - this.gpano.CroppedAreaImageWidthPixels / 2) / size,
36251                 (fullPanoPixel[1] - this.gpano.CroppedAreaTopPixels - this.gpano.CroppedAreaImageHeightPixels / 2) / size,
36252             ];
36253         }
36254         else {
36255             if (bearing[2] > 0) {
36256                 return [
36257                     bearing[0] * this._focal / bearing[2],
36258                     bearing[1] * this._focal / bearing[2],
36259                 ];
36260             }
36261             else {
36262                 return [
36263                     bearing[0] < 0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
36264                     bearing[1] < 0 ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
36265                 ];
36266             }
36267         }
36268     };
36269     /**
36270      * Convert basic coordinates to SfM coordinates.
36271      *
36272      * @param {Array<number>} basic - 2D basic coordinates.
36273      * @returns {Array<number>} 2D SfM coordinates.
36274      */
36275     Transform.prototype._basicToSfm = function (basic) {
36276         var rotatedX;
36277         var rotatedY;
36278         switch (this._orientation) {
36279             case 1:
36280                 rotatedX = basic[0];
36281                 rotatedY = basic[1];
36282                 break;
36283             case 3:
36284                 rotatedX = 1 - basic[0];
36285                 rotatedY = 1 - basic[1];
36286                 break;
36287             case 6:
36288                 rotatedX = basic[1];
36289                 rotatedY = 1 - basic[0];
36290                 break;
36291             case 8:
36292                 rotatedX = 1 - basic[1];
36293                 rotatedY = basic[0];
36294                 break;
36295             default:
36296                 rotatedX = basic[0];
36297                 rotatedY = basic[1];
36298                 break;
36299         }
36300         var w = this._width;
36301         var h = this._height;
36302         var s = Math.max(w, h);
36303         var sfmX = rotatedX * w / s - w / s / 2;
36304         var sfmY = rotatedY * h / s - h / s / 2;
36305         return [sfmX, sfmY];
36306     };
36307     /**
36308      * Convert SfM coordinates to basic coordinates.
36309      *
36310      * @param {Array<number>} sfm - 2D SfM coordinates.
36311      * @returns {Array<number>} 2D basic coordinates.
36312      */
36313     Transform.prototype._sfmToBasic = function (sfm) {
36314         var w = this._width;
36315         var h = this._height;
36316         var s = Math.max(w, h);
36317         var rotatedX = (sfm[0] + w / s / 2) / w * s;
36318         var rotatedY = (sfm[1] + h / s / 2) / h * s;
36319         var basicX;
36320         var basicY;
36321         switch (this._orientation) {
36322             case 1:
36323                 basicX = rotatedX;
36324                 basicY = rotatedY;
36325                 break;
36326             case 3:
36327                 basicX = 1 - rotatedX;
36328                 basicY = 1 - rotatedY;
36329                 break;
36330             case 6:
36331                 basicX = 1 - rotatedY;
36332                 basicY = rotatedX;
36333                 break;
36334             case 8:
36335                 basicX = rotatedY;
36336                 basicY = 1 - rotatedX;
36337                 break;
36338             default:
36339                 basicX = rotatedX;
36340                 basicY = rotatedY;
36341                 break;
36342         }
36343         return [basicX, basicY];
36344     };
36345     /**
36346      * Determines if the gpano information indicates a full panorama.
36347      *
36348      * @returns {boolean} Value determining if the gpano information indicates
36349      * a full panorama.
36350      */
36351     Transform.prototype._fullPano = function () {
36352         return this.gpano != null &&
36353             this.gpano.CroppedAreaLeftPixels === 0 &&
36354             this.gpano.CroppedAreaTopPixels === 0 &&
36355             this.gpano.CroppedAreaImageWidthPixels === this.gpano.FullPanoWidthPixels &&
36356             this.gpano.CroppedAreaImageHeightPixels === this.gpano.FullPanoHeightPixels;
36357     };
36358     /**
36359      * Checks a value and returns it if it exists and is larger than 0.
36360      * Fallbacks if it is null.
36361      *
36362      * @param {number} value - Value to check.
36363      * @param {number} fallback - Value to fall back to.
36364      * @returns {number} The value or its fallback value if it is not defined or negative.
36365      */
36366     Transform.prototype._getValue = function (value, fallback) {
36367         return value != null && value > 0 ? value : fallback;
36368     };
36369     /**
36370      * Creates the extrinsic camera matrix [ R | t ].
36371      *
36372      * @param {Array<number>} rotation - Rotation vector in angle axis representation.
36373      * @param {Array<number>} translation - Translation vector.
36374      * @returns {THREE.Matrix4} Extrisic camera matrix.
36375      */
36376     Transform.prototype._getRt = function (rotation, translation) {
36377         var axis = new THREE.Vector3(rotation[0], rotation[1], rotation[2]);
36378         var angle = axis.length();
36379         if (angle > 0) {
36380             axis.normalize();
36381         }
36382         var rt = new THREE.Matrix4();
36383         rt.makeRotationAxis(axis, angle);
36384         rt.setPosition(new THREE.Vector3(translation[0], translation[1], translation[2]));
36385         return rt;
36386     };
36387     /**
36388      * Calculates the scaled extrinsic camera matrix scale * [ R | t ].
36389      *
36390      * @param {THREE.Matrix4} rt - Extrisic camera matrix.
36391      * @param {number} scale - Scale factor.
36392      * @returns {THREE.Matrix4} Scaled extrisic camera matrix.
36393      */
36394     Transform.prototype._getSrt = function (rt, scale) {
36395         var srt = rt.clone();
36396         var elements = srt.elements;
36397         elements[12] = scale * elements[12];
36398         elements[13] = scale * elements[13];
36399         elements[14] = scale * elements[14];
36400         srt.scale(new THREE.Vector3(scale, scale, scale));
36401         return srt;
36402     };
36403     /**
36404      * Calculate a transformation matrix from normalized coordinates for
36405      * texture map coordinates.
36406      *
36407      * @returns {THREE.Matrix4} Normalized coordinates to texture map
36408      * coordinates transformation matrix.
36409      */
36410     Transform.prototype._normalizedToTextureMatrix = function () {
36411         var size = Math.max(this._width, this._height);
36412         var w = size / this._width;
36413         var h = size / this._height;
36414         switch (this._orientation) {
36415             case 1:
36416                 return new THREE.Matrix4().set(w, 0, 0, 0.5, 0, -h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
36417             case 3:
36418                 return new THREE.Matrix4().set(-w, 0, 0, 0.5, 0, h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
36419             case 6:
36420                 return new THREE.Matrix4().set(0, -h, 0, 0.5, -w, 0, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
36421             case 8:
36422                 return new THREE.Matrix4().set(0, h, 0, 0.5, w, 0, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
36423             default:
36424                 return new THREE.Matrix4().set(w, 0, 0, 0.5, 0, -h, 0, 0.5, 0, 0, 1, 0, 0, 0, 0, 1);
36425         }
36426     };
36427     return Transform;
36428 }());
36429 exports.Transform = Transform;
36430
36431 },{"three":241}],391:[function(require,module,exports){
36432 "use strict";
36433 /// <reference path="../../typings/index.d.ts" />
36434 Object.defineProperty(exports, "__esModule", { value: true });
36435 var THREE = require("three");
36436 /**
36437  * @class ViewportCoords
36438  *
36439  * @classdesc Provides methods for calculating 2D coordinate conversions
36440  * as well as 3D projection and unprojection.
36441  *
36442  * Basic coordinates are 2D coordinates on the [0, 1] interval and
36443  * have the origin point, (0, 0), at the top left corner and the
36444  * maximum value, (1, 1), at the bottom right corner of the original
36445  * image.
36446  *
36447  * Viewport coordinates are 2D coordinates on the [-1, 1] interval and
36448  * have the origin point in the center. The bottom left corner point is
36449  * (-1, -1) and the top right corner point is (1, 1).
36450  *
36451  * Canvas coordiantes are 2D pixel coordinates on the [0, canvasWidth] and
36452  * [0, canvasHeight] intervals. The origin point (0, 0) is in the top left
36453  * corner and the maximum value is (canvasWidth, canvasHeight) is in the
36454  * bottom right corner.
36455  *
36456  * 3D coordinates are in the topocentric world reference frame.
36457  */
36458 var ViewportCoords = /** @class */ (function () {
36459     function ViewportCoords() {
36460         this._unprojectDepth = 200;
36461     }
36462     /**
36463      * Convert basic coordinates to canvas coordinates.
36464      *
36465      * @description Transform origin and camera position needs to be the
36466      * equal for reliable return value.
36467      *
36468      * @param {number} basicX - Basic X coordinate.
36469      * @param {number} basicY - Basic Y coordinate.
36470      * @param {HTMLElement} container - The viewer container.
36471      * @param {Transform} transform - Transform of the node to unproject from.
36472      * @param {THREE.Camera} camera - Camera used in rendering.
36473      * @returns {Array<number>} 2D canvas coordinates.
36474      */
36475     ViewportCoords.prototype.basicToCanvas = function (basicX, basicY, container, transform, camera) {
36476         var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
36477         var canvas = this.projectToCanvas(point3d, container, camera);
36478         return canvas;
36479     };
36480     /**
36481      * Convert basic coordinates to canvas coordinates safely. If 3D point is
36482      * behind camera null will be returned.
36483      *
36484      * @description Transform origin and camera position needs to be the
36485      * equal for reliable return value.
36486      *
36487      * @param {number} basicX - Basic X coordinate.
36488      * @param {number} basicY - Basic Y coordinate.
36489      * @param {HTMLElement} container - The viewer container.
36490      * @param {Transform} transform - Transform of the node to unproject from.
36491      * @param {THREE.Camera} camera - Camera used in rendering.
36492      * @returns {Array<number>} 2D canvas coordinates if the basic point represents a 3D point
36493      * in front of the camera, otherwise null.
36494      */
36495     ViewportCoords.prototype.basicToCanvasSafe = function (basicX, basicY, container, transform, camera) {
36496         var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
36497         var pointCamera = this.worldToCamera(point3d, camera);
36498         if (pointCamera[2] > 0) {
36499             return null;
36500         }
36501         var _a = this.cameraToViewport(pointCamera, camera), viewportX = _a[0], viewportY = _a[1];
36502         var canvas = this.viewportToCanvas(viewportX, viewportY, container);
36503         return canvas;
36504     };
36505     /**
36506      * Convert basic coordinates to viewport coordinates.
36507      *
36508      * @description Transform origin and camera position needs to be the
36509      * equal for reliable return value.
36510      *
36511      * @param {number} basicX - Basic X coordinate.
36512      * @param {number} basicY - Basic Y coordinate.
36513      * @param {Transform} transform - Transform of the node to unproject from.
36514      * @param {THREE.Camera} camera - Camera used in rendering.
36515      * @returns {Array<number>} 2D viewport coordinates.
36516      */
36517     ViewportCoords.prototype.basicToViewport = function (basicX, basicY, transform, camera) {
36518         var point3d = transform.unprojectBasic([basicX, basicY], this._unprojectDepth);
36519         var viewport = this.projectToViewport(point3d, camera);
36520         return viewport;
36521     };
36522     /**
36523      * Convert camera 3D coordinates to viewport coordinates.
36524      *
36525      * @param {number} pointCamera - 3D point in camera coordinate system.
36526      * @param {THREE.Camera} camera - Camera used in rendering.
36527      * @returns {Array<number>} 2D viewport coordinates.
36528      */
36529     ViewportCoords.prototype.cameraToViewport = function (pointCamera, camera) {
36530         var viewport = new THREE.Vector3().fromArray(pointCamera)
36531             .applyMatrix4(camera.projectionMatrix);
36532         return [viewport.x, viewport.y];
36533     };
36534     /**
36535      * Get canvas pixel position from event.
36536      *
36537      * @param {Event} event - Event containing clientX and clientY properties.
36538      * @param {HTMLElement} element - HTML element.
36539      * @returns {Array<number>} 2D canvas coordinates.
36540      */
36541     ViewportCoords.prototype.canvasPosition = function (event, element) {
36542         var clientRect = element.getBoundingClientRect();
36543         var canvasX = event.clientX - clientRect.left - element.clientLeft;
36544         var canvasY = event.clientY - clientRect.top - element.clientTop;
36545         return [canvasX, canvasY];
36546     };
36547     /**
36548      * Convert canvas coordinates to basic coordinates.
36549      *
36550      * @description Transform origin and camera position needs to be the
36551      * equal for reliable return value.
36552      *
36553      * @param {number} canvasX - Canvas X coordinate.
36554      * @param {number} canvasY - Canvas Y coordinate.
36555      * @param {HTMLElement} container - The viewer container.
36556      * @param {Transform} transform - Transform of the node to unproject from.
36557      * @param {THREE.Camera} camera - Camera used in rendering.
36558      * @returns {Array<number>} 2D basic coordinates.
36559      */
36560     ViewportCoords.prototype.canvasToBasic = function (canvasX, canvasY, container, transform, camera) {
36561         var point3d = this.unprojectFromCanvas(canvasX, canvasY, container, camera)
36562             .toArray();
36563         var basic = transform.projectBasic(point3d);
36564         return basic;
36565     };
36566     /**
36567      * Convert canvas coordinates to viewport coordinates.
36568      *
36569      * @param {number} canvasX - Canvas X coordinate.
36570      * @param {number} canvasY - Canvas Y coordinate.
36571      * @param {HTMLElement} container - The viewer container.
36572      * @returns {Array<number>} 2D viewport coordinates.
36573      */
36574     ViewportCoords.prototype.canvasToViewport = function (canvasX, canvasY, container) {
36575         var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
36576         var viewportX = 2 * canvasX / canvasWidth - 1;
36577         var viewportY = 1 - 2 * canvasY / canvasHeight;
36578         return [viewportX, viewportY];
36579     };
36580     /**
36581      * Determines the width and height of the container in canvas coordinates.
36582      *
36583      * @param {HTMLElement} container - The viewer container.
36584      * @returns {Array<number>} 2D canvas coordinates.
36585      */
36586     ViewportCoords.prototype.containerToCanvas = function (container) {
36587         return [container.offsetWidth, container.offsetHeight];
36588     };
36589     /**
36590      * Determine basic distances from image to canvas corners.
36591      *
36592      * @description Transform origin and camera position needs to be the
36593      * equal for reliable return value.
36594      *
36595      * Determines the smallest basic distance for every side of the canvas.
36596      *
36597      * @param {Transform} transform - Transform of the node to unproject from.
36598      * @param {THREE.Camera} camera - Camera used in rendering.
36599      * @returns {Array<number>} Array of basic distances as [top, right, bottom, left].
36600      */
36601     ViewportCoords.prototype.getBasicDistances = function (transform, camera) {
36602         var topLeftBasic = this.viewportToBasic(-1, 1, transform, camera);
36603         var topRightBasic = this.viewportToBasic(1, 1, transform, camera);
36604         var bottomRightBasic = this.viewportToBasic(1, -1, transform, camera);
36605         var bottomLeftBasic = this.viewportToBasic(-1, -1, transform, camera);
36606         var topBasicDistance = 0;
36607         var rightBasicDistance = 0;
36608         var bottomBasicDistance = 0;
36609         var leftBasicDistance = 0;
36610         if (topLeftBasic[1] < 0 && topRightBasic[1] < 0) {
36611             topBasicDistance = topLeftBasic[1] > topRightBasic[1] ?
36612                 -topLeftBasic[1] :
36613                 -topRightBasic[1];
36614         }
36615         if (topRightBasic[0] > 1 && bottomRightBasic[0] > 1) {
36616             rightBasicDistance = topRightBasic[0] < bottomRightBasic[0] ?
36617                 topRightBasic[0] - 1 :
36618                 bottomRightBasic[0] - 1;
36619         }
36620         if (bottomRightBasic[1] > 1 && bottomLeftBasic[1] > 1) {
36621             bottomBasicDistance = bottomRightBasic[1] < bottomLeftBasic[1] ?
36622                 bottomRightBasic[1] - 1 :
36623                 bottomLeftBasic[1] - 1;
36624         }
36625         if (bottomLeftBasic[0] < 0 && topLeftBasic[0] < 0) {
36626             leftBasicDistance = bottomLeftBasic[0] > topLeftBasic[0] ?
36627                 -bottomLeftBasic[0] :
36628                 -topLeftBasic[0];
36629         }
36630         return [topBasicDistance, rightBasicDistance, bottomBasicDistance, leftBasicDistance];
36631     };
36632     /**
36633      * Determine pixel distances from image to canvas corners.
36634      *
36635      * @description Transform origin and camera position needs to be the
36636      * equal for reliable return value.
36637      *
36638      * Determines the smallest pixel distance for every side of the canvas.
36639      *
36640      * @param {HTMLElement} container - The viewer container.
36641      * @param {Transform} transform - Transform of the node to unproject from.
36642      * @param {THREE.Camera} camera - Camera used in rendering.
36643      * @returns {Array<number>} Array of pixel distances as [top, right, bottom, left].
36644      */
36645     ViewportCoords.prototype.getPixelDistances = function (container, transform, camera) {
36646         var topLeftBasic = this.viewportToBasic(-1, 1, transform, camera);
36647         var topRightBasic = this.viewportToBasic(1, 1, transform, camera);
36648         var bottomRightBasic = this.viewportToBasic(1, -1, transform, camera);
36649         var bottomLeftBasic = this.viewportToBasic(-1, -1, transform, camera);
36650         var topPixelDistance = 0;
36651         var rightPixelDistance = 0;
36652         var bottomPixelDistance = 0;
36653         var leftPixelDistance = 0;
36654         var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
36655         if (topLeftBasic[1] < 0 && topRightBasic[1] < 0) {
36656             var basicX = topLeftBasic[1] > topRightBasic[1] ?
36657                 topLeftBasic[0] :
36658                 topRightBasic[0];
36659             var canvas = this.basicToCanvas(basicX, 0, container, transform, camera);
36660             topPixelDistance = canvas[1] > 0 ? canvas[1] : 0;
36661         }
36662         if (topRightBasic[0] > 1 && bottomRightBasic[0] > 1) {
36663             var basicY = topRightBasic[0] < bottomRightBasic[0] ?
36664                 topRightBasic[1] :
36665                 bottomRightBasic[1];
36666             var canvas = this.basicToCanvas(1, basicY, container, transform, camera);
36667             rightPixelDistance = canvas[0] < canvasWidth ? canvasWidth - canvas[0] : 0;
36668         }
36669         if (bottomRightBasic[1] > 1 && bottomLeftBasic[1] > 1) {
36670             var basicX = bottomRightBasic[1] < bottomLeftBasic[1] ?
36671                 bottomRightBasic[0] :
36672                 bottomLeftBasic[0];
36673             var canvas = this.basicToCanvas(basicX, 1, container, transform, camera);
36674             bottomPixelDistance = canvas[1] < canvasHeight ? canvasHeight - canvas[1] : 0;
36675         }
36676         if (bottomLeftBasic[0] < 0 && topLeftBasic[0] < 0) {
36677             var basicY = bottomLeftBasic[0] > topLeftBasic[0] ?
36678                 bottomLeftBasic[1] :
36679                 topLeftBasic[1];
36680             var canvas = this.basicToCanvas(0, basicY, container, transform, camera);
36681             leftPixelDistance = canvas[0] > 0 ? canvas[0] : 0;
36682         }
36683         return [topPixelDistance, rightPixelDistance, bottomPixelDistance, leftPixelDistance];
36684     };
36685     /**
36686      * Determine if an event occured inside an element.
36687      *
36688      * @param {Event} event - Event containing clientX and clientY properties.
36689      * @param {HTMLElement} element - HTML element.
36690      * @returns {boolean} Value indicating if the event occured inside the element or not.
36691      */
36692     ViewportCoords.prototype.insideElement = function (event, element) {
36693         var clientRect = element.getBoundingClientRect();
36694         var minX = clientRect.left + element.clientLeft;
36695         var maxX = minX + element.clientWidth;
36696         var minY = clientRect.top + element.clientTop;
36697         var maxY = minY + element.clientHeight;
36698         return event.clientX > minX &&
36699             event.clientX < maxX &&
36700             event.clientY > minY &&
36701             event.clientY < maxY;
36702     };
36703     /**
36704      * Project 3D world coordinates to canvas coordinates.
36705      *
36706      * @param {Array<number>} point3D - 3D world coordinates.
36707      * @param {HTMLElement} container - The viewer container.
36708      * @param {THREE.Camera} camera - Camera used in rendering.
36709      * @returns {Array<number>} 2D canvas coordinates.
36710      */
36711     ViewportCoords.prototype.projectToCanvas = function (point3d, container, camera) {
36712         var viewport = this.projectToViewport(point3d, camera);
36713         var canvas = this.viewportToCanvas(viewport[0], viewport[1], container);
36714         return canvas;
36715     };
36716     /**
36717      * Project 3D world coordinates to viewport coordinates.
36718      *
36719      * @param {Array<number>} point3D - 3D world coordinates.
36720      * @param {THREE.Camera} camera - Camera used in rendering.
36721      * @returns {Array<number>} 2D viewport coordinates.
36722      */
36723     ViewportCoords.prototype.projectToViewport = function (point3d, camera) {
36724         var viewport = new THREE.Vector3(point3d[0], point3d[1], point3d[2])
36725             .project(camera);
36726         return [viewport.x, viewport.y];
36727     };
36728     /**
36729      * Uproject canvas coordinates to 3D world coordinates.
36730      *
36731      * @param {number} canvasX - Canvas X coordinate.
36732      * @param {number} canvasY - Canvas Y coordinate.
36733      * @param {HTMLElement} container - The viewer container.
36734      * @param {THREE.Camera} camera - Camera used in rendering.
36735      * @returns {Array<number>} 3D world coordinates.
36736      */
36737     ViewportCoords.prototype.unprojectFromCanvas = function (canvasX, canvasY, container, camera) {
36738         var viewport = this.canvasToViewport(canvasX, canvasY, container);
36739         var point3d = this.unprojectFromViewport(viewport[0], viewport[1], camera);
36740         return point3d;
36741     };
36742     /**
36743      * Unproject viewport coordinates to 3D world coordinates.
36744      *
36745      * @param {number} viewportX - Viewport X coordinate.
36746      * @param {number} viewportY - Viewport Y coordinate.
36747      * @param {THREE.Camera} camera - Camera used in rendering.
36748      * @returns {Array<number>} 3D world coordinates.
36749      */
36750     ViewportCoords.prototype.unprojectFromViewport = function (viewportX, viewportY, camera) {
36751         var point3d = new THREE.Vector3(viewportX, viewportY, 1)
36752             .unproject(camera);
36753         return point3d;
36754     };
36755     /**
36756      * Convert viewport coordinates to basic coordinates.
36757      *
36758      * @description Transform origin and camera position needs to be the
36759      * equal for reliable return value.
36760      *
36761      * @param {number} viewportX - Viewport X coordinate.
36762      * @param {number} viewportY - Viewport Y coordinate.
36763      * @param {Transform} transform - Transform of the node to unproject from.
36764      * @param {THREE.Camera} camera - Camera used in rendering.
36765      * @returns {Array<number>} 2D basic coordinates.
36766      */
36767     ViewportCoords.prototype.viewportToBasic = function (viewportX, viewportY, transform, camera) {
36768         var point3d = new THREE.Vector3(viewportX, viewportY, 1)
36769             .unproject(camera)
36770             .toArray();
36771         var basic = transform.projectBasic(point3d);
36772         return basic;
36773     };
36774     /**
36775      * Convert viewport coordinates to canvas coordinates.
36776      *
36777      * @param {number} viewportX - Viewport X coordinate.
36778      * @param {number} viewportY - Viewport Y coordinate.
36779      * @param {HTMLElement} container - The viewer container.
36780      * @returns {Array<number>} 2D canvas coordinates.
36781      */
36782     ViewportCoords.prototype.viewportToCanvas = function (viewportX, viewportY, container) {
36783         var _a = this.containerToCanvas(container), canvasWidth = _a[0], canvasHeight = _a[1];
36784         var canvasX = canvasWidth * (viewportX + 1) / 2;
36785         var canvasY = -canvasHeight * (viewportY - 1) / 2;
36786         return [canvasX, canvasY];
36787     };
36788     /**
36789      * Convert 3D world coordinates to 3D camera coordinates.
36790      *
36791      * @param {number} point3D - 3D point in world coordinate system.
36792      * @param {THREE.Camera} camera - Camera used in rendering.
36793      * @returns {Array<number>} 3D camera coordinates.
36794      */
36795     ViewportCoords.prototype.worldToCamera = function (point3d, camera) {
36796         var pointCamera = new THREE.Vector3(point3d[0], point3d[1], point3d[2])
36797             .applyMatrix4(camera.matrixWorldInverse);
36798         return pointCamera.toArray();
36799     };
36800     return ViewportCoords;
36801 }());
36802 exports.ViewportCoords = ViewportCoords;
36803 exports.default = ViewportCoords;
36804
36805 },{"three":241}],392:[function(require,module,exports){
36806 "use strict";
36807 Object.defineProperty(exports, "__esModule", { value: true });
36808 /**
36809  * @class Filter
36810  *
36811  * @classdesc Represents a class for creating node filters. Implementation and
36812  * definitions based on https://github.com/mapbox/feature-filter.
36813  */
36814 var FilterCreator = /** @class */ (function () {
36815     function FilterCreator() {
36816     }
36817     /**
36818      * Create a filter from a filter expression.
36819      *
36820      * @description The following filters are supported:
36821      *
36822      * Comparison
36823      * `==`
36824      * `!=`
36825      * `<`
36826      * `<=`
36827      * `>`
36828      * `>=`
36829      *
36830      * Set membership
36831      * `in`
36832      * `!in`
36833      *
36834      * Combining
36835      * `all`
36836      *
36837      * @param {FilterExpression} filter - Comparison, set membership or combinding filter
36838      * expression.
36839      * @returns {FilterFunction} Function taking a node and returning a boolean that
36840      * indicates whether the node passed the test or not.
36841      */
36842     FilterCreator.prototype.createFilter = function (filter) {
36843         return new Function("node", "return " + this._compile(filter) + ";");
36844     };
36845     FilterCreator.prototype._compile = function (filter) {
36846         if (filter == null || filter.length <= 1) {
36847             return "true";
36848         }
36849         var operator = filter[0];
36850         var operation = operator === "==" ? this._compileComparisonOp("===", filter[1], filter[2], false) :
36851             operator === "!=" ? this._compileComparisonOp("!==", filter[1], filter[2], false) :
36852                 operator === ">" ||
36853                     operator === ">=" ||
36854                     operator === "<" ||
36855                     operator === "<=" ? this._compileComparisonOp(operator, filter[1], filter[2], true) :
36856                     operator === "in" ?
36857                         this._compileInOp(filter[1], filter.slice(2)) :
36858                         operator === "!in" ?
36859                             this._compileNegation(this._compileInOp(filter[1], filter.slice(2))) :
36860                             operator === "all" ? this._compileLogicalOp(filter.slice(1), "&&") :
36861                                 "true";
36862         return "(" + operation + ")";
36863     };
36864     FilterCreator.prototype._compare = function (a, b) {
36865         return a < b ? -1 : a > b ? 1 : 0;
36866     };
36867     FilterCreator.prototype._compileComparisonOp = function (operator, property, value, checkType) {
36868         var left = this._compilePropertyReference(property);
36869         var right = JSON.stringify(value);
36870         return (checkType ? "typeof " + left + "===typeof " + right + "&&" : "") + left + operator + right;
36871     };
36872     FilterCreator.prototype._compileInOp = function (property, values) {
36873         var compare = this._compare;
36874         var left = JSON.stringify(values.sort(compare));
36875         var right = this._compilePropertyReference(property);
36876         return left + ".indexOf(" + right + ")!==-1";
36877     };
36878     FilterCreator.prototype._compileLogicalOp = function (filters, operator) {
36879         var compile = this._compile.bind(this);
36880         return filters.map(compile).join(operator);
36881     };
36882     FilterCreator.prototype._compileNegation = function (expression) {
36883         return "!(" + expression + ")";
36884     };
36885     FilterCreator.prototype._compilePropertyReference = function (property) {
36886         return "node[" + JSON.stringify(property) + "]";
36887     };
36888     return FilterCreator;
36889 }());
36890 exports.FilterCreator = FilterCreator;
36891 exports.default = FilterCreator;
36892
36893 },{}],393:[function(require,module,exports){
36894 "use strict";
36895 /// <reference path="../../typings/index.d.ts" />
36896 Object.defineProperty(exports, "__esModule", { value: true });
36897 var rbush = require("rbush");
36898 var Observable_1 = require("rxjs/Observable");
36899 var Subject_1 = require("rxjs/Subject");
36900 require("rxjs/add/observable/from");
36901 require("rxjs/add/operator/catch");
36902 require("rxjs/add/operator/do");
36903 require("rxjs/add/operator/finally");
36904 require("rxjs/add/operator/last");
36905 require("rxjs/add/operator/map");
36906 require("rxjs/add/operator/publish");
36907 require("rxjs/add/operator/reduce");
36908 var Edge_1 = require("../Edge");
36909 var Error_1 = require("../Error");
36910 var Graph_1 = require("../Graph");
36911 /**
36912  * @class Graph
36913  *
36914  * @classdesc Represents a graph of nodes with edges.
36915  */
36916 var Graph = /** @class */ (function () {
36917     /**
36918      * Create a new graph instance.
36919      *
36920      * @param {APIv3} [apiV3] - API instance for retrieving data.
36921      * @param {rbush.RBush<NodeIndexItem>} [nodeIndex] - Node index for fast spatial retreival.
36922      * @param {GraphCalculator} [graphCalculator] - Instance for graph calculations.
36923      * @param {EdgeCalculator} [edgeCalculator] - Instance for edge calculations.
36924      * @param {FilterCreator} [filterCreator] - Instance for  filter creation.
36925      * @param {IGraphConfiguration} [configuration] - Configuration struct.
36926      */
36927     function Graph(apiV3, nodeIndex, graphCalculator, edgeCalculator, filterCreator, configuration) {
36928         this._apiV3 = apiV3;
36929         this._cachedNodes = {};
36930         this._cachedNodeTiles = {};
36931         this._cachedSequenceNodes = {};
36932         this._cachedSpatialEdges = {};
36933         this._cachedTiles = {};
36934         this._cachingFill$ = {};
36935         this._cachingFull$ = {};
36936         this._cachingSequenceNodes$ = {};
36937         this._cachingSequences$ = {};
36938         this._cachingSpatialArea$ = {};
36939         this._cachingTiles$ = {};
36940         this._changed$ = new Subject_1.Subject();
36941         this._defaultAlt = 2;
36942         this._edgeCalculator = edgeCalculator != null ? edgeCalculator : new Edge_1.EdgeCalculator();
36943         this._filterCreator = filterCreator != null ? filterCreator : new Graph_1.FilterCreator();
36944         this._filter = this._filterCreator.createFilter(undefined);
36945         this._graphCalculator = graphCalculator != null ? graphCalculator : new Graph_1.GraphCalculator();
36946         this._configuration = configuration != null ?
36947             configuration :
36948             {
36949                 maxSequences: 50,
36950                 maxUnusedNodes: 100,
36951                 maxUnusedPreStoredNodes: 30,
36952                 maxUnusedTiles: 20,
36953             };
36954         this._nodes = {};
36955         this._nodeIndex = nodeIndex != null ? nodeIndex : rbush(16, [".lat", ".lon", ".lat", ".lon"]);
36956         this._nodeIndexTiles = {};
36957         this._nodeToTile = {};
36958         this._preStored = {};
36959         this._requiredNodeTiles = {};
36960         this._requiredSpatialArea = {};
36961         this._sequences = {};
36962         this._tilePrecision = 7;
36963         this._tileThreshold = 20;
36964     }
36965     Object.defineProperty(Graph.prototype, "changed$", {
36966         /**
36967          * Get changed$.
36968          *
36969          * @returns {Observable<Graph>} Observable emitting
36970          * the graph every time it has changed.
36971          */
36972         get: function () {
36973             return this._changed$;
36974         },
36975         enumerable: true,
36976         configurable: true
36977     });
36978     /**
36979      * Caches the full node data for all images within a bounding
36980      * box.
36981      *
36982      * @description The node assets are not cached.
36983      *
36984      * @param {ILatLon} sw - South west corner of bounding box.
36985      * @param {ILatLon} ne - North east corner of bounding box.
36986      * @returns {Observable<Graph>} Observable emitting the full
36987      * nodes in the bounding box.
36988      */
36989     Graph.prototype.cacheBoundingBox$ = function (sw, ne) {
36990         var _this = this;
36991         var cacheTiles$ = this._graphCalculator.encodeHsFromBoundingBox(sw, ne)
36992             .filter(function (h) {
36993             return !(h in _this._cachedTiles);
36994         })
36995             .map(function (h) {
36996             return h in _this._cachingTiles$ ?
36997                 _this._cachingTiles$[h] :
36998                 _this._cacheTile$(h);
36999         });
37000         if (cacheTiles$.length === 0) {
37001             cacheTiles$.push(Observable_1.Observable.of(this));
37002         }
37003         return Observable_1.Observable
37004             .from(cacheTiles$)
37005             .mergeAll()
37006             .last()
37007             .mergeMap(function (graph) {
37008             var nodes = _this._nodeIndex
37009                 .search({
37010                 maxX: ne.lat,
37011                 maxY: ne.lon,
37012                 minX: sw.lat,
37013                 minY: sw.lon,
37014             })
37015                 .map(function (item) {
37016                 return item.node;
37017             });
37018             var fullNodes = [];
37019             var coreNodes = [];
37020             for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
37021                 var node = nodes_1[_i];
37022                 if (node.full) {
37023                     fullNodes.push(node);
37024                 }
37025                 else {
37026                     coreNodes.push(node.key);
37027                 }
37028             }
37029             var coreNodeBatches = [];
37030             var batchSize = 200;
37031             while (coreNodes.length > 0) {
37032                 coreNodeBatches.push(coreNodes.splice(0, batchSize));
37033             }
37034             var fullNodes$ = Observable_1.Observable.of(fullNodes);
37035             var fillNodes$ = coreNodeBatches
37036                 .map(function (batch) {
37037                 return _this._apiV3.imageByKeyFill$(batch)
37038                     .map(function (imageByKeyFill) {
37039                     var filledNodes = [];
37040                     for (var fillKey in imageByKeyFill) {
37041                         if (!imageByKeyFill.hasOwnProperty(fillKey)) {
37042                             continue;
37043                         }
37044                         if (_this.hasNode(fillKey)) {
37045                             var node = _this.getNode(fillKey);
37046                             if (!node.full) {
37047                                 _this._makeFull(node, imageByKeyFill[fillKey]);
37048                             }
37049                             filledNodes.push(node);
37050                         }
37051                     }
37052                     return filledNodes;
37053                 });
37054             });
37055             return Observable_1.Observable
37056                 .merge(fullNodes$, Observable_1.Observable
37057                 .from(fillNodes$)
37058                 .mergeAll());
37059         })
37060             .reduce(function (acc, value) {
37061             return acc.concat(value);
37062         });
37063     };
37064     /**
37065      * Retrieve and cache node fill properties.
37066      *
37067      * @param {string} key - Key of node to fill.
37068      * @returns {Observable<Graph>} Observable emitting the graph
37069      * when the node has been updated.
37070      * @throws {GraphMapillaryError} When the operation is not valid on the
37071      * current graph.
37072      */
37073     Graph.prototype.cacheFill$ = function (key) {
37074         var _this = this;
37075         if (key in this._cachingFull$) {
37076             throw new Error_1.GraphMapillaryError("Cannot fill node while caching full (" + key + ").");
37077         }
37078         if (!this.hasNode(key)) {
37079             throw new Error_1.GraphMapillaryError("Cannot fill node that does not exist in graph (" + key + ").");
37080         }
37081         if (key in this._cachingFill$) {
37082             return this._cachingFill$[key];
37083         }
37084         var node = this.getNode(key);
37085         if (node.full) {
37086             throw new Error_1.GraphMapillaryError("Cannot fill node that is already full (" + key + ").");
37087         }
37088         this._cachingFill$[key] = this._apiV3.imageByKeyFill$([key])
37089             .do(function (imageByKeyFill) {
37090             if (!node.full) {
37091                 _this._makeFull(node, imageByKeyFill[key]);
37092             }
37093             delete _this._cachingFill$[key];
37094         })
37095             .map(function (imageByKeyFill) {
37096             return _this;
37097         })
37098             .finally(function () {
37099             if (key in _this._cachingFill$) {
37100                 delete _this._cachingFill$[key];
37101             }
37102             _this._changed$.next(_this);
37103         })
37104             .publish()
37105             .refCount();
37106         return this._cachingFill$[key];
37107     };
37108     /**
37109      * Retrieve and cache full node properties.
37110      *
37111      * @param {string} key - Key of node to fill.
37112      * @returns {Observable<Graph>} Observable emitting the graph
37113      * when the node has been updated.
37114      * @throws {GraphMapillaryError} When the operation is not valid on the
37115      * current graph.
37116      */
37117     Graph.prototype.cacheFull$ = function (key) {
37118         var _this = this;
37119         if (key in this._cachingFull$) {
37120             return this._cachingFull$[key];
37121         }
37122         if (this.hasNode(key)) {
37123             throw new Error_1.GraphMapillaryError("Cannot cache full node that already exist in graph (" + key + ").");
37124         }
37125         this._cachingFull$[key] = this._apiV3.imageByKeyFull$([key])
37126             .do(function (imageByKeyFull) {
37127             var fn = imageByKeyFull[key];
37128             if (_this.hasNode(key)) {
37129                 var node = _this.getNode(key);
37130                 if (!node.full) {
37131                     _this._makeFull(node, fn);
37132                 }
37133             }
37134             else {
37135                 if (fn.sequence_key == null) {
37136                     throw new Error_1.GraphMapillaryError("Node has no sequence key (" + key + ").");
37137                 }
37138                 var node = new Graph_1.Node(fn);
37139                 _this._makeFull(node, fn);
37140                 var h = _this._graphCalculator.encodeH(node.originalLatLon, _this._tilePrecision);
37141                 _this._preStore(h, node);
37142                 _this._setNode(node);
37143                 delete _this._cachingFull$[key];
37144             }
37145         })
37146             .map(function (imageByKeyFull) {
37147             return _this;
37148         })
37149             .finally(function () {
37150             if (key in _this._cachingFull$) {
37151                 delete _this._cachingFull$[key];
37152             }
37153             _this._changed$.next(_this);
37154         })
37155             .publish()
37156             .refCount();
37157         return this._cachingFull$[key];
37158     };
37159     /**
37160      * Retrieve and cache a node sequence.
37161      *
37162      * @param {string} key - Key of node for which to retrieve sequence.
37163      * @returns {Observable<Graph>} Observable emitting the graph
37164      * when the sequence has been retrieved.
37165      * @throws {GraphMapillaryError} When the operation is not valid on the
37166      * current graph.
37167      */
37168     Graph.prototype.cacheNodeSequence$ = function (key) {
37169         if (!this.hasNode(key)) {
37170             throw new Error_1.GraphMapillaryError("Cannot cache sequence edges of node that does not exist in graph (" + key + ").");
37171         }
37172         var node = this.getNode(key);
37173         if (node.sequenceKey in this._sequences) {
37174             throw new Error_1.GraphMapillaryError("Sequence already cached (" + key + "), (" + node.sequenceKey + ").");
37175         }
37176         return this._cacheSequence$(node.sequenceKey);
37177     };
37178     /**
37179      * Retrieve and cache a sequence.
37180      *
37181      * @param {string} sequenceKey - Key of sequence to cache.
37182      * @returns {Observable<Graph>} Observable emitting the graph
37183      * when the sequence has been retrieved.
37184      * @throws {GraphMapillaryError} When the operation is not valid on the
37185      * current graph.
37186      */
37187     Graph.prototype.cacheSequence$ = function (sequenceKey) {
37188         if (sequenceKey in this._sequences) {
37189             throw new Error_1.GraphMapillaryError("Sequence already cached (" + sequenceKey + ")");
37190         }
37191         return this._cacheSequence$(sequenceKey);
37192     };
37193     /**
37194      * Cache sequence edges for a node.
37195      *
37196      * @param {string} key - Key of node.
37197      * @throws {GraphMapillaryError} When the operation is not valid on the
37198      * current graph.
37199      */
37200     Graph.prototype.cacheSequenceEdges = function (key) {
37201         var node = this.getNode(key);
37202         if (!(node.sequenceKey in this._sequences)) {
37203             throw new Error_1.GraphMapillaryError("Sequence is not cached (" + key + "), (" + node.sequenceKey + ")");
37204         }
37205         var sequence = this._sequences[node.sequenceKey].sequence;
37206         var edges = this._edgeCalculator.computeSequenceEdges(node, sequence);
37207         node.cacheSequenceEdges(edges);
37208     };
37209     /**
37210      * Retrieve and cache full nodes for all keys in a sequence.
37211      *
37212      * @param {string} sequenceKey - Key of sequence.
37213      * @param {string} referenceNodeKey - Key of node to use as reference
37214      * for optimized caching.
37215      * @returns {Observable<Graph>} Observable emitting the graph
37216      * when the nodes of the sequence has been cached.
37217      */
37218     Graph.prototype.cacheSequenceNodes$ = function (sequenceKey, referenceNodeKey) {
37219         var _this = this;
37220         if (!this.hasSequence(sequenceKey)) {
37221             throw new Error_1.GraphMapillaryError("Cannot cache sequence nodes of sequence that does not exist in graph (" + sequenceKey + ").");
37222         }
37223         if (this.hasSequenceNodes(sequenceKey)) {
37224             throw new Error_1.GraphMapillaryError("Sequence nodes already cached (" + sequenceKey + ").");
37225         }
37226         var sequence = this.getSequence(sequenceKey);
37227         if (sequence.key in this._cachingSequenceNodes$) {
37228             return this._cachingSequenceNodes$[sequence.key];
37229         }
37230         var batches = [];
37231         var keys = sequence.keys.slice();
37232         var referenceBatchSize = 50;
37233         if (!!referenceNodeKey && keys.length > referenceBatchSize) {
37234             var referenceIndex = keys.indexOf(referenceNodeKey);
37235             var startIndex = Math.max(0, Math.min(referenceIndex - referenceBatchSize / 2, keys.length - referenceBatchSize));
37236             batches.push(keys.splice(startIndex, referenceBatchSize));
37237         }
37238         var batchSize = 200;
37239         while (keys.length > 0) {
37240             batches.push(keys.splice(0, batchSize));
37241         }
37242         var batchesToCache = batches.length;
37243         var sequenceNodes$ = Observable_1.Observable
37244             .from(batches)
37245             .mergeMap(function (batch) {
37246             return _this._apiV3.imageByKeyFull$(batch)
37247                 .do(function (imageByKeyFull) {
37248                 for (var fullKey in imageByKeyFull) {
37249                     if (!imageByKeyFull.hasOwnProperty(fullKey)) {
37250                         continue;
37251                     }
37252                     var fn = imageByKeyFull[fullKey];
37253                     if (_this.hasNode(fullKey)) {
37254                         var node = _this.getNode(fn.key);
37255                         if (!node.full) {
37256                             _this._makeFull(node, fn);
37257                         }
37258                     }
37259                     else {
37260                         if (fn.sequence_key == null) {
37261                             console.warn("Sequence missing, discarding node (" + fn.key + ")");
37262                         }
37263                         var node = new Graph_1.Node(fn);
37264                         _this._makeFull(node, fn);
37265                         var h = _this._graphCalculator.encodeH(node.originalLatLon, _this._tilePrecision);
37266                         _this._preStore(h, node);
37267                         _this._setNode(node);
37268                     }
37269                 }
37270                 batchesToCache--;
37271             })
37272                 .map(function (imageByKeyFull) {
37273                 return _this;
37274             });
37275         }, 6)
37276             .last()
37277             .finally(function () {
37278             delete _this._cachingSequenceNodes$[sequence.key];
37279             if (batchesToCache === 0) {
37280                 _this._cachedSequenceNodes[sequence.key] = true;
37281             }
37282         })
37283             .publish()
37284             .refCount();
37285         this._cachingSequenceNodes$[sequence.key] = sequenceNodes$;
37286         return sequenceNodes$;
37287     };
37288     /**
37289      * Retrieve and cache full nodes for a node spatial area.
37290      *
37291      * @param {string} key - Key of node for which to retrieve sequence.
37292      * @returns {Observable<Graph>} Observable emitting the graph
37293      * when the nodes in the spatial area has been made full.
37294      * @throws {GraphMapillaryError} When the operation is not valid on the
37295      * current graph.
37296      */
37297     Graph.prototype.cacheSpatialArea$ = function (key) {
37298         var _this = this;
37299         if (!this.hasNode(key)) {
37300             throw new Error_1.GraphMapillaryError("Cannot cache spatial area of node that does not exist in graph (" + key + ").");
37301         }
37302         if (key in this._cachedSpatialEdges) {
37303             throw new Error_1.GraphMapillaryError("Node already spatially cached (" + key + ").");
37304         }
37305         if (!(key in this._requiredSpatialArea)) {
37306             throw new Error_1.GraphMapillaryError("Spatial area not determined (" + key + ").");
37307         }
37308         var spatialArea = this._requiredSpatialArea[key];
37309         if (Object.keys(spatialArea.cacheNodes).length === 0) {
37310             throw new Error_1.GraphMapillaryError("Spatial nodes already cached (" + key + ").");
37311         }
37312         if (key in this._cachingSpatialArea$) {
37313             return this._cachingSpatialArea$[key];
37314         }
37315         var batches = [];
37316         while (spatialArea.cacheKeys.length > 0) {
37317             batches.push(spatialArea.cacheKeys.splice(0, 200));
37318         }
37319         var batchesToCache = batches.length;
37320         var spatialNodes$ = [];
37321         var _loop_1 = function (batch) {
37322             var spatialNodeBatch$ = this_1._apiV3.imageByKeyFill$(batch)
37323                 .do(function (imageByKeyFill) {
37324                 for (var fillKey in imageByKeyFill) {
37325                     if (!imageByKeyFill.hasOwnProperty(fillKey)) {
37326                         continue;
37327                     }
37328                     var spatialNode = spatialArea.cacheNodes[fillKey];
37329                     if (spatialNode.full) {
37330                         delete spatialArea.cacheNodes[fillKey];
37331                         continue;
37332                     }
37333                     var fillNode = imageByKeyFill[fillKey];
37334                     _this._makeFull(spatialNode, fillNode);
37335                     delete spatialArea.cacheNodes[fillKey];
37336                 }
37337                 if (--batchesToCache === 0) {
37338                     delete _this._cachingSpatialArea$[key];
37339                 }
37340             })
37341                 .map(function (imageByKeyFill) {
37342                 return _this;
37343             })
37344                 .catch(function (error) {
37345                 for (var _i = 0, batch_1 = batch; _i < batch_1.length; _i++) {
37346                     var batchKey = batch_1[_i];
37347                     if (batchKey in spatialArea.all) {
37348                         delete spatialArea.all[batchKey];
37349                     }
37350                     if (batchKey in spatialArea.cacheNodes) {
37351                         delete spatialArea.cacheNodes[batchKey];
37352                     }
37353                 }
37354                 if (--batchesToCache === 0) {
37355                     delete _this._cachingSpatialArea$[key];
37356                 }
37357                 throw error;
37358             })
37359                 .finally(function () {
37360                 if (Object.keys(spatialArea.cacheNodes).length === 0) {
37361                     _this._changed$.next(_this);
37362                 }
37363             })
37364                 .publish()
37365                 .refCount();
37366             spatialNodes$.push(spatialNodeBatch$);
37367         };
37368         var this_1 = this;
37369         for (var _i = 0, batches_1 = batches; _i < batches_1.length; _i++) {
37370             var batch = batches_1[_i];
37371             _loop_1(batch);
37372         }
37373         this._cachingSpatialArea$[key] = spatialNodes$;
37374         return spatialNodes$;
37375     };
37376     /**
37377      * Cache spatial edges for a node.
37378      *
37379      * @param {string} key - Key of node.
37380      * @throws {GraphMapillaryError} When the operation is not valid on the
37381      * current graph.
37382      */
37383     Graph.prototype.cacheSpatialEdges = function (key) {
37384         if (key in this._cachedSpatialEdges) {
37385             throw new Error_1.GraphMapillaryError("Spatial edges already cached (" + key + ").");
37386         }
37387         var node = this.getNode(key);
37388         var sequence = this._sequences[node.sequenceKey].sequence;
37389         var fallbackKeys = [];
37390         var prevKey = sequence.findPrevKey(node.key);
37391         if (prevKey != null) {
37392             fallbackKeys.push(prevKey);
37393         }
37394         var nextKey = sequence.findNextKey(node.key);
37395         if (nextKey != null) {
37396             fallbackKeys.push(nextKey);
37397         }
37398         var allSpatialNodes = this._requiredSpatialArea[key].all;
37399         var potentialNodes = [];
37400         var filter = this._filter;
37401         for (var spatialNodeKey in allSpatialNodes) {
37402             if (!allSpatialNodes.hasOwnProperty(spatialNodeKey)) {
37403                 continue;
37404             }
37405             var spatialNode = allSpatialNodes[spatialNodeKey];
37406             if (filter(spatialNode)) {
37407                 potentialNodes.push(spatialNode);
37408             }
37409         }
37410         var potentialEdges = this._edgeCalculator.getPotentialEdges(node, potentialNodes, fallbackKeys);
37411         var edges = this._edgeCalculator.computeStepEdges(node, potentialEdges, prevKey, nextKey);
37412         edges = edges.concat(this._edgeCalculator.computeTurnEdges(node, potentialEdges));
37413         edges = edges.concat(this._edgeCalculator.computePanoEdges(node, potentialEdges));
37414         edges = edges.concat(this._edgeCalculator.computePerspectiveToPanoEdges(node, potentialEdges));
37415         edges = edges.concat(this._edgeCalculator.computeSimilarEdges(node, potentialEdges));
37416         node.cacheSpatialEdges(edges);
37417         this._cachedSpatialEdges[key] = node;
37418         delete this._requiredSpatialArea[key];
37419         delete this._cachedNodeTiles[key];
37420     };
37421     /**
37422      * Retrieve and cache geohash tiles for a node.
37423      *
37424      * @param {string} key - Key of node for which to retrieve tiles.
37425      * @returns {Array<Observable<Graph>>} Array of observables emitting
37426      * the graph for each tile required for the node has been cached.
37427      * @throws {GraphMapillaryError} When the operation is not valid on the
37428      * current graph.
37429      */
37430     Graph.prototype.cacheTiles$ = function (key) {
37431         var _this = this;
37432         if (key in this._cachedNodeTiles) {
37433             throw new Error_1.GraphMapillaryError("Tiles already cached (" + key + ").");
37434         }
37435         if (key in this._cachedSpatialEdges) {
37436             throw new Error_1.GraphMapillaryError("Spatial edges already cached so tiles considered cached (" + key + ").");
37437         }
37438         if (!(key in this._requiredNodeTiles)) {
37439             throw new Error_1.GraphMapillaryError("Tiles have not been determined (" + key + ").");
37440         }
37441         var nodeTiles = this._requiredNodeTiles[key];
37442         if (nodeTiles.cache.length === 0 &&
37443             nodeTiles.caching.length === 0) {
37444             throw new Error_1.GraphMapillaryError("Tiles already cached (" + key + ").");
37445         }
37446         if (!this.hasNode(key)) {
37447             throw new Error_1.GraphMapillaryError("Cannot cache tiles of node that does not exist in graph (" + key + ").");
37448         }
37449         var hs = nodeTiles.cache.slice();
37450         nodeTiles.caching = this._requiredNodeTiles[key].caching.concat(hs);
37451         nodeTiles.cache = [];
37452         var cacheTiles$ = [];
37453         var _loop_2 = function (h) {
37454             var cacheTile$ = h in this_2._cachingTiles$ ?
37455                 this_2._cachingTiles$[h] :
37456                 this_2._cacheTile$(h);
37457             cacheTiles$.push(cacheTile$
37458                 .do(function (graph) {
37459                 var index = nodeTiles.caching.indexOf(h);
37460                 if (index > -1) {
37461                     nodeTiles.caching.splice(index, 1);
37462                 }
37463                 if (nodeTiles.caching.length === 0 &&
37464                     nodeTiles.cache.length === 0) {
37465                     delete _this._requiredNodeTiles[key];
37466                     _this._cachedNodeTiles[key] = true;
37467                 }
37468             })
37469                 .catch(function (error) {
37470                 var index = nodeTiles.caching.indexOf(h);
37471                 if (index > -1) {
37472                     nodeTiles.caching.splice(index, 1);
37473                 }
37474                 if (nodeTiles.caching.length === 0 &&
37475                     nodeTiles.cache.length === 0) {
37476                     delete _this._requiredNodeTiles[key];
37477                     _this._cachedNodeTiles[key] = true;
37478                 }
37479                 throw error;
37480             })
37481                 .finally(function () {
37482                 _this._changed$.next(_this);
37483             })
37484                 .publish()
37485                 .refCount());
37486         };
37487         var this_2 = this;
37488         for (var _i = 0, _a = nodeTiles.caching; _i < _a.length; _i++) {
37489             var h = _a[_i];
37490             _loop_2(h);
37491         }
37492         return cacheTiles$;
37493     };
37494     /**
37495      * Initialize the cache for a node.
37496      *
37497      * @param {string} key - Key of node.
37498      * @throws {GraphMapillaryError} When the operation is not valid on the
37499      * current graph.
37500      */
37501     Graph.prototype.initializeCache = function (key) {
37502         if (key in this._cachedNodes) {
37503             throw new Error_1.GraphMapillaryError("Node already in cache (" + key + ").");
37504         }
37505         var node = this.getNode(key);
37506         node.initializeCache(new Graph_1.NodeCache());
37507         var accessed = new Date().getTime();
37508         this._cachedNodes[key] = { accessed: accessed, node: node };
37509         this._updateCachedTileAccess(key, accessed);
37510     };
37511     /**
37512      * Get a value indicating if the graph is fill caching a node.
37513      *
37514      * @param {string} key - Key of node.
37515      * @returns {boolean} Value indicating if the node is being fill cached.
37516      */
37517     Graph.prototype.isCachingFill = function (key) {
37518         return key in this._cachingFill$;
37519     };
37520     /**
37521      * Get a value indicating if the graph is fully caching a node.
37522      *
37523      * @param {string} key - Key of node.
37524      * @returns {boolean} Value indicating if the node is being fully cached.
37525      */
37526     Graph.prototype.isCachingFull = function (key) {
37527         return key in this._cachingFull$;
37528     };
37529     /**
37530      * Get a value indicating if the graph is caching a sequence of a node.
37531      *
37532      * @param {string} key - Key of node.
37533      * @returns {boolean} Value indicating if the sequence of a node is
37534      * being cached.
37535      */
37536     Graph.prototype.isCachingNodeSequence = function (key) {
37537         var node = this.getNode(key);
37538         return node.sequenceKey in this._cachingSequences$;
37539     };
37540     /**
37541      * Get a value indicating if the graph is caching a sequence.
37542      *
37543      * @param {string} sequenceKey - Key of sequence.
37544      * @returns {boolean} Value indicating if the sequence is
37545      * being cached.
37546      */
37547     Graph.prototype.isCachingSequence = function (sequenceKey) {
37548         return sequenceKey in this._cachingSequences$;
37549     };
37550     /**
37551      * Get a value indicating if the graph is caching sequence nodes.
37552      *
37553      * @param {string} sequenceKey - Key of sequence.
37554      * @returns {boolean} Value indicating if the sequence nodes are
37555      * being cached.
37556      */
37557     Graph.prototype.isCachingSequenceNodes = function (sequenceKey) {
37558         return sequenceKey in this._cachingSequenceNodes$;
37559     };
37560     /**
37561      * Get a value indicating if the graph is caching the tiles
37562      * required for calculating spatial edges of a node.
37563      *
37564      * @param {string} key - Key of node.
37565      * @returns {boolean} Value indicating if the tiles of
37566      * a node are being cached.
37567      */
37568     Graph.prototype.isCachingTiles = function (key) {
37569         return key in this._requiredNodeTiles &&
37570             this._requiredNodeTiles[key].cache.length === 0 &&
37571             this._requiredNodeTiles[key].caching.length > 0;
37572     };
37573     /**
37574      * Get a value indicating if the cache has been initialized
37575      * for a node.
37576      *
37577      * @param {string} key - Key of node.
37578      * @returns {boolean} Value indicating if the cache has been
37579      * initialized for a node.
37580      */
37581     Graph.prototype.hasInitializedCache = function (key) {
37582         return key in this._cachedNodes;
37583     };
37584     /**
37585      * Get a value indicating if a node exist in the graph.
37586      *
37587      * @param {string} key - Key of node.
37588      * @returns {boolean} Value indicating if a node exist in the graph.
37589      */
37590     Graph.prototype.hasNode = function (key) {
37591         var accessed = new Date().getTime();
37592         this._updateCachedNodeAccess(key, accessed);
37593         this._updateCachedTileAccess(key, accessed);
37594         return key in this._nodes;
37595     };
37596     /**
37597      * Get a value indicating if a node sequence exist in the graph.
37598      *
37599      * @param {string} key - Key of node.
37600      * @returns {boolean} Value indicating if a node sequence exist
37601      * in the graph.
37602      */
37603     Graph.prototype.hasNodeSequence = function (key) {
37604         var node = this.getNode(key);
37605         var sequenceKey = node.sequenceKey;
37606         var hasNodeSequence = sequenceKey in this._sequences;
37607         if (hasNodeSequence) {
37608             this._sequences[sequenceKey].accessed = new Date().getTime();
37609         }
37610         return hasNodeSequence;
37611     };
37612     /**
37613      * Get a value indicating if a sequence exist in the graph.
37614      *
37615      * @param {string} sequenceKey - Key of sequence.
37616      * @returns {boolean} Value indicating if a sequence exist
37617      * in the graph.
37618      */
37619     Graph.prototype.hasSequence = function (sequenceKey) {
37620         var hasSequence = sequenceKey in this._sequences;
37621         if (hasSequence) {
37622             this._sequences[sequenceKey].accessed = new Date().getTime();
37623         }
37624         return hasSequence;
37625     };
37626     /**
37627      * Get a value indicating if sequence nodes has been cached in the graph.
37628      *
37629      * @param {string} sequenceKey - Key of sequence.
37630      * @returns {boolean} Value indicating if a sequence nodes has been
37631      * cached in the graph.
37632      */
37633     Graph.prototype.hasSequenceNodes = function (sequenceKey) {
37634         return sequenceKey in this._cachedSequenceNodes;
37635     };
37636     /**
37637      * Get a value indicating if the graph has fully cached
37638      * all nodes in the spatial area of a node.
37639      *
37640      * @param {string} key - Key of node.
37641      * @returns {boolean} Value indicating if the spatial area
37642      * of a node has been cached.
37643      */
37644     Graph.prototype.hasSpatialArea = function (key) {
37645         if (!this.hasNode(key)) {
37646             throw new Error_1.GraphMapillaryError("Spatial area nodes cannot be determined if node not in graph (" + key + ").");
37647         }
37648         if (key in this._cachedSpatialEdges) {
37649             return true;
37650         }
37651         if (key in this._requiredSpatialArea) {
37652             return Object.keys(this._requiredSpatialArea[key].cacheNodes).length === 0;
37653         }
37654         var node = this.getNode(key);
37655         var bbox = this._graphCalculator.boundingBoxCorners(node.latLon, this._tileThreshold);
37656         var spatialItems = this._nodeIndex.search({
37657             maxX: bbox[1].lat,
37658             maxY: bbox[1].lon,
37659             minX: bbox[0].lat,
37660             minY: bbox[0].lon,
37661         });
37662         var spatialNodes = {
37663             all: {},
37664             cacheKeys: [],
37665             cacheNodes: {},
37666         };
37667         for (var _i = 0, spatialItems_1 = spatialItems; _i < spatialItems_1.length; _i++) {
37668             var spatialItem = spatialItems_1[_i];
37669             spatialNodes.all[spatialItem.node.key] = spatialItem.node;
37670             if (!spatialItem.node.full) {
37671                 spatialNodes.cacheKeys.push(spatialItem.node.key);
37672                 spatialNodes.cacheNodes[spatialItem.node.key] = spatialItem.node;
37673             }
37674         }
37675         this._requiredSpatialArea[key] = spatialNodes;
37676         return spatialNodes.cacheKeys.length === 0;
37677     };
37678     /**
37679      * Get a value indicating if the graph has a tiles required
37680      * for a node.
37681      *
37682      * @param {string} key - Key of node.
37683      * @returns {boolean} Value indicating if the the tiles required
37684      * by a node has been cached.
37685      */
37686     Graph.prototype.hasTiles = function (key) {
37687         var _this = this;
37688         if (key in this._cachedNodeTiles) {
37689             return true;
37690         }
37691         if (key in this._cachedSpatialEdges) {
37692             return true;
37693         }
37694         if (!this.hasNode(key)) {
37695             throw new Error_1.GraphMapillaryError("Node does not exist in graph (" + key + ").");
37696         }
37697         var nodeTiles = { cache: [], caching: [] };
37698         if (!(key in this._requiredNodeTiles)) {
37699             var node = this.getNode(key);
37700             nodeTiles.cache = this._graphCalculator
37701                 .encodeHs(node.latLon, this._tilePrecision, this._tileThreshold)
37702                 .filter(function (h) {
37703                 return !(h in _this._cachedTiles);
37704             });
37705             if (nodeTiles.cache.length > 0) {
37706                 this._requiredNodeTiles[key] = nodeTiles;
37707             }
37708         }
37709         else {
37710             nodeTiles = this._requiredNodeTiles[key];
37711         }
37712         return nodeTiles.cache.length === 0 && nodeTiles.caching.length === 0;
37713     };
37714     /**
37715      * Get a node.
37716      *
37717      * @param {string} key - Key of node.
37718      * @returns {Node} Retrieved node.
37719      */
37720     Graph.prototype.getNode = function (key) {
37721         var accessed = new Date().getTime();
37722         this._updateCachedNodeAccess(key, accessed);
37723         this._updateCachedTileAccess(key, accessed);
37724         return this._nodes[key];
37725     };
37726     /**
37727      * Get a sequence.
37728      *
37729      * @param {string} sequenceKey - Key of sequence.
37730      * @returns {Node} Retrieved sequence.
37731      */
37732     Graph.prototype.getSequence = function (sequenceKey) {
37733         var sequenceAccess = this._sequences[sequenceKey];
37734         sequenceAccess.accessed = new Date().getTime();
37735         return sequenceAccess.sequence;
37736     };
37737     /**
37738      * Reset all spatial edges of the graph nodes.
37739      */
37740     Graph.prototype.resetSpatialEdges = function () {
37741         var cachedKeys = Object.keys(this._cachedSpatialEdges);
37742         for (var _i = 0, cachedKeys_1 = cachedKeys; _i < cachedKeys_1.length; _i++) {
37743             var cachedKey = cachedKeys_1[_i];
37744             var node = this._cachedSpatialEdges[cachedKey];
37745             node.resetSpatialEdges();
37746             delete this._cachedSpatialEdges[cachedKey];
37747         }
37748     };
37749     /**
37750      * Reset the complete graph but keep the nodes corresponding
37751      * to the supplied keys. All other nodes will be disposed.
37752      *
37753      * @param {Array<string>} keepKeys - Keys for nodes to keep
37754      * in graph after reset.
37755      */
37756     Graph.prototype.reset = function (keepKeys) {
37757         var nodes = [];
37758         for (var _i = 0, keepKeys_1 = keepKeys; _i < keepKeys_1.length; _i++) {
37759             var key = keepKeys_1[_i];
37760             if (!this.hasNode(key)) {
37761                 throw new Error("Node does not exist " + key);
37762             }
37763             var node = this.getNode(key);
37764             node.resetSequenceEdges();
37765             node.resetSpatialEdges();
37766             nodes.push(node);
37767         }
37768         for (var _a = 0, _b = Object.keys(this._cachedNodes); _a < _b.length; _a++) {
37769             var cachedKey = _b[_a];
37770             if (keepKeys.indexOf(cachedKey) !== -1) {
37771                 continue;
37772             }
37773             this._cachedNodes[cachedKey].node.dispose();
37774             delete this._cachedNodes[cachedKey];
37775         }
37776         this._cachedNodeTiles = {};
37777         this._cachedSpatialEdges = {};
37778         this._cachedTiles = {};
37779         this._cachingFill$ = {};
37780         this._cachingFull$ = {};
37781         this._cachingSequences$ = {};
37782         this._cachingSpatialArea$ = {};
37783         this._cachingTiles$ = {};
37784         this._nodes = {};
37785         this._nodeToTile = {};
37786         this._preStored = {};
37787         for (var _c = 0, nodes_2 = nodes; _c < nodes_2.length; _c++) {
37788             var node = nodes_2[_c];
37789             this._nodes[node.key] = node;
37790             var h = this._graphCalculator.encodeH(node.originalLatLon, this._tilePrecision);
37791             this._preStore(h, node);
37792         }
37793         this._requiredNodeTiles = {};
37794         this._requiredSpatialArea = {};
37795         this._sequences = {};
37796         this._nodeIndexTiles = {};
37797         this._nodeIndex.clear();
37798     };
37799     /**
37800      * Set the spatial node filter.
37801      *
37802      * @param {FilterExpression} filter - Filter expression to be applied
37803      * when calculating spatial edges.
37804      */
37805     Graph.prototype.setFilter = function (filter) {
37806         this._filter = this._filterCreator.createFilter(filter);
37807     };
37808     /**
37809      * Uncache the graph according to the graph configuration.
37810      *
37811      * @description Uncaches unused tiles, unused nodes and
37812      * sequences according to the numbers specified in the
37813      * graph configuration. Sequences does not have a direct
37814      * reference to either tiles or nodes and may be uncached
37815      * even if they are related to the nodes that should be kept.
37816      *
37817      * @param {Array<string>} keepKeys - Keys of nodes to keep in
37818      * graph unrelated to last access. Tiles related to those keys
37819      * will also be kept in graph.
37820      * @param {string} keepSequenceKey - Optional key of sequence
37821      * for which the belonging nodes should not be disposed or
37822      * removed from the graph. These nodes may still be uncached if
37823      * not specified in keep keys param.
37824      */
37825     Graph.prototype.uncache = function (keepKeys, keepSequenceKey) {
37826         var keysInUse = {};
37827         this._addNewKeys(keysInUse, this._cachingFull$);
37828         this._addNewKeys(keysInUse, this._cachingFill$);
37829         this._addNewKeys(keysInUse, this._cachingSpatialArea$);
37830         this._addNewKeys(keysInUse, this._requiredNodeTiles);
37831         this._addNewKeys(keysInUse, this._requiredSpatialArea);
37832         for (var _i = 0, keepKeys_2 = keepKeys; _i < keepKeys_2.length; _i++) {
37833             var key = keepKeys_2[_i];
37834             if (key in keysInUse) {
37835                 continue;
37836             }
37837             keysInUse[key] = true;
37838         }
37839         var keepHs = {};
37840         for (var key in keysInUse) {
37841             if (!keysInUse.hasOwnProperty(key)) {
37842                 continue;
37843             }
37844             var node = this._nodes[key];
37845             var nodeHs = this._graphCalculator.encodeHs(node.latLon);
37846             for (var _a = 0, nodeHs_1 = nodeHs; _a < nodeHs_1.length; _a++) {
37847                 var nodeH = nodeHs_1[_a];
37848                 if (!(nodeH in keepHs)) {
37849                     keepHs[nodeH] = true;
37850                 }
37851             }
37852         }
37853         var potentialHs = [];
37854         for (var h in this._cachedTiles) {
37855             if (!this._cachedTiles.hasOwnProperty(h) || h in keepHs) {
37856                 continue;
37857             }
37858             potentialHs.push([h, this._cachedTiles[h]]);
37859         }
37860         var uncacheHs = potentialHs
37861             .sort(function (h1, h2) {
37862             return h2[1].accessed - h1[1].accessed;
37863         })
37864             .slice(this._configuration.maxUnusedTiles)
37865             .map(function (h) {
37866             return h[0];
37867         });
37868         for (var _b = 0, uncacheHs_1 = uncacheHs; _b < uncacheHs_1.length; _b++) {
37869             var uncacheH = uncacheHs_1[_b];
37870             this._uncacheTile(uncacheH, keepSequenceKey);
37871         }
37872         var potentialPreStored = [];
37873         var nonCachedPreStored = [];
37874         for (var h in this._preStored) {
37875             if (!this._preStored.hasOwnProperty(h) || h in this._cachingTiles$) {
37876                 continue;
37877             }
37878             var prestoredNodes = this._preStored[h];
37879             for (var key in prestoredNodes) {
37880                 if (!prestoredNodes.hasOwnProperty(key) || key in keysInUse) {
37881                     continue;
37882                 }
37883                 if (prestoredNodes[key].sequenceKey === keepSequenceKey) {
37884                     continue;
37885                 }
37886                 if (key in this._cachedNodes) {
37887                     potentialPreStored.push([this._cachedNodes[key], h]);
37888                 }
37889                 else {
37890                     nonCachedPreStored.push([key, h]);
37891                 }
37892             }
37893         }
37894         var uncachePreStored = potentialPreStored
37895             .sort(function (_a, _b) {
37896             var na1 = _a[0], h1 = _a[1];
37897             var na2 = _b[0], h2 = _b[1];
37898             return na2.accessed - na1.accessed;
37899         })
37900             .slice(this._configuration.maxUnusedPreStoredNodes)
37901             .map(function (_a) {
37902             var na = _a[0], h = _a[1];
37903             return [na.node.key, h];
37904         });
37905         this._uncachePreStored(nonCachedPreStored);
37906         this._uncachePreStored(uncachePreStored);
37907         var potentialNodes = [];
37908         for (var key in this._cachedNodes) {
37909             if (!this._cachedNodes.hasOwnProperty(key) || key in keysInUse) {
37910                 continue;
37911             }
37912             potentialNodes.push(this._cachedNodes[key]);
37913         }
37914         var uncacheNodes = potentialNodes
37915             .sort(function (n1, n2) {
37916             return n2.accessed - n1.accessed;
37917         })
37918             .slice(this._configuration.maxUnusedNodes);
37919         for (var _c = 0, uncacheNodes_1 = uncacheNodes; _c < uncacheNodes_1.length; _c++) {
37920             var nodeAccess = uncacheNodes_1[_c];
37921             nodeAccess.node.uncache();
37922             var key = nodeAccess.node.key;
37923             delete this._cachedNodes[key];
37924             if (key in this._cachedNodeTiles) {
37925                 delete this._cachedNodeTiles[key];
37926             }
37927             if (key in this._cachedSpatialEdges) {
37928                 delete this._cachedSpatialEdges[key];
37929             }
37930         }
37931         var potentialSequences = [];
37932         for (var sequenceKey in this._sequences) {
37933             if (!this._sequences.hasOwnProperty(sequenceKey) ||
37934                 sequenceKey in this._cachingSequences$ ||
37935                 sequenceKey === keepSequenceKey) {
37936                 continue;
37937             }
37938             potentialSequences.push(this._sequences[sequenceKey]);
37939         }
37940         var uncacheSequences = potentialSequences
37941             .sort(function (s1, s2) {
37942             return s2.accessed - s1.accessed;
37943         })
37944             .slice(this._configuration.maxSequences);
37945         for (var _d = 0, uncacheSequences_1 = uncacheSequences; _d < uncacheSequences_1.length; _d++) {
37946             var sequenceAccess = uncacheSequences_1[_d];
37947             var sequenceKey = sequenceAccess.sequence.key;
37948             delete this._sequences[sequenceKey];
37949             if (sequenceKey in this._cachedSequenceNodes) {
37950                 delete this._cachedSequenceNodes[sequenceKey];
37951             }
37952             sequenceAccess.sequence.dispose();
37953         }
37954     };
37955     Graph.prototype._addNewKeys = function (keys, dict) {
37956         for (var key in dict) {
37957             if (!dict.hasOwnProperty(key) || !this.hasNode(key)) {
37958                 continue;
37959             }
37960             if (!(key in keys)) {
37961                 keys[key] = true;
37962             }
37963         }
37964     };
37965     Graph.prototype._cacheSequence$ = function (sequenceKey) {
37966         var _this = this;
37967         if (sequenceKey in this._cachingSequences$) {
37968             return this._cachingSequences$[sequenceKey];
37969         }
37970         this._cachingSequences$[sequenceKey] = this._apiV3.sequenceByKey$([sequenceKey])
37971             .do(function (sequenceByKey) {
37972             if (!(sequenceKey in _this._sequences)) {
37973                 _this._sequences[sequenceKey] = {
37974                     accessed: new Date().getTime(),
37975                     sequence: new Graph_1.Sequence(sequenceByKey[sequenceKey]),
37976                 };
37977             }
37978             delete _this._cachingSequences$[sequenceKey];
37979         })
37980             .map(function (sequenceByKey) {
37981             return _this;
37982         })
37983             .finally(function () {
37984             if (sequenceKey in _this._cachingSequences$) {
37985                 delete _this._cachingSequences$[sequenceKey];
37986             }
37987             _this._changed$.next(_this);
37988         })
37989             .publish()
37990             .refCount();
37991         return this._cachingSequences$[sequenceKey];
37992     };
37993     Graph.prototype._cacheTile$ = function (h) {
37994         var _this = this;
37995         this._cachingTiles$[h] = this._apiV3.imagesByH$([h])
37996             .do(function (imagesByH) {
37997             var coreNodes = imagesByH[h];
37998             if (h in _this._cachedTiles) {
37999                 return;
38000             }
38001             _this._nodeIndexTiles[h] = [];
38002             _this._cachedTiles[h] = { accessed: new Date().getTime(), nodes: [] };
38003             var hCache = _this._cachedTiles[h].nodes;
38004             var preStored = _this._removeFromPreStore(h);
38005             for (var index in coreNodes) {
38006                 if (!coreNodes.hasOwnProperty(index)) {
38007                     continue;
38008                 }
38009                 var coreNode = coreNodes[index];
38010                 if (coreNode == null) {
38011                     break;
38012                 }
38013                 if (coreNode.sequence_key == null) {
38014                     console.warn("Sequence missing, discarding node (" + coreNode.key + ")");
38015                     continue;
38016                 }
38017                 if (preStored != null && coreNode.key in preStored) {
38018                     var preStoredNode = preStored[coreNode.key];
38019                     delete preStored[coreNode.key];
38020                     hCache.push(preStoredNode);
38021                     var preStoredNodeIndexItem = {
38022                         lat: preStoredNode.latLon.lat,
38023                         lon: preStoredNode.latLon.lon,
38024                         node: preStoredNode,
38025                     };
38026                     _this._nodeIndex.insert(preStoredNodeIndexItem);
38027                     _this._nodeIndexTiles[h].push(preStoredNodeIndexItem);
38028                     _this._nodeToTile[preStoredNode.key] = h;
38029                     continue;
38030                 }
38031                 var node = new Graph_1.Node(coreNode);
38032                 hCache.push(node);
38033                 var nodeIndexItem = {
38034                     lat: node.latLon.lat,
38035                     lon: node.latLon.lon,
38036                     node: node,
38037                 };
38038                 _this._nodeIndex.insert(nodeIndexItem);
38039                 _this._nodeIndexTiles[h].push(nodeIndexItem);
38040                 _this._nodeToTile[node.key] = h;
38041                 _this._setNode(node);
38042             }
38043             delete _this._cachingTiles$[h];
38044         })
38045             .map(function (imagesByH) {
38046             return _this;
38047         })
38048             .catch(function (error) {
38049             delete _this._cachingTiles$[h];
38050             throw error;
38051         })
38052             .publish()
38053             .refCount();
38054         return this._cachingTiles$[h];
38055     };
38056     Graph.prototype._makeFull = function (node, fillNode) {
38057         if (fillNode.calt == null) {
38058             fillNode.calt = this._defaultAlt;
38059         }
38060         if (fillNode.c_rotation == null) {
38061             fillNode.c_rotation = this._graphCalculator.rotationFromCompass(fillNode.ca, fillNode.orientation);
38062         }
38063         node.makeFull(fillNode);
38064     };
38065     Graph.prototype._preStore = function (h, node) {
38066         if (!(h in this._preStored)) {
38067             this._preStored[h] = {};
38068         }
38069         this._preStored[h][node.key] = node;
38070     };
38071     Graph.prototype._removeFromPreStore = function (h) {
38072         var preStored = null;
38073         if (h in this._preStored) {
38074             preStored = this._preStored[h];
38075             delete this._preStored[h];
38076         }
38077         return preStored;
38078     };
38079     Graph.prototype._setNode = function (node) {
38080         var key = node.key;
38081         if (this.hasNode(key)) {
38082             throw new Error_1.GraphMapillaryError("Node already exist (" + key + ").");
38083         }
38084         this._nodes[key] = node;
38085     };
38086     Graph.prototype._uncacheTile = function (h, keepSequenceKey) {
38087         for (var _i = 0, _a = this._cachedTiles[h].nodes; _i < _a.length; _i++) {
38088             var node = _a[_i];
38089             var key = node.key;
38090             delete this._nodeToTile[key];
38091             if (key in this._cachedNodes) {
38092                 delete this._cachedNodes[key];
38093             }
38094             if (key in this._cachedNodeTiles) {
38095                 delete this._cachedNodeTiles[key];
38096             }
38097             if (key in this._cachedSpatialEdges) {
38098                 delete this._cachedSpatialEdges[key];
38099             }
38100             if (node.sequenceKey === keepSequenceKey) {
38101                 this._preStore(h, node);
38102                 node.uncache();
38103             }
38104             else {
38105                 delete this._nodes[key];
38106                 if (node.sequenceKey in this._cachedSequenceNodes) {
38107                     delete this._cachedSequenceNodes[node.sequenceKey];
38108                 }
38109                 node.dispose();
38110             }
38111         }
38112         for (var _b = 0, _c = this._nodeIndexTiles[h]; _b < _c.length; _b++) {
38113             var nodeIndexItem = _c[_b];
38114             this._nodeIndex.remove(nodeIndexItem);
38115         }
38116         delete this._nodeIndexTiles[h];
38117         delete this._cachedTiles[h];
38118     };
38119     Graph.prototype._uncachePreStored = function (preStored) {
38120         var hs = {};
38121         for (var _i = 0, preStored_1 = preStored; _i < preStored_1.length; _i++) {
38122             var _a = preStored_1[_i], key = _a[0], h = _a[1];
38123             if (key in this._nodes) {
38124                 delete this._nodes[key];
38125             }
38126             if (key in this._cachedNodes) {
38127                 delete this._cachedNodes[key];
38128             }
38129             var node = this._preStored[h][key];
38130             if (node.sequenceKey in this._cachedSequenceNodes) {
38131                 delete this._cachedSequenceNodes[node.sequenceKey];
38132             }
38133             delete this._preStored[h][key];
38134             node.dispose();
38135             hs[h] = true;
38136         }
38137         for (var h in hs) {
38138             if (!hs.hasOwnProperty(h)) {
38139                 continue;
38140             }
38141             if (Object.keys(this._preStored[h]).length === 0) {
38142                 delete this._preStored[h];
38143             }
38144         }
38145     };
38146     Graph.prototype._updateCachedTileAccess = function (key, accessed) {
38147         if (key in this._nodeToTile) {
38148             this._cachedTiles[this._nodeToTile[key]].accessed = accessed;
38149         }
38150     };
38151     Graph.prototype._updateCachedNodeAccess = function (key, accessed) {
38152         if (key in this._cachedNodes) {
38153             this._cachedNodes[key].accessed = accessed;
38154         }
38155     };
38156     return Graph;
38157 }());
38158 exports.Graph = Graph;
38159 exports.default = Graph;
38160
38161 },{"../Edge":292,"../Error":293,"../Graph":295,"rbush":25,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/from":42,"rxjs/add/operator/catch":54,"rxjs/add/operator/do":61,"rxjs/add/operator/finally":64,"rxjs/add/operator/last":66,"rxjs/add/operator/map":67,"rxjs/add/operator/publish":73,"rxjs/add/operator/reduce":75}],394:[function(require,module,exports){
38162 "use strict";
38163 /// <reference path="../../typings/index.d.ts" />
38164 Object.defineProperty(exports, "__esModule", { value: true });
38165 var geohash = require("latlon-geohash");
38166 var THREE = require("three");
38167 var Error_1 = require("../Error");
38168 var Geo_1 = require("../Geo");
38169 var GeoHashDirections = /** @class */ (function () {
38170     function GeoHashDirections() {
38171     }
38172     GeoHashDirections.n = "n";
38173     GeoHashDirections.nw = "nw";
38174     GeoHashDirections.w = "w";
38175     GeoHashDirections.sw = "sw";
38176     GeoHashDirections.s = "s";
38177     GeoHashDirections.se = "se";
38178     GeoHashDirections.e = "e";
38179     GeoHashDirections.ne = "ne";
38180     return GeoHashDirections;
38181 }());
38182 /**
38183  * @class GraphCalculator
38184  *
38185  * @classdesc Represents a calculator for graph entities.
38186  */
38187 var GraphCalculator = /** @class */ (function () {
38188     /**
38189      * Create a new graph calculator instance.
38190      *
38191      * @param {GeoCoords} geoCoords - Geo coords instance.
38192      */
38193     function GraphCalculator(geoCoords) {
38194         this._geoCoords = geoCoords != null ? geoCoords : new Geo_1.GeoCoords();
38195     }
38196     /**
38197      * Encode the geohash tile for geodetic coordinates.
38198      *
38199      * @param {ILatLon} latlon - Latitude and longitude to encode.
38200      * @param {number} precision - Precision of the encoding.
38201      *
38202      * @returns {string} The geohash tile for the lat, lon and precision.
38203      */
38204     GraphCalculator.prototype.encodeH = function (latLon, precision) {
38205         if (precision === void 0) { precision = 7; }
38206         return geohash.encode(latLon.lat, latLon.lon, precision);
38207     };
38208     /**
38209      * Encode the geohash tiles within a threshold from a position
38210      * using Manhattan distance.
38211      *
38212      * @param {ILatLon} latlon - Latitude and longitude to encode.
38213      * @param {number} precision - Precision of the encoding.
38214      * @param {number} threshold - Threshold of the encoding in meters.
38215      *
38216      * @returns {string} The geohash tiles reachable within the threshold.
38217      */
38218     GraphCalculator.prototype.encodeHs = function (latLon, precision, threshold) {
38219         if (precision === void 0) { precision = 7; }
38220         if (threshold === void 0) { threshold = 20; }
38221         var h = geohash.encode(latLon.lat, latLon.lon, precision);
38222         var bounds = geohash.bounds(h);
38223         var ne = bounds.ne;
38224         var sw = bounds.sw;
38225         var neighbours = geohash.neighbours(h);
38226         var bl = [0, 0, 0];
38227         var tr = this._geoCoords.geodeticToEnu(ne.lat, ne.lon, 0, sw.lat, sw.lon, 0);
38228         var position = this._geoCoords.geodeticToEnu(latLon.lat, latLon.lon, 0, sw.lat, sw.lon, 0);
38229         var left = position[0] - bl[0];
38230         var right = tr[0] - position[0];
38231         var bottom = position[1] - bl[1];
38232         var top = tr[1] - position[1];
38233         var l = left < threshold;
38234         var r = right < threshold;
38235         var b = bottom < threshold;
38236         var t = top < threshold;
38237         var hs = [h];
38238         if (t) {
38239             hs.push(neighbours[GeoHashDirections.n]);
38240         }
38241         if (t && l) {
38242             hs.push(neighbours[GeoHashDirections.nw]);
38243         }
38244         if (l) {
38245             hs.push(neighbours[GeoHashDirections.w]);
38246         }
38247         if (l && b) {
38248             hs.push(neighbours[GeoHashDirections.sw]);
38249         }
38250         if (b) {
38251             hs.push(neighbours[GeoHashDirections.s]);
38252         }
38253         if (b && r) {
38254             hs.push(neighbours[GeoHashDirections.se]);
38255         }
38256         if (r) {
38257             hs.push(neighbours[GeoHashDirections.e]);
38258         }
38259         if (r && t) {
38260             hs.push(neighbours[GeoHashDirections.ne]);
38261         }
38262         return hs;
38263     };
38264     /**
38265      * Encode the minimum set of geohash tiles containing a bounding box.
38266      *
38267      * @description The current algorithm does expect the bounding box
38268      * to be sufficiently small to be contained in an area with the size
38269      * of maximally four tiles. Up to nine adjacent tiles may be returned.
38270      * The method currently uses the largest side as the threshold leading to
38271      * more tiles being returned than needed in edge cases.
38272      *
38273      * @param {ILatLon} sw - South west corner of bounding box.
38274      * @param {ILatLon} ne - North east corner of bounding box.
38275      * @param {number} precision - Precision of the encoding.
38276      *
38277      * @returns {string} The geohash tiles containing the bounding box.
38278      */
38279     GraphCalculator.prototype.encodeHsFromBoundingBox = function (sw, ne, precision) {
38280         if (precision === void 0) { precision = 7; }
38281         if (ne.lat <= sw.lat || ne.lon <= sw.lon) {
38282             throw new Error_1.GraphMapillaryError("North east needs to be top right of south west");
38283         }
38284         var centerLat = (sw.lat + ne.lat) / 2;
38285         var centerLon = (sw.lon + ne.lon) / 2;
38286         var enu = this._geoCoords.geodeticToEnu(ne.lat, ne.lon, 0, centerLat, centerLon, 0);
38287         var threshold = Math.max(enu[0], enu[1]);
38288         return this.encodeHs({ lat: centerLat, lon: centerLon }, precision, threshold);
38289     };
38290     /**
38291      * Get the bounding box corners for a circle with radius of a threshold
38292      * with center in a geodetic position.
38293      *
38294      * @param {ILatLon} latlon - Latitude and longitude to encode.
38295      * @param {number} threshold - Threshold distance from the position in meters.
38296      *
38297      * @returns {Array<ILatLon>} The south west and north east corners of the
38298      * bounding box.
38299      */
38300     GraphCalculator.prototype.boundingBoxCorners = function (latLon, threshold) {
38301         var bl = this._geoCoords.enuToGeodetic(-threshold, -threshold, 0, latLon.lat, latLon.lon, 0);
38302         var tr = this._geoCoords.enuToGeodetic(threshold, threshold, 0, latLon.lat, latLon.lon, 0);
38303         return [
38304             { lat: bl[0], lon: bl[1] },
38305             { lat: tr[0], lon: tr[1] },
38306         ];
38307     };
38308     /**
38309      * Convert a compass angle to an angle axis rotation vector.
38310      *
38311      * @param {number} compassAngle - The compass angle in degrees.
38312      * @param {number} orientation - The orientation of the original image.
38313      *
38314      * @returns {Array<number>} Angle axis rotation vector.
38315      */
38316     GraphCalculator.prototype.rotationFromCompass = function (compassAngle, orientation) {
38317         var x = 0;
38318         var y = 0;
38319         var z = 0;
38320         switch (orientation) {
38321             case 1:
38322                 x = Math.PI / 2;
38323                 break;
38324             case 3:
38325                 x = -Math.PI / 2;
38326                 z = Math.PI;
38327                 break;
38328             case 6:
38329                 y = -Math.PI / 2;
38330                 z = -Math.PI / 2;
38331                 break;
38332             case 8:
38333                 y = Math.PI / 2;
38334                 z = Math.PI / 2;
38335                 break;
38336             default:
38337                 break;
38338         }
38339         var rz = new THREE.Matrix4().makeRotationZ(z);
38340         var euler = new THREE.Euler(x, y, compassAngle * Math.PI / 180, "XYZ");
38341         var re = new THREE.Matrix4().makeRotationFromEuler(euler);
38342         var rotation = new THREE.Vector4().setAxisAngleFromRotationMatrix(re.multiply(rz));
38343         return rotation.multiplyScalar(rotation.w).toArray().slice(0, 3);
38344     };
38345     return GraphCalculator;
38346 }());
38347 exports.GraphCalculator = GraphCalculator;
38348 exports.default = GraphCalculator;
38349
38350 },{"../Error":293,"../Geo":294,"latlon-geohash":21,"three":241}],395:[function(require,module,exports){
38351 "use strict";
38352 Object.defineProperty(exports, "__esModule", { value: true });
38353 /**
38354  * Enumeration for graph modes.
38355  * @enum {number}
38356  * @readonly
38357  * @description Modes for the retrieval and caching performed
38358  * by the graph service on the graph.
38359  */
38360 var GraphMode;
38361 (function (GraphMode) {
38362     /**
38363      * Caching is performed on sequences only and sequence edges are
38364      * calculated. Spatial tiles
38365      * are not retrieved and spatial edges are not calculated when
38366      * caching nodes. Complete sequences are being cached for requested
38367      * nodes within the graph.
38368      */
38369     GraphMode[GraphMode["Sequence"] = 0] = "Sequence";
38370     /**
38371      * Caching is performed with emphasis on spatial data. Sequence edges
38372      * as well as spatial edges are cached. Sequence data
38373      * is still requested but complete sequences are not being cached
38374      * for requested nodes.
38375      *
38376      * This is the initial mode of the graph service.
38377      */
38378     GraphMode[GraphMode["Spatial"] = 1] = "Spatial";
38379 })(GraphMode = exports.GraphMode || (exports.GraphMode = {}));
38380 exports.default = GraphMode;
38381
38382 },{}],396:[function(require,module,exports){
38383 "use strict";
38384 Object.defineProperty(exports, "__esModule", { value: true });
38385 var Observable_1 = require("rxjs/Observable");
38386 var Subject_1 = require("rxjs/Subject");
38387 require("rxjs/add/operator/catch");
38388 require("rxjs/add/operator/concat");
38389 require("rxjs/add/operator/do");
38390 require("rxjs/add/operator/expand");
38391 require("rxjs/add/operator/finally");
38392 require("rxjs/add/operator/first");
38393 require("rxjs/add/operator/last");
38394 require("rxjs/add/operator/map");
38395 require("rxjs/add/operator/mergeMap");
38396 require("rxjs/add/operator/publishReplay");
38397 var Graph_1 = require("../Graph");
38398 /**
38399  * @class GraphService
38400  *
38401  * @classdesc Represents a service for graph operations.
38402  */
38403 var GraphService = /** @class */ (function () {
38404     /**
38405      * Create a new graph service instance.
38406      *
38407      * @param {Graph} graph - Graph instance to be operated on.
38408      */
38409     function GraphService(graph, imageLoadingService) {
38410         this._graph$ = Observable_1.Observable
38411             .of(graph)
38412             .concat(graph.changed$)
38413             .publishReplay(1)
38414             .refCount();
38415         this._graph$.subscribe(function () { });
38416         this._graphMode = Graph_1.GraphMode.Spatial;
38417         this._graphModeSubject$ = new Subject_1.Subject();
38418         this._graphMode$ = this._graphModeSubject$
38419             .startWith(this._graphMode)
38420             .publishReplay(1)
38421             .refCount();
38422         this._graphMode$.subscribe(function () { });
38423         this._imageLoadingService = imageLoadingService;
38424         this._firstGraphSubjects$ = [];
38425         this._initializeCacheSubscriptions = [];
38426         this._sequenceSubscriptions = [];
38427         this._spatialSubscriptions = [];
38428     }
38429     Object.defineProperty(GraphService.prototype, "graphMode$", {
38430         /**
38431          * Get graph mode observable.
38432          *
38433          * @description Emits the current graph mode.
38434          *
38435          * @returns {Observable<GraphMode>} Observable
38436          * emitting the current graph mode when it changes.
38437          */
38438         get: function () {
38439             return this._graphMode$;
38440         },
38441         enumerable: true,
38442         configurable: true
38443     });
38444     /**
38445      * Cache full nodes in a bounding box.
38446      *
38447      * @description When called, the full properties of
38448      * the node are retrieved. The node cache is not initialized
38449      * for any new nodes retrieved and the node assets are not
38450      * retrieved, {@link cacheNode$} needs to be called for caching
38451      * assets.
38452      *
38453      * @param {ILatLon} sw - South west corner of bounding box.
38454      * @param {ILatLon} ne - North east corner of bounding box.
38455      * @return {Observable<Array<Node>>} Observable emitting a single item,
38456      * the nodes of the bounding box, when they have all been retrieved.
38457      * @throws {Error} Propagates any IO node caching errors to the caller.
38458      */
38459     GraphService.prototype.cacheBoundingBox$ = function (sw, ne) {
38460         return this._graph$
38461             .first()
38462             .mergeMap(function (graph) {
38463             return graph.cacheBoundingBox$(sw, ne);
38464         });
38465     };
38466     /**
38467      * Cache a node in the graph and retrieve it.
38468      *
38469      * @description When called, the full properties of
38470      * the node are retrieved and the node cache is initialized.
38471      * After that the node assets are cached and the node
38472      * is emitted to the observable when.
38473      * In parallel to caching the node assets, the sequence and
38474      * spatial edges of the node are cached. For this, the sequence
38475      * of the node and the required tiles and spatial nodes are
38476      * retrieved. The sequence and spatial edges may be set before
38477      * or after the node is returned.
38478      *
38479      * @param {string} key - Key of the node to cache.
38480      * @return {Observable<Node>} Observable emitting a single item,
38481      * the node, when it has been retrieved and its assets are cached.
38482      * @throws {Error} Propagates any IO node caching errors to the caller.
38483      */
38484     GraphService.prototype.cacheNode$ = function (key) {
38485         var _this = this;
38486         var firstGraphSubject$ = new Subject_1.Subject();
38487         this._firstGraphSubjects$.push(firstGraphSubject$);
38488         var firstGraph$ = firstGraphSubject$
38489             .publishReplay(1)
38490             .refCount();
38491         var node$ = firstGraph$
38492             .map(function (graph) {
38493             return graph.getNode(key);
38494         })
38495             .mergeMap(function (node) {
38496             return node.assetsCached ?
38497                 Observable_1.Observable.of(node) :
38498                 node.cacheAssets$();
38499         })
38500             .publishReplay(1)
38501             .refCount();
38502         node$.subscribe(function (node) {
38503             _this._imageLoadingService.loadnode$.next(node);
38504         }, function (error) {
38505             console.error("Failed to cache node (" + key + ")", error);
38506         });
38507         var initializeCacheSubscription = this._graph$
38508             .first()
38509             .mergeMap(function (graph) {
38510             if (graph.isCachingFull(key) || !graph.hasNode(key)) {
38511                 return graph.cacheFull$(key);
38512             }
38513             if (graph.isCachingFill(key) || !graph.getNode(key).full) {
38514                 return graph.cacheFill$(key);
38515             }
38516             return Observable_1.Observable.of(graph);
38517         })
38518             .do(function (graph) {
38519             if (!graph.hasInitializedCache(key)) {
38520                 graph.initializeCache(key);
38521             }
38522         })
38523             .finally(function () {
38524             if (initializeCacheSubscription == null) {
38525                 return;
38526             }
38527             _this._removeFromArray(initializeCacheSubscription, _this._initializeCacheSubscriptions);
38528             _this._removeFromArray(firstGraphSubject$, _this._firstGraphSubjects$);
38529         })
38530             .subscribe(function (graph) {
38531             firstGraphSubject$.next(graph);
38532             firstGraphSubject$.complete();
38533         }, function (error) {
38534             firstGraphSubject$.error(error);
38535         });
38536         if (!initializeCacheSubscription.closed) {
38537             this._initializeCacheSubscriptions.push(initializeCacheSubscription);
38538         }
38539         var graphSequence$ = firstGraph$
38540             .mergeMap(function (graph) {
38541             if (graph.isCachingNodeSequence(key) || !graph.hasNodeSequence(key)) {
38542                 return graph.cacheNodeSequence$(key);
38543             }
38544             return Observable_1.Observable.of(graph);
38545         })
38546             .publishReplay(1)
38547             .refCount();
38548         var sequenceSubscription = graphSequence$
38549             .do(function (graph) {
38550             if (!graph.getNode(key).sequenceEdges.cached) {
38551                 graph.cacheSequenceEdges(key);
38552             }
38553         })
38554             .finally(function () {
38555             if (sequenceSubscription == null) {
38556                 return;
38557             }
38558             _this._removeFromArray(sequenceSubscription, _this._sequenceSubscriptions);
38559         })
38560             .subscribe(function (graph) { return; }, function (error) {
38561             console.error("Failed to cache sequence edges (" + key + ").", error);
38562         });
38563         if (!sequenceSubscription.closed) {
38564             this._sequenceSubscriptions.push(sequenceSubscription);
38565         }
38566         if (this._graphMode === Graph_1.GraphMode.Spatial) {
38567             var spatialSubscription_1 = firstGraph$
38568                 .expand(function (graph) {
38569                 if (graph.hasTiles(key)) {
38570                     return Observable_1.Observable.empty();
38571                 }
38572                 return Observable_1.Observable
38573                     .from(graph.cacheTiles$(key))
38574                     .mergeMap(function (graph$) {
38575                     return graph$
38576                         .mergeMap(function (g) {
38577                         if (g.isCachingTiles(key)) {
38578                             return Observable_1.Observable.empty();
38579                         }
38580                         return Observable_1.Observable.of(g);
38581                     })
38582                         .catch(function (error, caught$) {
38583                         console.error("Failed to cache tile data (" + key + ").", error);
38584                         return Observable_1.Observable.empty();
38585                     });
38586                 });
38587             })
38588                 .last()
38589                 .mergeMap(function (graph) {
38590                 if (graph.hasSpatialArea(key)) {
38591                     return Observable_1.Observable.of(graph);
38592                 }
38593                 return Observable_1.Observable
38594                     .from(graph.cacheSpatialArea$(key))
38595                     .mergeMap(function (graph$) {
38596                     return graph$
38597                         .catch(function (error, caught$) {
38598                         console.error("Failed to cache spatial nodes (" + key + ").", error);
38599                         return Observable_1.Observable.empty();
38600                     });
38601                 });
38602             })
38603                 .last()
38604                 .mergeMap(function (graph) {
38605                 return graph.hasNodeSequence(key) ?
38606                     Observable_1.Observable.of(graph) :
38607                     graph.cacheNodeSequence$(key);
38608             })
38609                 .do(function (graph) {
38610                 if (!graph.getNode(key).spatialEdges.cached) {
38611                     graph.cacheSpatialEdges(key);
38612                 }
38613             })
38614                 .finally(function () {
38615                 if (spatialSubscription_1 == null) {
38616                     return;
38617                 }
38618                 _this._removeFromArray(spatialSubscription_1, _this._spatialSubscriptions);
38619             })
38620                 .subscribe(function (graph) { return; }, function (error) {
38621                 console.error("Failed to cache spatial edges (" + key + ").", error);
38622             });
38623             if (!spatialSubscription_1.closed) {
38624                 this._spatialSubscriptions.push(spatialSubscription_1);
38625             }
38626         }
38627         return node$
38628             .first(function (node) {
38629             return node.assetsCached;
38630         });
38631     };
38632     /**
38633      * Cache a sequence in the graph and retrieve it.
38634      *
38635      * @param {string} sequenceKey - Sequence key.
38636      * @returns {Observable<Sequence>} Observable emitting a single item,
38637      * the sequence, when it has been retrieved and its assets are cached.
38638      * @throws {Error} Propagates any IO node caching errors to the caller.
38639      */
38640     GraphService.prototype.cacheSequence$ = function (sequenceKey) {
38641         return this._graph$
38642             .first()
38643             .mergeMap(function (graph) {
38644             if (graph.isCachingSequence(sequenceKey) || !graph.hasSequence(sequenceKey)) {
38645                 return graph.cacheSequence$(sequenceKey);
38646             }
38647             return Observable_1.Observable.of(graph);
38648         })
38649             .map(function (graph) {
38650             return graph.getSequence(sequenceKey);
38651         });
38652     };
38653     /**
38654      * Cache a sequence and its nodes in the graph and retrieve the sequence.
38655      *
38656      * @description Caches a sequence and its assets are cached and
38657      * retrieves all nodes belonging to the sequence. The node assets
38658      * or edges will not be cached.
38659      *
38660      * @param {string} sequenceKey - Sequence key.
38661      * @param {string} referenceNodeKey - Key of node to use as reference
38662      * for optimized caching.
38663      * @returns {Observable<Sequence>} Observable emitting a single item,
38664      * the sequence, when it has been retrieved, its assets are cached and
38665      * all nodes belonging to the sequence has been retrieved.
38666      * @throws {Error} Propagates any IO node caching errors to the caller.
38667      */
38668     GraphService.prototype.cacheSequenceNodes$ = function (sequenceKey, referenceNodeKey) {
38669         return this._graph$
38670             .first()
38671             .mergeMap(function (graph) {
38672             if (graph.isCachingSequence(sequenceKey) || !graph.hasSequence(sequenceKey)) {
38673                 return graph.cacheSequence$(sequenceKey);
38674             }
38675             return Observable_1.Observable.of(graph);
38676         })
38677             .mergeMap(function (graph) {
38678             if (graph.isCachingSequenceNodes(sequenceKey) || !graph.hasSequenceNodes(sequenceKey)) {
38679                 return graph.cacheSequenceNodes$(sequenceKey, referenceNodeKey);
38680             }
38681             return Observable_1.Observable.of(graph);
38682         })
38683             .map(function (graph) {
38684             return graph.getSequence(sequenceKey);
38685         });
38686     };
38687     /**
38688      * Set a spatial edge filter on the graph.
38689      *
38690      * @description Resets the spatial edges of all cached nodes.
38691      *
38692      * @param {FilterExpression} filter - Filter expression to be applied.
38693      * @return {Observable<Graph>} Observable emitting a single item,
38694      * the graph, when the spatial edges have been reset.
38695      */
38696     GraphService.prototype.setFilter$ = function (filter) {
38697         this._resetSubscriptions(this._spatialSubscriptions);
38698         return this._graph$
38699             .first()
38700             .do(function (graph) {
38701             graph.resetSpatialEdges();
38702             graph.setFilter(filter);
38703         })
38704             .map(function (graph) {
38705             return undefined;
38706         });
38707     };
38708     /**
38709      * Set the graph mode.
38710      *
38711      * @description If graph mode is set to spatial, caching
38712      * is performed with emphasis on spatial edges. If graph
38713      * mode is set to sequence no tile data is requested and
38714      * no spatial edges are computed.
38715      *
38716      * When setting graph mode to sequence all spatial
38717      * subscriptions are aborted.
38718      *
38719      * @param {GraphMode} mode - Graph mode to set.
38720      */
38721     GraphService.prototype.setGraphMode = function (mode) {
38722         if (this._graphMode === mode) {
38723             return;
38724         }
38725         if (mode === Graph_1.GraphMode.Sequence) {
38726             this._resetSubscriptions(this._spatialSubscriptions);
38727         }
38728         this._graphMode = mode;
38729         this._graphModeSubject$.next(this._graphMode);
38730     };
38731     /**
38732      * Reset the graph.
38733      *
38734      * @description Resets the graph but keeps the nodes of the
38735      * supplied keys.
38736      *
38737      * @param {Array<string>} keepKeys - Keys of nodes to keep in graph.
38738      * @return {Observable<Node>} Observable emitting a single item,
38739      * the graph, when it has been reset.
38740      */
38741     GraphService.prototype.reset$ = function (keepKeys) {
38742         this._abortSubjects(this._firstGraphSubjects$);
38743         this._resetSubscriptions(this._initializeCacheSubscriptions);
38744         this._resetSubscriptions(this._sequenceSubscriptions);
38745         this._resetSubscriptions(this._spatialSubscriptions);
38746         return this._graph$
38747             .first()
38748             .do(function (graph) {
38749             graph.reset(keepKeys);
38750         })
38751             .map(function (graph) {
38752             return undefined;
38753         });
38754     };
38755     /**
38756      * Uncache the graph.
38757      *
38758      * @description Uncaches the graph by removing tiles, nodes and
38759      * sequences. Keeps the nodes of the supplied keys and the tiles
38760      * related to those nodes.
38761      *
38762      * @param {Array<string>} keepKeys - Keys of nodes to keep in graph.
38763      * @param {string} keepSequenceKey - Optional key of sequence
38764      * for which the belonging nodes should not be disposed or
38765      * removed from the graph. These nodes may still be uncached if
38766      * not specified in keep keys param.
38767      * @return {Observable<Graph>} Observable emitting a single item,
38768      * the graph, when the graph has been uncached.
38769      */
38770     GraphService.prototype.uncache$ = function (keepKeys, keepSequenceKey) {
38771         return this._graph$
38772             .first()
38773             .do(function (graph) {
38774             graph.uncache(keepKeys, keepSequenceKey);
38775         })
38776             .map(function (graph) {
38777             return undefined;
38778         });
38779     };
38780     GraphService.prototype._abortSubjects = function (subjects) {
38781         for (var _i = 0, _a = subjects.slice(); _i < _a.length; _i++) {
38782             var subject = _a[_i];
38783             this._removeFromArray(subject, subjects);
38784             subject.error(new Error("Cache node request was aborted."));
38785         }
38786     };
38787     GraphService.prototype._removeFromArray = function (object, objects) {
38788         var index = objects.indexOf(object);
38789         if (index !== -1) {
38790             objects.splice(index, 1);
38791         }
38792     };
38793     GraphService.prototype._resetSubscriptions = function (subscriptions) {
38794         for (var _i = 0, _a = subscriptions.slice(); _i < _a.length; _i++) {
38795             var subscription = _a[_i];
38796             this._removeFromArray(subscription, subscriptions);
38797             if (!subscription.closed) {
38798                 subscription.unsubscribe();
38799             }
38800         }
38801     };
38802     return GraphService;
38803 }());
38804 exports.GraphService = GraphService;
38805 exports.default = GraphService;
38806
38807 },{"../Graph":295,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/operator/catch":54,"rxjs/add/operator/concat":56,"rxjs/add/operator/do":61,"rxjs/add/operator/expand":62,"rxjs/add/operator/finally":64,"rxjs/add/operator/first":65,"rxjs/add/operator/last":66,"rxjs/add/operator/map":67,"rxjs/add/operator/mergeMap":70,"rxjs/add/operator/publishReplay":74}],397:[function(require,module,exports){
38808 "use strict";
38809 /// <reference path="../../typings/index.d.ts" />
38810 Object.defineProperty(exports, "__esModule", { value: true });
38811 var Subject_1 = require("rxjs/Subject");
38812 var ImageLoadingService = /** @class */ (function () {
38813     function ImageLoadingService() {
38814         this._loadnode$ = new Subject_1.Subject();
38815         this._loadstatus$ = this._loadnode$
38816             .scan(function (_a, node) {
38817             var nodes = _a[0];
38818             var changed = false;
38819             if (node.loadStatus.total === 0 || node.loadStatus.loaded === node.loadStatus.total) {
38820                 if (node.key in nodes) {
38821                     delete nodes[node.key];
38822                     changed = true;
38823                 }
38824             }
38825             else {
38826                 nodes[node.key] = node.loadStatus;
38827                 changed = true;
38828             }
38829             return [nodes, changed];
38830         }, [{}, false])
38831             .filter(function (_a) {
38832             var nodes = _a[0], changed = _a[1];
38833             return changed;
38834         })
38835             .map(function (_a) {
38836             var nodes = _a[0];
38837             return nodes;
38838         })
38839             .publishReplay(1)
38840             .refCount();
38841         this._loadstatus$.subscribe(function () { });
38842     }
38843     Object.defineProperty(ImageLoadingService.prototype, "loadnode$", {
38844         get: function () {
38845             return this._loadnode$;
38846         },
38847         enumerable: true,
38848         configurable: true
38849     });
38850     Object.defineProperty(ImageLoadingService.prototype, "loadstatus$", {
38851         get: function () {
38852             return this._loadstatus$;
38853         },
38854         enumerable: true,
38855         configurable: true
38856     });
38857     return ImageLoadingService;
38858 }());
38859 exports.ImageLoadingService = ImageLoadingService;
38860
38861 },{"rxjs/Subject":34}],398:[function(require,module,exports){
38862 "use strict";
38863 /// <reference path="../../typings/index.d.ts" />
38864 Object.defineProperty(exports, "__esModule", { value: true });
38865 var Pbf = require("pbf");
38866 var MeshReader = /** @class */ (function () {
38867     function MeshReader() {
38868     }
38869     MeshReader.read = function (buffer) {
38870         var pbf = new Pbf(buffer);
38871         return pbf.readFields(MeshReader._readMeshField, { faces: [], vertices: [] });
38872     };
38873     MeshReader._readMeshField = function (tag, mesh, pbf) {
38874         if (tag === 1) {
38875             mesh.vertices.push(pbf.readFloat());
38876         }
38877         else if (tag === 2) {
38878             mesh.faces.push(pbf.readVarint());
38879         }
38880     };
38881     return MeshReader;
38882 }());
38883 exports.MeshReader = MeshReader;
38884
38885 },{"pbf":23}],399:[function(require,module,exports){
38886 "use strict";
38887 Object.defineProperty(exports, "__esModule", { value: true });
38888 require("rxjs/add/observable/combineLatest");
38889 require("rxjs/add/operator/map");
38890 /**
38891  * @class Node
38892  *
38893  * @classdesc Represents a node in the navigation graph.
38894  *
38895  * Explanation of position and bearing properties:
38896  *
38897  * When images are uploaded they will have GPS information in the EXIF, this is what
38898  * is called `originalLatLon` {@link Node.originalLatLon}.
38899  *
38900  * When Structure from Motions has been run for a node a `computedLatLon` that
38901  * differs from the `originalLatLon` will be created. It is different because
38902  * GPS positions are not very exact and SfM aligns the camera positions according
38903  * to the 3D reconstruction {@link Node.computedLatLon}.
38904  *
38905  * At last there exist a `latLon` property which evaluates to
38906  * the `computedLatLon` from SfM if it exists but falls back
38907  * to the `originalLatLon` from the EXIF GPS otherwise {@link Node.latlon}.
38908  *
38909  * Everything that is done in in the Viewer is based on the SfM positions,
38910  * i.e. `computedLatLon`. That is why the smooth transitions go in the right
38911  * direction (nd not in strange directions because of bad GPS).
38912  *
38913  * E.g. when placing a marker in the Viewer it is relative to the SfM
38914  * position i.e. the `computedLatLon`.
38915  *
38916  * The same concept as above also applies to the compass angle (or bearing) properties
38917  * `originalCa`, `computedCa` and `ca`.
38918  */
38919 var Node = /** @class */ (function () {
38920     /**
38921      * Create a new node instance.
38922      *
38923      * @description Nodes are always created internally by the library.
38924      * Nodes can not be added to the library through any API method.
38925      *
38926      * @param {ICoreNode} coreNode - Raw core node data.
38927      */
38928     function Node(core) {
38929         this._cache = null;
38930         this._core = core;
38931         this._fill = null;
38932     }
38933     Object.defineProperty(Node.prototype, "assetsCached", {
38934         /**
38935          * Get assets cached.
38936          *
38937          * @description The assets that need to be cached for this property
38938          * to report true are the following: fill properties, image and mesh.
38939          * The library ensures that the current node will always have the
38940          * assets cached.
38941          *
38942          * @returns {boolean} Value indicating whether all assets have been
38943          * cached.
38944          */
38945         get: function () {
38946             return this._core != null &&
38947                 this._fill != null &&
38948                 this._cache != null &&
38949                 this._cache.image != null &&
38950                 this._cache.mesh != null;
38951         },
38952         enumerable: true,
38953         configurable: true
38954     });
38955     Object.defineProperty(Node.prototype, "alt", {
38956         /**
38957          * Get alt.
38958          *
38959          * @description If SfM has not been run the computed altitude is
38960          * set to a default value of two meters.
38961          *
38962          * @returns {number} Altitude, in meters.
38963          */
38964         get: function () {
38965             return this._fill.calt;
38966         },
38967         enumerable: true,
38968         configurable: true
38969     });
38970     Object.defineProperty(Node.prototype, "ca", {
38971         /**
38972          * Get ca.
38973          *
38974          * @description If the SfM computed compass angle exists it will
38975          * be returned, otherwise the original EXIF compass angle.
38976          *
38977          * @returns {number} Compass angle, measured in degrees.
38978          */
38979         get: function () {
38980             return this._fill.cca != null ? this._fill.cca : this._fill.ca;
38981         },
38982         enumerable: true,
38983         configurable: true
38984     });
38985     Object.defineProperty(Node.prototype, "capturedAt", {
38986         /**
38987          * Get capturedAt.
38988          *
38989          * @returns {number} Timestamp when the image was captured.
38990          */
38991         get: function () {
38992             return this._fill.captured_at;
38993         },
38994         enumerable: true,
38995         configurable: true
38996     });
38997     Object.defineProperty(Node.prototype, "cameraUuid", {
38998         /**
38999          * Get camera uuid.
39000          *
39001          * @description Will be undefined if the camera uuid was not
39002          * recorded in the image exif information.
39003          *
39004          * @returns {string} Universally unique id for camera used
39005          * when capturing image.
39006          */
39007         get: function () {
39008             return this._fill.captured_with_camera_uuid;
39009         },
39010         enumerable: true,
39011         configurable: true
39012     });
39013     Object.defineProperty(Node.prototype, "computedCA", {
39014         /**
39015          * Get computedCA.
39016          *
39017          * @description Will not be set if SfM has not been run.
39018          *
39019          * @returns {number} SfM computed compass angle, measured in degrees.
39020          */
39021         get: function () {
39022             return this._fill.cca;
39023         },
39024         enumerable: true,
39025         configurable: true
39026     });
39027     Object.defineProperty(Node.prototype, "computedLatLon", {
39028         /**
39029          * Get computedLatLon.
39030          *
39031          * @description Will not be set if SfM has not been run.
39032          *
39033          * @returns {ILatLon} SfM computed latitude longitude in WGS84 datum,
39034          * measured in degrees.
39035          */
39036         get: function () {
39037             return this._core.cl;
39038         },
39039         enumerable: true,
39040         configurable: true
39041     });
39042     Object.defineProperty(Node.prototype, "focal", {
39043         /**
39044          * Get focal.
39045          *
39046          * @description Will not be set if SfM has not been run.
39047          *
39048          * @returns {number} SfM computed focal length.
39049          */
39050         get: function () {
39051             return this._fill.cfocal;
39052         },
39053         enumerable: true,
39054         configurable: true
39055     });
39056     Object.defineProperty(Node.prototype, "full", {
39057         /**
39058          * Get full.
39059          *
39060          * @description The library ensures that the current node will
39061          * always be full.
39062          *
39063          * @returns {boolean} Value indicating whether the node has all
39064          * properties filled.
39065          */
39066         get: function () {
39067             return this._fill != null;
39068         },
39069         enumerable: true,
39070         configurable: true
39071     });
39072     Object.defineProperty(Node.prototype, "fullPano", {
39073         /**
39074          * Get fullPano.
39075          *
39076          * @returns {boolean} Value indicating whether the node is a complete
39077          * 360 panorama.
39078          */
39079         get: function () {
39080             return this._fill.gpano != null &&
39081                 this._fill.gpano.CroppedAreaLeftPixels === 0 &&
39082                 this._fill.gpano.CroppedAreaTopPixels === 0 &&
39083                 this._fill.gpano.CroppedAreaImageWidthPixels === this._fill.gpano.FullPanoWidthPixels &&
39084                 this._fill.gpano.CroppedAreaImageHeightPixels === this._fill.gpano.FullPanoHeightPixels;
39085         },
39086         enumerable: true,
39087         configurable: true
39088     });
39089     Object.defineProperty(Node.prototype, "gpano", {
39090         /**
39091          * Get gpano.
39092          *
39093          * @description Will not be set for non panoramic images.
39094          *
39095          * @returns {IGPano} Panorama information for panorama images.
39096          */
39097         get: function () {
39098             return this._fill.gpano;
39099         },
39100         enumerable: true,
39101         configurable: true
39102     });
39103     Object.defineProperty(Node.prototype, "height", {
39104         /**
39105          * Get height.
39106          *
39107          * @returns {number} Height of original image, not adjusted
39108          * for orientation.
39109          */
39110         get: function () {
39111             return this._fill.height;
39112         },
39113         enumerable: true,
39114         configurable: true
39115     });
39116     Object.defineProperty(Node.prototype, "image", {
39117         /**
39118          * Get image.
39119          *
39120          * @description The image will always be set on the current node.
39121          *
39122          * @returns {HTMLImageElement} Cached image element of the node.
39123          */
39124         get: function () {
39125             return this._cache.image;
39126         },
39127         enumerable: true,
39128         configurable: true
39129     });
39130     Object.defineProperty(Node.prototype, "key", {
39131         /**
39132          * Get key.
39133          *
39134          * @returns {string} Unique key of the node.
39135          */
39136         get: function () {
39137             return this._core.key;
39138         },
39139         enumerable: true,
39140         configurable: true
39141     });
39142     Object.defineProperty(Node.prototype, "latLon", {
39143         /**
39144          * Get latLon.
39145          *
39146          * @description If the SfM computed latitude longitude exist
39147          * it will be returned, otherwise the original EXIF latitude
39148          * longitude.
39149          *
39150          * @returns {ILatLon} Latitude longitude in WGS84 datum,
39151          * measured in degrees.
39152          */
39153         get: function () {
39154             return this._core.cl != null ? this._core.cl : this._core.l;
39155         },
39156         enumerable: true,
39157         configurable: true
39158     });
39159     Object.defineProperty(Node.prototype, "loadStatus", {
39160         /**
39161          * Get loadStatus.
39162          *
39163          * @returns {ILoadStatus} Value indicating the load status
39164          * of the mesh and image.
39165          */
39166         get: function () {
39167             return this._cache.loadStatus;
39168         },
39169         enumerable: true,
39170         configurable: true
39171     });
39172     Object.defineProperty(Node.prototype, "merged", {
39173         /**
39174          * Get merged.
39175          *
39176          * @returns {boolean} Value indicating whether SfM has been
39177          * run on the node and the node has been merged into a
39178          * connected component.
39179          */
39180         get: function () {
39181             return this._fill != null &&
39182                 this._fill.merge_version != null &&
39183                 this._fill.merge_version > 0;
39184         },
39185         enumerable: true,
39186         configurable: true
39187     });
39188     Object.defineProperty(Node.prototype, "mergeCC", {
39189         /**
39190          * Get mergeCC.
39191          *
39192          * @description Will not be set if SfM has not yet been run on
39193          * node.
39194          *
39195          * @returns {number} SfM connected component key to which
39196          * image belongs.
39197          */
39198         get: function () {
39199             return this._fill.merge_cc;
39200         },
39201         enumerable: true,
39202         configurable: true
39203     });
39204     Object.defineProperty(Node.prototype, "mergeVersion", {
39205         /**
39206          * Get mergeVersion.
39207          *
39208          * @returns {number} Version for which SfM was run and image was merged.
39209          */
39210         get: function () {
39211             return this._fill.merge_version;
39212         },
39213         enumerable: true,
39214         configurable: true
39215     });
39216     Object.defineProperty(Node.prototype, "mesh", {
39217         /**
39218          * Get mesh.
39219          *
39220          * @description The mesh will always be set on the current node.
39221          *
39222          * @returns {IMesh} SfM triangulated mesh of reconstructed
39223          * atomic 3D points.
39224          */
39225         get: function () {
39226             return this._cache.mesh;
39227         },
39228         enumerable: true,
39229         configurable: true
39230     });
39231     Object.defineProperty(Node.prototype, "organizationKey", {
39232         /**
39233          * Get organizationKey.
39234          *
39235          * @returns {string} Unique key of the organization to which
39236          * the node belongs. If the node does not belong to an
39237          * organization the organization key will be undefined.
39238          */
39239         get: function () {
39240             return this._fill.organization_key;
39241         },
39242         enumerable: true,
39243         configurable: true
39244     });
39245     Object.defineProperty(Node.prototype, "orientation", {
39246         /**
39247          * Get orientation.
39248          *
39249          * @returns {number} EXIF orientation of original image.
39250          */
39251         get: function () {
39252             return this._fill.orientation;
39253         },
39254         enumerable: true,
39255         configurable: true
39256     });
39257     Object.defineProperty(Node.prototype, "originalCA", {
39258         /**
39259          * Get originalCA.
39260          *
39261          * @returns {number} Original EXIF compass angle, measured in
39262          * degrees.
39263          */
39264         get: function () {
39265             return this._fill.ca;
39266         },
39267         enumerable: true,
39268         configurable: true
39269     });
39270     Object.defineProperty(Node.prototype, "originalLatLon", {
39271         /**
39272          * Get originalLatLon.
39273          *
39274          * @returns {ILatLon} Original EXIF latitude longitude in
39275          * WGS84 datum, measured in degrees.
39276          */
39277         get: function () {
39278             return this._core.l;
39279         },
39280         enumerable: true,
39281         configurable: true
39282     });
39283     Object.defineProperty(Node.prototype, "pano", {
39284         /**
39285          * Get pano.
39286          *
39287          * @returns {boolean} Value indicating whether the node is a panorama.
39288          * It could be a cropped or full panorama.
39289          */
39290         get: function () {
39291             return this._fill.gpano != null &&
39292                 this._fill.gpano.FullPanoWidthPixels != null;
39293         },
39294         enumerable: true,
39295         configurable: true
39296     });
39297     Object.defineProperty(Node.prototype, "private", {
39298         /**
39299          * Get private.
39300          *
39301          * @returns {boolean} Value specifying if image is accessible to
39302          * organization members only or to everyone.
39303          */
39304         get: function () {
39305             return this._fill.private;
39306         },
39307         enumerable: true,
39308         configurable: true
39309     });
39310     Object.defineProperty(Node.prototype, "projectKey", {
39311         /**
39312          * Get projectKey.
39313          *
39314          * @returns {string} Unique key of the project to which
39315          * the node belongs. If the node does not belong to a
39316          * project the project key will be undefined.
39317          *
39318          * @deprecated This property will be deprecated in favor
39319          * of the organization key and private properties.
39320          */
39321         get: function () {
39322             return this._fill.project != null ?
39323                 this._fill.project.key :
39324                 null;
39325         },
39326         enumerable: true,
39327         configurable: true
39328     });
39329     Object.defineProperty(Node.prototype, "rotation", {
39330         /**
39331          * Get rotation.
39332          *
39333          * @description Will not be set if SfM has not been run.
39334          *
39335          * @returns {Array<number>} Rotation vector in angle axis representation.
39336          */
39337         get: function () {
39338             return this._fill.c_rotation;
39339         },
39340         enumerable: true,
39341         configurable: true
39342     });
39343     Object.defineProperty(Node.prototype, "scale", {
39344         /**
39345          * Get scale.
39346          *
39347          * @description Will not be set if SfM has not been run.
39348          *
39349          * @returns {number} Scale of atomic reconstruction.
39350          */
39351         get: function () {
39352             return this._fill.atomic_scale;
39353         },
39354         enumerable: true,
39355         configurable: true
39356     });
39357     Object.defineProperty(Node.prototype, "sequenceKey", {
39358         /**
39359          * Get sequenceKey.
39360          *
39361          * @returns {string} Unique key of the sequence to which
39362          * the node belongs.
39363          */
39364         get: function () {
39365             return this._core.sequence_key;
39366         },
39367         enumerable: true,
39368         configurable: true
39369     });
39370     Object.defineProperty(Node.prototype, "sequenceEdges", {
39371         /**
39372          * Get sequenceEdges.
39373          *
39374          * @returns {IEdgeStatus} Value describing the status of the
39375          * sequence edges.
39376          */
39377         get: function () {
39378             return this._cache.sequenceEdges;
39379         },
39380         enumerable: true,
39381         configurable: true
39382     });
39383     Object.defineProperty(Node.prototype, "sequenceEdges$", {
39384         /**
39385          * Get sequenceEdges$.
39386          *
39387          * @returns {Observable<IEdgeStatus>} Observable emitting
39388          * values describing the status of the sequence edges.
39389          */
39390         get: function () {
39391             return this._cache.sequenceEdges$;
39392         },
39393         enumerable: true,
39394         configurable: true
39395     });
39396     Object.defineProperty(Node.prototype, "spatialEdges", {
39397         /**
39398          * Get spatialEdges.
39399          *
39400          * @returns {IEdgeStatus} Value describing the status of the
39401          * spatial edges.
39402          */
39403         get: function () {
39404             return this._cache.spatialEdges;
39405         },
39406         enumerable: true,
39407         configurable: true
39408     });
39409     Object.defineProperty(Node.prototype, "spatialEdges$", {
39410         /**
39411          * Get spatialEdges$.
39412          *
39413          * @returns {Observable<IEdgeStatus>} Observable emitting
39414          * values describing the status of the spatial edges.
39415          */
39416         get: function () {
39417             return this._cache.spatialEdges$;
39418         },
39419         enumerable: true,
39420         configurable: true
39421     });
39422     Object.defineProperty(Node.prototype, "userKey", {
39423         /**
39424          * Get userKey.
39425          *
39426          * @returns {string} Unique key of the user who uploaded
39427          * the image.
39428          */
39429         get: function () {
39430             return this._fill.user.key;
39431         },
39432         enumerable: true,
39433         configurable: true
39434     });
39435     Object.defineProperty(Node.prototype, "username", {
39436         /**
39437          * Get username.
39438          *
39439          * @returns {string} Username of the user who uploaded
39440          * the image.
39441          */
39442         get: function () {
39443             return this._fill.user.username;
39444         },
39445         enumerable: true,
39446         configurable: true
39447     });
39448     Object.defineProperty(Node.prototype, "width", {
39449         /**
39450          * Get width.
39451          *
39452          * @returns {number} Width of original image, not
39453          * adjusted for orientation.
39454          */
39455         get: function () {
39456             return this._fill.width;
39457         },
39458         enumerable: true,
39459         configurable: true
39460     });
39461     /**
39462      * Cache the image and mesh assets.
39463      *
39464      * @description The assets are always cached internally by the
39465      * library prior to setting a node as the current node.
39466      *
39467      * @returns {Observable<Node>} Observable emitting this node whenever the
39468      * load status has changed and when the mesh or image has been fully loaded.
39469      */
39470     Node.prototype.cacheAssets$ = function () {
39471         var _this = this;
39472         return this._cache.cacheAssets$(this.key, this.pano, this.merged)
39473             .map(function (cache) {
39474             return _this;
39475         });
39476     };
39477     Node.prototype.cacheImage$ = function (imageSize) {
39478         var _this = this;
39479         return this._cache.cacheImage$(this.key, imageSize)
39480             .map(function (cache) {
39481             return _this;
39482         });
39483     };
39484     /**
39485      * Cache the sequence edges.
39486      *
39487      * @description The sequence edges are cached asynchronously
39488      * internally by the library.
39489      *
39490      * @param {Array<IEdge>} edges - Sequence edges to cache.
39491      */
39492     Node.prototype.cacheSequenceEdges = function (edges) {
39493         this._cache.cacheSequenceEdges(edges);
39494     };
39495     /**
39496      * Cache the spatial edges.
39497      *
39498      * @description The spatial edges are cached asynchronously
39499      * internally by the library.
39500      *
39501      * @param {Array<IEdge>} edges - Spatial edges to cache.
39502      */
39503     Node.prototype.cacheSpatialEdges = function (edges) {
39504         this._cache.cacheSpatialEdges(edges);
39505     };
39506     /**
39507      * Dispose the node.
39508      *
39509      * @description Disposes all cached assets.
39510      */
39511     Node.prototype.dispose = function () {
39512         if (this._cache != null) {
39513             this._cache.dispose();
39514             this._cache = null;
39515         }
39516         this._core = null;
39517         this._fill = null;
39518     };
39519     /**
39520      * Initialize the node cache.
39521      *
39522      * @description The node cache is initialized internally by
39523      * the library.
39524      *
39525      * @param {NodeCache} cache - The node cache to set as cache.
39526      */
39527     Node.prototype.initializeCache = function (cache) {
39528         if (this._cache != null) {
39529             throw new Error("Node cache already initialized (" + this.key + ").");
39530         }
39531         this._cache = cache;
39532     };
39533     /**
39534      * Fill the node with all properties.
39535      *
39536      * @description The node is filled internally by
39537      * the library.
39538      *
39539      * @param {IFillNode} fill - The fill node struct.
39540      */
39541     Node.prototype.makeFull = function (fill) {
39542         if (fill == null) {
39543             throw new Error("Fill can not be null.");
39544         }
39545         this._fill = fill;
39546     };
39547     /**
39548      * Reset the sequence edges.
39549      */
39550     Node.prototype.resetSequenceEdges = function () {
39551         this._cache.resetSequenceEdges();
39552     };
39553     /**
39554      * Reset the spatial edges.
39555      */
39556     Node.prototype.resetSpatialEdges = function () {
39557         this._cache.resetSpatialEdges();
39558     };
39559     /**
39560      * Clears the image and mesh assets, aborts
39561      * any outstanding requests and resets edges.
39562      */
39563     Node.prototype.uncache = function () {
39564         if (this._cache == null) {
39565             return;
39566         }
39567         this._cache.dispose();
39568         this._cache = null;
39569     };
39570     return Node;
39571 }());
39572 exports.Node = Node;
39573 exports.default = Node;
39574
39575 },{"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/map":67}],400:[function(require,module,exports){
39576 (function (Buffer){
39577 "use strict";
39578 Object.defineProperty(exports, "__esModule", { value: true });
39579 var Subject_1 = require("rxjs/Subject");
39580 var Observable_1 = require("rxjs/Observable");
39581 require("rxjs/add/observable/combineLatest");
39582 require("rxjs/add/operator/publishReplay");
39583 var Graph_1 = require("../Graph");
39584 var Utils_1 = require("../Utils");
39585 /**
39586  * @class NodeCache
39587  *
39588  * @classdesc Represents the cached properties of a node.
39589  */
39590 var NodeCache = /** @class */ (function () {
39591     /**
39592      * Create a new node cache instance.
39593      */
39594     function NodeCache() {
39595         this._disposed = false;
39596         this._image = null;
39597         this._loadStatus = { loaded: 0, total: 0 };
39598         this._mesh = null;
39599         this._sequenceEdges = { cached: false, edges: [] };
39600         this._spatialEdges = { cached: false, edges: [] };
39601         this._sequenceEdgesChanged$ = new Subject_1.Subject();
39602         this._sequenceEdges$ = this._sequenceEdgesChanged$
39603             .startWith(this._sequenceEdges)
39604             .publishReplay(1)
39605             .refCount();
39606         this._sequenceEdgesSubscription = this._sequenceEdges$.subscribe(function () { });
39607         this._spatialEdgesChanged$ = new Subject_1.Subject();
39608         this._spatialEdges$ = this._spatialEdgesChanged$
39609             .startWith(this._spatialEdges)
39610             .publishReplay(1)
39611             .refCount();
39612         this._spatialEdgesSubscription = this._spatialEdges$.subscribe(function () { });
39613         this._cachingAssets$ = null;
39614     }
39615     Object.defineProperty(NodeCache.prototype, "image", {
39616         /**
39617          * Get image.
39618          *
39619          * @description Will not be set when assets have not been cached
39620          * or when the object has been disposed.
39621          *
39622          * @returns {HTMLImageElement} Cached image element of the node.
39623          */
39624         get: function () {
39625             return this._image;
39626         },
39627         enumerable: true,
39628         configurable: true
39629     });
39630     Object.defineProperty(NodeCache.prototype, "loadStatus", {
39631         /**
39632          * Get loadStatus.
39633          *
39634          * @returns {ILoadStatus} Value indicating the load status
39635          * of the mesh and image.
39636          */
39637         get: function () {
39638             return this._loadStatus;
39639         },
39640         enumerable: true,
39641         configurable: true
39642     });
39643     Object.defineProperty(NodeCache.prototype, "mesh", {
39644         /**
39645          * Get mesh.
39646          *
39647          * @description Will not be set when assets have not been cached
39648          * or when the object has been disposed.
39649          *
39650          * @returns {IMesh} SfM triangulated mesh of reconstructed
39651          * atomic 3D points.
39652          */
39653         get: function () {
39654             return this._mesh;
39655         },
39656         enumerable: true,
39657         configurable: true
39658     });
39659     Object.defineProperty(NodeCache.prototype, "sequenceEdges", {
39660         /**
39661          * Get sequenceEdges.
39662          *
39663          * @returns {IEdgeStatus} Value describing the status of the
39664          * sequence edges.
39665          */
39666         get: function () {
39667             return this._sequenceEdges;
39668         },
39669         enumerable: true,
39670         configurable: true
39671     });
39672     Object.defineProperty(NodeCache.prototype, "sequenceEdges$", {
39673         /**
39674          * Get sequenceEdges$.
39675          *
39676          * @returns {Observable<IEdgeStatus>} Observable emitting
39677          * values describing the status of the sequence edges.
39678          */
39679         get: function () {
39680             return this._sequenceEdges$;
39681         },
39682         enumerable: true,
39683         configurable: true
39684     });
39685     Object.defineProperty(NodeCache.prototype, "spatialEdges", {
39686         /**
39687          * Get spatialEdges.
39688          *
39689          * @returns {IEdgeStatus} Value describing the status of the
39690          * spatial edges.
39691          */
39692         get: function () {
39693             return this._spatialEdges;
39694         },
39695         enumerable: true,
39696         configurable: true
39697     });
39698     Object.defineProperty(NodeCache.prototype, "spatialEdges$", {
39699         /**
39700          * Get spatialEdges$.
39701          *
39702          * @returns {Observable<IEdgeStatus>} Observable emitting
39703          * values describing the status of the spatial edges.
39704          */
39705         get: function () {
39706             return this._spatialEdges$;
39707         },
39708         enumerable: true,
39709         configurable: true
39710     });
39711     /**
39712      * Cache the image and mesh assets.
39713      *
39714      * @param {string} key - Key of the node to cache.
39715      * @param {boolean} pano - Value indicating whether node is a panorama.
39716      * @param {boolean} merged - Value indicating whether node is merged.
39717      * @returns {Observable<NodeCache>} Observable emitting this node
39718      * cache whenever the load status has changed and when the mesh or image
39719      * has been fully loaded.
39720      */
39721     NodeCache.prototype.cacheAssets$ = function (key, pano, merged) {
39722         var _this = this;
39723         if (this._cachingAssets$ != null) {
39724             return this._cachingAssets$;
39725         }
39726         var imageSize = pano ?
39727             Utils_1.Settings.basePanoramaSize :
39728             Utils_1.Settings.baseImageSize;
39729         this._cachingAssets$ = Observable_1.Observable
39730             .combineLatest(this._cacheImage$(key, imageSize), this._cacheMesh$(key, merged), function (imageStatus, meshStatus) {
39731             _this._loadStatus.loaded = 0;
39732             _this._loadStatus.total = 0;
39733             if (meshStatus) {
39734                 _this._mesh = meshStatus.object;
39735                 _this._loadStatus.loaded += meshStatus.loaded.loaded;
39736                 _this._loadStatus.total += meshStatus.loaded.total;
39737             }
39738             if (imageStatus) {
39739                 _this._image = imageStatus.object;
39740                 _this._loadStatus.loaded += imageStatus.loaded.loaded;
39741                 _this._loadStatus.total += imageStatus.loaded.total;
39742             }
39743             return _this;
39744         })
39745             .finally(function () {
39746             _this._cachingAssets$ = null;
39747         })
39748             .publishReplay(1)
39749             .refCount();
39750         return this._cachingAssets$;
39751     };
39752     /**
39753      * Cache an image with a higher resolution than the current one.
39754      *
39755      * @param {string} key - Key of the node to cache.
39756      * @param {ImageSize} imageSize - The size to cache.
39757      * @returns {Observable<NodeCache>} Observable emitting a single item,
39758      * the node cache, when the image has been cached. If supplied image
39759      * size is not larger than the current image size the node cache is
39760      * returned immediately.
39761      */
39762     NodeCache.prototype.cacheImage$ = function (key, imageSize) {
39763         var _this = this;
39764         if (this._image != null && imageSize <= Math.max(this._image.width, this._image.height)) {
39765             return Observable_1.Observable.of(this);
39766         }
39767         return this._cacheImage$(key, imageSize)
39768             .first(function (status) {
39769             return status.object != null;
39770         })
39771             .do(function (status) {
39772             _this._disposeImage();
39773             _this._image = status.object;
39774         })
39775             .map(function (imageStatus) {
39776             return _this;
39777         });
39778     };
39779     /**
39780      * Cache the sequence edges.
39781      *
39782      * @param {Array<IEdge>} edges - Sequence edges to cache.
39783      */
39784     NodeCache.prototype.cacheSequenceEdges = function (edges) {
39785         this._sequenceEdges = { cached: true, edges: edges };
39786         this._sequenceEdgesChanged$.next(this._sequenceEdges);
39787     };
39788     /**
39789      * Cache the spatial edges.
39790      *
39791      * @param {Array<IEdge>} edges - Spatial edges to cache.
39792      */
39793     NodeCache.prototype.cacheSpatialEdges = function (edges) {
39794         this._spatialEdges = { cached: true, edges: edges };
39795         this._spatialEdgesChanged$.next(this._spatialEdges);
39796     };
39797     /**
39798      * Dispose the node cache.
39799      *
39800      * @description Disposes all cached assets and unsubscribes to
39801      * all streams.
39802      */
39803     NodeCache.prototype.dispose = function () {
39804         this._sequenceEdgesSubscription.unsubscribe();
39805         this._spatialEdgesSubscription.unsubscribe();
39806         this._disposeImage();
39807         this._mesh = null;
39808         this._loadStatus.loaded = 0;
39809         this._loadStatus.total = 0;
39810         this._sequenceEdges = { cached: false, edges: [] };
39811         this._spatialEdges = { cached: false, edges: [] };
39812         this._sequenceEdgesChanged$.next(this._sequenceEdges);
39813         this._spatialEdgesChanged$.next(this._spatialEdges);
39814         this._disposed = true;
39815         if (this._imageRequest != null) {
39816             this._imageRequest.abort();
39817         }
39818         if (this._meshRequest != null) {
39819             this._meshRequest.abort();
39820         }
39821     };
39822     /**
39823      * Reset the sequence edges.
39824      */
39825     NodeCache.prototype.resetSequenceEdges = function () {
39826         this._sequenceEdges = { cached: false, edges: [] };
39827         this._sequenceEdgesChanged$.next(this._sequenceEdges);
39828     };
39829     /**
39830      * Reset the spatial edges.
39831      */
39832     NodeCache.prototype.resetSpatialEdges = function () {
39833         this._spatialEdges = { cached: false, edges: [] };
39834         this._spatialEdgesChanged$.next(this._spatialEdges);
39835     };
39836     /**
39837      * Cache the image.
39838      *
39839      * @param {string} key - Key of the node to cache.
39840      * @param {boolean} pano - Value indicating whether node is a panorama.
39841      * @returns {Observable<ILoadStatusObject<HTMLImageElement>>} Observable
39842      * emitting a load status object every time the load status changes
39843      * and completes when the image is fully loaded.
39844      */
39845     NodeCache.prototype._cacheImage$ = function (key, imageSize) {
39846         var _this = this;
39847         return Observable_1.Observable.create(function (subscriber) {
39848             var xmlHTTP = new XMLHttpRequest();
39849             xmlHTTP.open("GET", Utils_1.Urls.thumbnail(key, imageSize, Utils_1.Urls.origin), true);
39850             xmlHTTP.responseType = "arraybuffer";
39851             xmlHTTP.timeout = 15000;
39852             xmlHTTP.onload = function (pe) {
39853                 if (xmlHTTP.status !== 200) {
39854                     _this._imageRequest = null;
39855                     subscriber.error(new Error("Failed to fetch image (" + key + "). Status: " + xmlHTTP.status + ", " + xmlHTTP.statusText));
39856                     return;
39857                 }
39858                 var image = new Image();
39859                 image.crossOrigin = "Anonymous";
39860                 image.onload = function (e) {
39861                     _this._imageRequest = null;
39862                     if (_this._disposed) {
39863                         window.URL.revokeObjectURL(image.src);
39864                         subscriber.error(new Error("Image load was aborted (" + key + ")"));
39865                         return;
39866                     }
39867                     subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: image });
39868                     subscriber.complete();
39869                 };
39870                 image.onerror = function (error) {
39871                     _this._imageRequest = null;
39872                     subscriber.error(new Error("Failed to load image (" + key + ")"));
39873                 };
39874                 var blob = new Blob([xmlHTTP.response]);
39875                 image.src = window.URL.createObjectURL(blob);
39876             };
39877             xmlHTTP.onprogress = function (pe) {
39878                 if (_this._disposed) {
39879                     return;
39880                 }
39881                 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: null });
39882             };
39883             xmlHTTP.onerror = function (error) {
39884                 _this._imageRequest = null;
39885                 subscriber.error(new Error("Failed to fetch image (" + key + ")"));
39886             };
39887             xmlHTTP.ontimeout = function (e) {
39888                 _this._imageRequest = null;
39889                 subscriber.error(new Error("Image request timed out (" + key + ")"));
39890             };
39891             xmlHTTP.onabort = function (event) {
39892                 _this._imageRequest = null;
39893                 subscriber.error(new Error("Image request was aborted (" + key + ")"));
39894             };
39895             _this._imageRequest = xmlHTTP;
39896             xmlHTTP.send(null);
39897         });
39898     };
39899     /**
39900      * Cache the mesh.
39901      *
39902      * @param {string} key - Key of the node to cache.
39903      * @param {boolean} merged - Value indicating whether node is merged.
39904      * @returns {Observable<ILoadStatusObject<IMesh>>} Observable emitting
39905      * a load status object every time the load status changes and completes
39906      * when the mesh is fully loaded.
39907      */
39908     NodeCache.prototype._cacheMesh$ = function (key, merged) {
39909         var _this = this;
39910         return Observable_1.Observable.create(function (subscriber) {
39911             if (!merged) {
39912                 subscriber.next(_this._createEmptyMeshLoadStatus());
39913                 subscriber.complete();
39914                 return;
39915             }
39916             var xmlHTTP = new XMLHttpRequest();
39917             xmlHTTP.open("GET", Utils_1.Urls.protoMesh(key), true);
39918             xmlHTTP.responseType = "arraybuffer";
39919             xmlHTTP.timeout = 15000;
39920             xmlHTTP.onload = function (pe) {
39921                 _this._meshRequest = null;
39922                 if (_this._disposed) {
39923                     return;
39924                 }
39925                 var mesh = xmlHTTP.status === 200 ?
39926                     Graph_1.MeshReader.read(new Buffer(xmlHTTP.response)) :
39927                     { faces: [], vertices: [] };
39928                 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: mesh });
39929                 subscriber.complete();
39930             };
39931             xmlHTTP.onprogress = function (pe) {
39932                 if (_this._disposed) {
39933                     return;
39934                 }
39935                 subscriber.next({ loaded: { loaded: pe.loaded, total: pe.total }, object: null });
39936             };
39937             xmlHTTP.onerror = function (e) {
39938                 _this._meshRequest = null;
39939                 console.error("Failed to cache mesh (" + key + ")");
39940                 subscriber.next(_this._createEmptyMeshLoadStatus());
39941                 subscriber.complete();
39942             };
39943             xmlHTTP.ontimeout = function (e) {
39944                 _this._meshRequest = null;
39945                 console.error("Mesh request timed out (" + key + ")");
39946                 subscriber.next(_this._createEmptyMeshLoadStatus());
39947                 subscriber.complete();
39948             };
39949             xmlHTTP.onabort = function (e) {
39950                 _this._meshRequest = null;
39951                 subscriber.error(new Error("Mesh request was aborted (" + key + ")"));
39952             };
39953             _this._meshRequest = xmlHTTP;
39954             xmlHTTP.send(null);
39955         });
39956     };
39957     /**
39958      * Create a load status object with an empty mesh.
39959      *
39960      * @returns {ILoadStatusObject<IMesh>} Load status object
39961      * with empty mesh.
39962      */
39963     NodeCache.prototype._createEmptyMeshLoadStatus = function () {
39964         return {
39965             loaded: { loaded: 0, total: 0 },
39966             object: { faces: [], vertices: [] },
39967         };
39968     };
39969     NodeCache.prototype._disposeImage = function () {
39970         if (this._image != null) {
39971             window.URL.revokeObjectURL(this._image.src);
39972         }
39973         this._image = null;
39974     };
39975     return NodeCache;
39976 }());
39977 exports.NodeCache = NodeCache;
39978 exports.default = NodeCache;
39979
39980 }).call(this,require("buffer").Buffer)
39981
39982 },{"../Graph":295,"../Utils":301,"buffer":7,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/publishReplay":74}],401:[function(require,module,exports){
39983 "use strict";
39984 /// <reference path="../../typings/index.d.ts" />
39985 Object.defineProperty(exports, "__esModule", { value: true });
39986 var _ = require("underscore");
39987 /**
39988  * @class Sequence
39989  *
39990  * @classdesc Represents a sequence of ordered nodes.
39991  */
39992 var Sequence = /** @class */ (function () {
39993     /**
39994      * Create a new sequene instance.
39995      *
39996      * @param {ISequence} sequence - Raw sequence data.
39997      */
39998     function Sequence(sequence) {
39999         this._key = sequence.key;
40000         this._keys = sequence.keys;
40001     }
40002     Object.defineProperty(Sequence.prototype, "key", {
40003         /**
40004          * Get key.
40005          *
40006          * @returns {string} Unique sequence key.
40007          */
40008         get: function () {
40009             return this._key;
40010         },
40011         enumerable: true,
40012         configurable: true
40013     });
40014     Object.defineProperty(Sequence.prototype, "keys", {
40015         /**
40016          * Get keys.
40017          *
40018          * @returns {Array<string>} Array of ordered node keys in the sequence.
40019          */
40020         get: function () {
40021             return this._keys;
40022         },
40023         enumerable: true,
40024         configurable: true
40025     });
40026     /**
40027      * Dispose the sequence.
40028      *
40029      * @description Disposes all cached assets.
40030      */
40031     Sequence.prototype.dispose = function () {
40032         this._key = null;
40033         this._keys = null;
40034     };
40035     /**
40036      * Find the next node key in the sequence with respect to
40037      * the provided node key.
40038      *
40039      * @param {string} key - Reference node key.
40040      * @returns {string} Next key in sequence if it exists, null otherwise.
40041      */
40042     Sequence.prototype.findNextKey = function (key) {
40043         var i = _.indexOf(this._keys, key);
40044         if ((i + 1) >= this._keys.length || i === -1) {
40045             return null;
40046         }
40047         else {
40048             return this._keys[i + 1];
40049         }
40050     };
40051     /**
40052      * Find the previous node key in the sequence with respect to
40053      * the provided node key.
40054      *
40055      * @param {string} key - Reference node key.
40056      * @returns {string} Previous key in sequence if it exists, null otherwise.
40057      */
40058     Sequence.prototype.findPrevKey = function (key) {
40059         var i = _.indexOf(this._keys, key);
40060         if (i === 0 || i === -1) {
40061             return null;
40062         }
40063         else {
40064             return this._keys[i - 1];
40065         }
40066     };
40067     return Sequence;
40068 }());
40069 exports.Sequence = Sequence;
40070 exports.default = Sequence;
40071
40072 },{"underscore":243}],402:[function(require,module,exports){
40073 "use strict";
40074 /// <reference path="../../../typings/index.d.ts" />
40075 Object.defineProperty(exports, "__esModule", { value: true });
40076 var THREE = require("three");
40077 var Edge_1 = require("../../Edge");
40078 var Error_1 = require("../../Error");
40079 var Geo_1 = require("../../Geo");
40080 /**
40081  * @class EdgeCalculator
40082  *
40083  * @classdesc Represents a class for calculating node edges.
40084  */
40085 var EdgeCalculator = /** @class */ (function () {
40086     /**
40087      * Create a new edge calculator instance.
40088      *
40089      * @param {EdgeCalculatorSettings} settings - Settings struct.
40090      * @param {EdgeCalculatorDirections} directions - Directions struct.
40091      * @param {EdgeCalculatorCoefficients} coefficients - Coefficients struct.
40092      */
40093     function EdgeCalculator(settings, directions, coefficients) {
40094         this._spatial = new Geo_1.Spatial();
40095         this._geoCoords = new Geo_1.GeoCoords();
40096         this._settings = settings != null ? settings : new Edge_1.EdgeCalculatorSettings();
40097         this._directions = directions != null ? directions : new Edge_1.EdgeCalculatorDirections();
40098         this._coefficients = coefficients != null ? coefficients : new Edge_1.EdgeCalculatorCoefficients();
40099     }
40100     /**
40101      * Returns the potential edges to destination nodes for a set
40102      * of nodes with respect to a source node.
40103      *
40104      * @param {Node} node - Source node.
40105      * @param {Array<Node>} nodes - Potential destination nodes.
40106      * @param {Array<string>} fallbackKeys - Keys for destination nodes that should
40107      * be returned even if they do not meet the criteria for a potential edge.
40108      * @throws {ArgumentMapillaryError} If node is not full.
40109      */
40110     EdgeCalculator.prototype.getPotentialEdges = function (node, potentialNodes, fallbackKeys) {
40111         if (!node.full) {
40112             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
40113         }
40114         if (!node.merged) {
40115             return [];
40116         }
40117         var currentDirection = this._spatial.viewingDirection(node.rotation);
40118         var currentVerticalDirection = this._spatial.angleToPlane(currentDirection.toArray(), [0, 0, 1]);
40119         var potentialEdges = [];
40120         for (var _i = 0, potentialNodes_1 = potentialNodes; _i < potentialNodes_1.length; _i++) {
40121             var potential = potentialNodes_1[_i];
40122             if (!potential.merged ||
40123                 potential.key === node.key) {
40124                 continue;
40125             }
40126             var enu = this._geoCoords.geodeticToEnu(potential.latLon.lat, potential.latLon.lon, potential.alt, node.latLon.lat, node.latLon.lon, node.alt);
40127             var motion = new THREE.Vector3(enu[0], enu[1], enu[2]);
40128             var distance = motion.length();
40129             if (distance > this._settings.maxDistance &&
40130                 fallbackKeys.indexOf(potential.key) < 0) {
40131                 continue;
40132             }
40133             var motionChange = this._spatial.angleBetweenVector2(currentDirection.x, currentDirection.y, motion.x, motion.y);
40134             var verticalMotion = this._spatial.angleToPlane(motion.toArray(), [0, 0, 1]);
40135             var direction = this._spatial.viewingDirection(potential.rotation);
40136             var directionChange = this._spatial.angleBetweenVector2(currentDirection.x, currentDirection.y, direction.x, direction.y);
40137             var verticalDirection = this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
40138             var verticalDirectionChange = verticalDirection - currentVerticalDirection;
40139             var rotation = this._spatial.relativeRotationAngle(node.rotation, potential.rotation);
40140             var worldMotionAzimuth = this._spatial.angleBetweenVector2(1, 0, motion.x, motion.y);
40141             var sameSequence = potential.sequenceKey != null &&
40142                 node.sequenceKey != null &&
40143                 potential.sequenceKey === node.sequenceKey;
40144             var sameMergeCC = (potential.mergeCC == null && node.mergeCC == null) ||
40145                 potential.mergeCC === node.mergeCC;
40146             var sameUser = potential.userKey === node.userKey;
40147             var potentialEdge = {
40148                 capturedAt: potential.capturedAt,
40149                 croppedPano: potential.pano && !potential.fullPano,
40150                 directionChange: directionChange,
40151                 distance: distance,
40152                 fullPano: potential.fullPano,
40153                 key: potential.key,
40154                 motionChange: motionChange,
40155                 rotation: rotation,
40156                 sameMergeCC: sameMergeCC,
40157                 sameSequence: sameSequence,
40158                 sameUser: sameUser,
40159                 sequenceKey: potential.sequenceKey,
40160                 verticalDirectionChange: verticalDirectionChange,
40161                 verticalMotion: verticalMotion,
40162                 worldMotionAzimuth: worldMotionAzimuth,
40163             };
40164             potentialEdges.push(potentialEdge);
40165         }
40166         return potentialEdges;
40167     };
40168     /**
40169      * Computes the sequence edges for a node.
40170      *
40171      * @param {Node} node - Source node.
40172      * @throws {ArgumentMapillaryError} If node is not full.
40173      */
40174     EdgeCalculator.prototype.computeSequenceEdges = function (node, sequence) {
40175         if (!node.full) {
40176             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
40177         }
40178         if (node.sequenceKey !== sequence.key) {
40179             throw new Error_1.ArgumentMapillaryError("Node and sequence does not correspond.");
40180         }
40181         var edges = [];
40182         var nextKey = sequence.findNextKey(node.key);
40183         if (nextKey != null) {
40184             edges.push({
40185                 data: {
40186                     direction: Edge_1.EdgeDirection.Next,
40187                     worldMotionAzimuth: Number.NaN,
40188                 },
40189                 from: node.key,
40190                 to: nextKey,
40191             });
40192         }
40193         var prevKey = sequence.findPrevKey(node.key);
40194         if (prevKey != null) {
40195             edges.push({
40196                 data: {
40197                     direction: Edge_1.EdgeDirection.Prev,
40198                     worldMotionAzimuth: Number.NaN,
40199                 },
40200                 from: node.key,
40201                 to: prevKey,
40202             });
40203         }
40204         return edges;
40205     };
40206     /**
40207      * Computes the similar edges for a node.
40208      *
40209      * @description Similar edges for perspective images and cropped panoramas
40210      * look roughly in the same direction and are positioned closed to the node.
40211      * Similar edges for full panoramas only target other full panoramas.
40212      *
40213      * @param {Node} node - Source node.
40214      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
40215      * @throws {ArgumentMapillaryError} If node is not full.
40216      */
40217     EdgeCalculator.prototype.computeSimilarEdges = function (node, potentialEdges) {
40218         var _this = this;
40219         if (!node.full) {
40220             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
40221         }
40222         var nodeFullPano = node.fullPano;
40223         var sequenceGroups = {};
40224         for (var _i = 0, potentialEdges_1 = potentialEdges; _i < potentialEdges_1.length; _i++) {
40225             var potentialEdge = potentialEdges_1[_i];
40226             if (potentialEdge.sequenceKey == null) {
40227                 continue;
40228             }
40229             if (potentialEdge.sameSequence ||
40230                 !potentialEdge.sameMergeCC) {
40231                 continue;
40232             }
40233             if (nodeFullPano) {
40234                 if (!potentialEdge.fullPano) {
40235                     continue;
40236                 }
40237             }
40238             else {
40239                 if (!potentialEdge.fullPano &&
40240                     Math.abs(potentialEdge.directionChange) > this._settings.similarMaxDirectionChange) {
40241                     continue;
40242                 }
40243             }
40244             if (potentialEdge.distance > this._settings.similarMaxDistance) {
40245                 continue;
40246             }
40247             if (potentialEdge.sameUser &&
40248                 Math.abs(potentialEdge.capturedAt - node.capturedAt) <
40249                     this._settings.similarMinTimeDifference) {
40250                 continue;
40251             }
40252             if (sequenceGroups[potentialEdge.sequenceKey] == null) {
40253                 sequenceGroups[potentialEdge.sequenceKey] = [];
40254             }
40255             sequenceGroups[potentialEdge.sequenceKey].push(potentialEdge);
40256         }
40257         var similarEdges = [];
40258         var calculateScore = node.fullPano ?
40259             function (potentialEdge) {
40260                 return potentialEdge.distance;
40261             } :
40262             function (potentialEdge) {
40263                 return _this._coefficients.similarDistance * potentialEdge.distance +
40264                     _this._coefficients.similarRotation * potentialEdge.rotation;
40265             };
40266         for (var sequenceKey in sequenceGroups) {
40267             if (!sequenceGroups.hasOwnProperty(sequenceKey)) {
40268                 continue;
40269             }
40270             var lowestScore = Number.MAX_VALUE;
40271             var similarEdge = null;
40272             for (var _a = 0, _b = sequenceGroups[sequenceKey]; _a < _b.length; _a++) {
40273                 var potentialEdge = _b[_a];
40274                 var score = calculateScore(potentialEdge);
40275                 if (score < lowestScore) {
40276                     lowestScore = score;
40277                     similarEdge = potentialEdge;
40278                 }
40279             }
40280             if (similarEdge == null) {
40281                 continue;
40282             }
40283             similarEdges.push(similarEdge);
40284         }
40285         return similarEdges
40286             .map(function (potentialEdge) {
40287             return {
40288                 data: {
40289                     direction: Edge_1.EdgeDirection.Similar,
40290                     worldMotionAzimuth: potentialEdge.worldMotionAzimuth,
40291                 },
40292                 from: node.key,
40293                 to: potentialEdge.key,
40294             };
40295         });
40296     };
40297     /**
40298      * Computes the step edges for a perspective node.
40299      *
40300      * @description Step edge targets can only be other perspective nodes.
40301      * Returns an empty array for cropped and full panoramas.
40302      *
40303      * @param {Node} node - Source node.
40304      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
40305      * @param {string} prevKey - Key of previous node in sequence.
40306      * @param {string} prevKey - Key of next node in sequence.
40307      * @throws {ArgumentMapillaryError} If node is not full.
40308      */
40309     EdgeCalculator.prototype.computeStepEdges = function (node, potentialEdges, prevKey, nextKey) {
40310         if (!node.full) {
40311             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
40312         }
40313         var edges = [];
40314         if (node.pano) {
40315             return edges;
40316         }
40317         for (var k in this._directions.steps) {
40318             if (!this._directions.steps.hasOwnProperty(k)) {
40319                 continue;
40320             }
40321             var step = this._directions.steps[k];
40322             var lowestScore = Number.MAX_VALUE;
40323             var edge = null;
40324             var fallback = null;
40325             for (var _i = 0, potentialEdges_2 = potentialEdges; _i < potentialEdges_2.length; _i++) {
40326                 var potential = potentialEdges_2[_i];
40327                 if (potential.croppedPano || potential.fullPano) {
40328                     continue;
40329                 }
40330                 if (Math.abs(potential.directionChange) > this._settings.stepMaxDirectionChange) {
40331                     continue;
40332                 }
40333                 var motionDifference = this._spatial.angleDifference(step.motionChange, potential.motionChange);
40334                 var directionMotionDifference = this._spatial.angleDifference(potential.directionChange, motionDifference);
40335                 var drift = Math.max(Math.abs(motionDifference), Math.abs(directionMotionDifference));
40336                 if (Math.abs(drift) > this._settings.stepMaxDrift) {
40337                     continue;
40338                 }
40339                 var potentialKey = potential.key;
40340                 if (step.useFallback && (potentialKey === prevKey || potentialKey === nextKey)) {
40341                     fallback = potential;
40342                 }
40343                 if (potential.distance > this._settings.stepMaxDistance) {
40344                     continue;
40345                 }
40346                 motionDifference = Math.sqrt(motionDifference * motionDifference +
40347                     potential.verticalMotion * potential.verticalMotion);
40348                 var score = this._coefficients.stepPreferredDistance *
40349                     Math.abs(potential.distance - this._settings.stepPreferredDistance) /
40350                     this._settings.stepMaxDistance +
40351                     this._coefficients.stepMotion * motionDifference / this._settings.stepMaxDrift +
40352                     this._coefficients.stepRotation * potential.rotation / this._settings.stepMaxDirectionChange +
40353                     this._coefficients.stepSequencePenalty * (potential.sameSequence ? 0 : 1) +
40354                     this._coefficients.stepMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
40355                 if (score < lowestScore) {
40356                     lowestScore = score;
40357                     edge = potential;
40358                 }
40359             }
40360             edge = edge == null ? fallback : edge;
40361             if (edge != null) {
40362                 edges.push({
40363                     data: {
40364                         direction: step.direction,
40365                         worldMotionAzimuth: edge.worldMotionAzimuth,
40366                     },
40367                     from: node.key,
40368                     to: edge.key,
40369                 });
40370             }
40371         }
40372         return edges;
40373     };
40374     /**
40375      * Computes the turn edges for a perspective node.
40376      *
40377      * @description Turn edge targets can only be other perspective images.
40378      * Returns an empty array for cropped and full panoramas.
40379      *
40380      * @param {Node} node - Source node.
40381      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
40382      * @throws {ArgumentMapillaryError} If node is not full.
40383      */
40384     EdgeCalculator.prototype.computeTurnEdges = function (node, potentialEdges) {
40385         if (!node.full) {
40386             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
40387         }
40388         var edges = [];
40389         if (node.pano) {
40390             return edges;
40391         }
40392         for (var k in this._directions.turns) {
40393             if (!this._directions.turns.hasOwnProperty(k)) {
40394                 continue;
40395             }
40396             var turn = this._directions.turns[k];
40397             var lowestScore = Number.MAX_VALUE;
40398             var edge = null;
40399             for (var _i = 0, potentialEdges_3 = potentialEdges; _i < potentialEdges_3.length; _i++) {
40400                 var potential = potentialEdges_3[_i];
40401                 if (potential.croppedPano || potential.fullPano) {
40402                     continue;
40403                 }
40404                 if (potential.distance > this._settings.turnMaxDistance) {
40405                     continue;
40406                 }
40407                 var rig = turn.direction !== Edge_1.EdgeDirection.TurnU &&
40408                     potential.distance < this._settings.turnMaxRigDistance &&
40409                     Math.abs(potential.directionChange) > this._settings.turnMinRigDirectionChange;
40410                 var directionDifference = this._spatial.angleDifference(turn.directionChange, potential.directionChange);
40411                 var score = void 0;
40412                 if (rig &&
40413                     potential.directionChange * turn.directionChange > 0 &&
40414                     Math.abs(potential.directionChange) < Math.abs(turn.directionChange)) {
40415                     score = -Math.PI / 2 + Math.abs(potential.directionChange);
40416                 }
40417                 else {
40418                     if (Math.abs(directionDifference) > this._settings.turnMaxDirectionChange) {
40419                         continue;
40420                     }
40421                     var motionDifference = turn.motionChange ?
40422                         this._spatial.angleDifference(turn.motionChange, potential.motionChange) : 0;
40423                     motionDifference = Math.sqrt(motionDifference * motionDifference +
40424                         potential.verticalMotion * potential.verticalMotion);
40425                     score =
40426                         this._coefficients.turnDistance * potential.distance /
40427                             this._settings.turnMaxDistance +
40428                             this._coefficients.turnMotion * motionDifference / Math.PI +
40429                             this._coefficients.turnSequencePenalty * (potential.sameSequence ? 0 : 1) +
40430                             this._coefficients.turnMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
40431                 }
40432                 if (score < lowestScore) {
40433                     lowestScore = score;
40434                     edge = potential;
40435                 }
40436             }
40437             if (edge != null) {
40438                 edges.push({
40439                     data: {
40440                         direction: turn.direction,
40441                         worldMotionAzimuth: edge.worldMotionAzimuth,
40442                     },
40443                     from: node.key,
40444                     to: edge.key,
40445                 });
40446             }
40447         }
40448         return edges;
40449     };
40450     /**
40451      * Computes the pano edges for a perspective node.
40452      *
40453      * @description Perspective to pano edge targets can only be
40454      * full pano nodes. Returns an empty array for cropped and full panoramas.
40455      *
40456      * @param {Node} node - Source node.
40457      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
40458      * @throws {ArgumentMapillaryError} If node is not full.
40459      */
40460     EdgeCalculator.prototype.computePerspectiveToPanoEdges = function (node, potentialEdges) {
40461         if (!node.full) {
40462             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
40463         }
40464         if (node.pano) {
40465             return [];
40466         }
40467         var lowestScore = Number.MAX_VALUE;
40468         var edge = null;
40469         for (var _i = 0, potentialEdges_4 = potentialEdges; _i < potentialEdges_4.length; _i++) {
40470             var potential = potentialEdges_4[_i];
40471             if (!potential.fullPano) {
40472                 continue;
40473             }
40474             var score = this._coefficients.panoPreferredDistance *
40475                 Math.abs(potential.distance - this._settings.panoPreferredDistance) /
40476                 this._settings.panoMaxDistance +
40477                 this._coefficients.panoMotion * Math.abs(potential.motionChange) / Math.PI +
40478                 this._coefficients.panoMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
40479             if (score < lowestScore) {
40480                 lowestScore = score;
40481                 edge = potential;
40482             }
40483         }
40484         if (edge == null) {
40485             return [];
40486         }
40487         return [
40488             {
40489                 data: {
40490                     direction: Edge_1.EdgeDirection.Pano,
40491                     worldMotionAzimuth: edge.worldMotionAzimuth,
40492                 },
40493                 from: node.key,
40494                 to: edge.key,
40495             },
40496         ];
40497     };
40498     /**
40499      * Computes the full pano and step edges for a full pano node.
40500      *
40501      * @description Pano to pano edge targets can only be
40502      * full pano nodes. Pano to step edge targets can only be perspective
40503      * nodes.
40504      * Returns an empty array for cropped panoramas and perspective nodes.
40505      *
40506      * @param {Node} node - Source node.
40507      * @param {Array<IPotentialEdge>} potentialEdges - Potential edges.
40508      * @throws {ArgumentMapillaryError} If node is not full.
40509      */
40510     EdgeCalculator.prototype.computePanoEdges = function (node, potentialEdges) {
40511         if (!node.full) {
40512             throw new Error_1.ArgumentMapillaryError("Node has to be full.");
40513         }
40514         if (!node.fullPano) {
40515             return [];
40516         }
40517         var panoEdges = [];
40518         var potentialPanos = [];
40519         var potentialSteps = [];
40520         for (var _i = 0, potentialEdges_5 = potentialEdges; _i < potentialEdges_5.length; _i++) {
40521             var potential = potentialEdges_5[_i];
40522             if (potential.distance > this._settings.panoMaxDistance) {
40523                 continue;
40524             }
40525             if (potential.fullPano) {
40526                 if (potential.distance < this._settings.panoMinDistance) {
40527                     continue;
40528                 }
40529                 potentialPanos.push(potential);
40530             }
40531             else {
40532                 if (potential.croppedPano) {
40533                     continue;
40534                 }
40535                 for (var k in this._directions.panos) {
40536                     if (!this._directions.panos.hasOwnProperty(k)) {
40537                         continue;
40538                     }
40539                     var pano = this._directions.panos[k];
40540                     var turn = this._spatial.angleDifference(potential.directionChange, potential.motionChange);
40541                     var turnChange = this._spatial.angleDifference(pano.directionChange, turn);
40542                     if (Math.abs(turnChange) > this._settings.panoMaxStepTurnChange) {
40543                         continue;
40544                     }
40545                     potentialSteps.push([pano.direction, potential]);
40546                     // break if step direction found
40547                     break;
40548                 }
40549             }
40550         }
40551         var maxRotationDifference = Math.PI / this._settings.panoMaxItems;
40552         var occupiedAngles = [];
40553         var stepAngles = [];
40554         for (var index = 0; index < this._settings.panoMaxItems; index++) {
40555             var rotation = index / this._settings.panoMaxItems * 2 * Math.PI;
40556             var lowestScore = Number.MAX_VALUE;
40557             var edge = null;
40558             for (var _a = 0, potentialPanos_1 = potentialPanos; _a < potentialPanos_1.length; _a++) {
40559                 var potential = potentialPanos_1[_a];
40560                 var motionDifference = this._spatial.angleDifference(rotation, potential.motionChange);
40561                 if (Math.abs(motionDifference) > maxRotationDifference) {
40562                     continue;
40563                 }
40564                 var occupiedDifference = Number.MAX_VALUE;
40565                 for (var _b = 0, occupiedAngles_1 = occupiedAngles; _b < occupiedAngles_1.length; _b++) {
40566                     var occupiedAngle = occupiedAngles_1[_b];
40567                     var difference = Math.abs(this._spatial.angleDifference(occupiedAngle, potential.motionChange));
40568                     if (difference < occupiedDifference) {
40569                         occupiedDifference = difference;
40570                     }
40571                 }
40572                 if (occupiedDifference <= maxRotationDifference) {
40573                     continue;
40574                 }
40575                 var score = this._coefficients.panoPreferredDistance *
40576                     Math.abs(potential.distance - this._settings.panoPreferredDistance) /
40577                     this._settings.panoMaxDistance +
40578                     this._coefficients.panoMotion * Math.abs(motionDifference) / maxRotationDifference +
40579                     this._coefficients.panoSequencePenalty * (potential.sameSequence ? 0 : 1) +
40580                     this._coefficients.panoMergeCCPenalty * (potential.sameMergeCC ? 0 : 1);
40581                 if (score < lowestScore) {
40582                     lowestScore = score;
40583                     edge = potential;
40584                 }
40585             }
40586             if (edge != null) {
40587                 occupiedAngles.push(edge.motionChange);
40588                 panoEdges.push({
40589                     data: {
40590                         direction: Edge_1.EdgeDirection.Pano,
40591                         worldMotionAzimuth: edge.worldMotionAzimuth,
40592                     },
40593                     from: node.key,
40594                     to: edge.key,
40595                 });
40596             }
40597             else {
40598                 stepAngles.push(rotation);
40599             }
40600         }
40601         var occupiedStepAngles = {};
40602         occupiedStepAngles[Edge_1.EdgeDirection.Pano] = occupiedAngles;
40603         occupiedStepAngles[Edge_1.EdgeDirection.StepForward] = [];
40604         occupiedStepAngles[Edge_1.EdgeDirection.StepLeft] = [];
40605         occupiedStepAngles[Edge_1.EdgeDirection.StepBackward] = [];
40606         occupiedStepAngles[Edge_1.EdgeDirection.StepRight] = [];
40607         for (var _c = 0, stepAngles_1 = stepAngles; _c < stepAngles_1.length; _c++) {
40608             var stepAngle = stepAngles_1[_c];
40609             var occupations = [];
40610             for (var k in this._directions.panos) {
40611                 if (!this._directions.panos.hasOwnProperty(k)) {
40612                     continue;
40613                 }
40614                 var pano = this._directions.panos[k];
40615                 var allOccupiedAngles = occupiedStepAngles[Edge_1.EdgeDirection.Pano]
40616                     .concat(occupiedStepAngles[pano.direction])
40617                     .concat(occupiedStepAngles[pano.prev])
40618                     .concat(occupiedStepAngles[pano.next]);
40619                 var lowestScore = Number.MAX_VALUE;
40620                 var edge = null;
40621                 for (var _d = 0, potentialSteps_1 = potentialSteps; _d < potentialSteps_1.length; _d++) {
40622                     var potential = potentialSteps_1[_d];
40623                     if (potential[0] !== pano.direction) {
40624                         continue;
40625                     }
40626                     var motionChange = this._spatial.angleDifference(stepAngle, potential[1].motionChange);
40627                     if (Math.abs(motionChange) > maxRotationDifference) {
40628                         continue;
40629                     }
40630                     var minOccupiedDifference = Number.MAX_VALUE;
40631                     for (var _e = 0, allOccupiedAngles_1 = allOccupiedAngles; _e < allOccupiedAngles_1.length; _e++) {
40632                         var occupiedAngle = allOccupiedAngles_1[_e];
40633                         var occupiedDifference = Math.abs(this._spatial.angleDifference(occupiedAngle, potential[1].motionChange));
40634                         if (occupiedDifference < minOccupiedDifference) {
40635                             minOccupiedDifference = occupiedDifference;
40636                         }
40637                     }
40638                     if (minOccupiedDifference <= maxRotationDifference) {
40639                         continue;
40640                     }
40641                     var score = this._coefficients.panoPreferredDistance *
40642                         Math.abs(potential[1].distance - this._settings.panoPreferredDistance) /
40643                         this._settings.panoMaxDistance +
40644                         this._coefficients.panoMotion * Math.abs(motionChange) / maxRotationDifference +
40645                         this._coefficients.panoMergeCCPenalty * (potential[1].sameMergeCC ? 0 : 1);
40646                     if (score < lowestScore) {
40647                         lowestScore = score;
40648                         edge = potential;
40649                     }
40650                 }
40651                 if (edge != null) {
40652                     occupations.push(edge);
40653                     panoEdges.push({
40654                         data: {
40655                             direction: edge[0],
40656                             worldMotionAzimuth: edge[1].worldMotionAzimuth,
40657                         },
40658                         from: node.key,
40659                         to: edge[1].key,
40660                     });
40661                 }
40662             }
40663             for (var _f = 0, occupations_1 = occupations; _f < occupations_1.length; _f++) {
40664                 var occupation = occupations_1[_f];
40665                 occupiedStepAngles[occupation[0]].push(occupation[1].motionChange);
40666             }
40667         }
40668         return panoEdges;
40669     };
40670     return EdgeCalculator;
40671 }());
40672 exports.EdgeCalculator = EdgeCalculator;
40673 exports.default = EdgeCalculator;
40674
40675 },{"../../Edge":292,"../../Error":293,"../../Geo":294,"three":241}],403:[function(require,module,exports){
40676 "use strict";
40677 Object.defineProperty(exports, "__esModule", { value: true });
40678 var EdgeCalculatorCoefficients = /** @class */ (function () {
40679     function EdgeCalculatorCoefficients() {
40680         this.panoPreferredDistance = 2;
40681         this.panoMotion = 2;
40682         this.panoSequencePenalty = 1;
40683         this.panoMergeCCPenalty = 4;
40684         this.stepPreferredDistance = 4;
40685         this.stepMotion = 3;
40686         this.stepRotation = 4;
40687         this.stepSequencePenalty = 2;
40688         this.stepMergeCCPenalty = 6;
40689         this.similarDistance = 2;
40690         this.similarRotation = 3;
40691         this.turnDistance = 4;
40692         this.turnMotion = 2;
40693         this.turnSequencePenalty = 1;
40694         this.turnMergeCCPenalty = 4;
40695     }
40696     return EdgeCalculatorCoefficients;
40697 }());
40698 exports.EdgeCalculatorCoefficients = EdgeCalculatorCoefficients;
40699 exports.default = EdgeCalculatorCoefficients;
40700
40701 },{}],404:[function(require,module,exports){
40702 "use strict";
40703 Object.defineProperty(exports, "__esModule", { value: true });
40704 var Edge_1 = require("../../Edge");
40705 var EdgeCalculatorDirections = /** @class */ (function () {
40706     function EdgeCalculatorDirections() {
40707         this.steps = {};
40708         this.turns = {};
40709         this.panos = {};
40710         this.steps[Edge_1.EdgeDirection.StepForward] = {
40711             direction: Edge_1.EdgeDirection.StepForward,
40712             motionChange: 0,
40713             useFallback: true,
40714         };
40715         this.steps[Edge_1.EdgeDirection.StepBackward] = {
40716             direction: Edge_1.EdgeDirection.StepBackward,
40717             motionChange: Math.PI,
40718             useFallback: true,
40719         };
40720         this.steps[Edge_1.EdgeDirection.StepLeft] = {
40721             direction: Edge_1.EdgeDirection.StepLeft,
40722             motionChange: Math.PI / 2,
40723             useFallback: false,
40724         };
40725         this.steps[Edge_1.EdgeDirection.StepRight] = {
40726             direction: Edge_1.EdgeDirection.StepRight,
40727             motionChange: -Math.PI / 2,
40728             useFallback: false,
40729         };
40730         this.turns[Edge_1.EdgeDirection.TurnLeft] = {
40731             direction: Edge_1.EdgeDirection.TurnLeft,
40732             directionChange: Math.PI / 2,
40733             motionChange: Math.PI / 4,
40734         };
40735         this.turns[Edge_1.EdgeDirection.TurnRight] = {
40736             direction: Edge_1.EdgeDirection.TurnRight,
40737             directionChange: -Math.PI / 2,
40738             motionChange: -Math.PI / 4,
40739         };
40740         this.turns[Edge_1.EdgeDirection.TurnU] = {
40741             direction: Edge_1.EdgeDirection.TurnU,
40742             directionChange: Math.PI,
40743             motionChange: null,
40744         };
40745         this.panos[Edge_1.EdgeDirection.StepForward] = {
40746             direction: Edge_1.EdgeDirection.StepForward,
40747             directionChange: 0,
40748             next: Edge_1.EdgeDirection.StepLeft,
40749             prev: Edge_1.EdgeDirection.StepRight,
40750         };
40751         this.panos[Edge_1.EdgeDirection.StepBackward] = {
40752             direction: Edge_1.EdgeDirection.StepBackward,
40753             directionChange: Math.PI,
40754             next: Edge_1.EdgeDirection.StepRight,
40755             prev: Edge_1.EdgeDirection.StepLeft,
40756         };
40757         this.panos[Edge_1.EdgeDirection.StepLeft] = {
40758             direction: Edge_1.EdgeDirection.StepLeft,
40759             directionChange: Math.PI / 2,
40760             next: Edge_1.EdgeDirection.StepBackward,
40761             prev: Edge_1.EdgeDirection.StepForward,
40762         };
40763         this.panos[Edge_1.EdgeDirection.StepRight] = {
40764             direction: Edge_1.EdgeDirection.StepRight,
40765             directionChange: -Math.PI / 2,
40766             next: Edge_1.EdgeDirection.StepForward,
40767             prev: Edge_1.EdgeDirection.StepBackward,
40768         };
40769     }
40770     return EdgeCalculatorDirections;
40771 }());
40772 exports.EdgeCalculatorDirections = EdgeCalculatorDirections;
40773
40774 },{"../../Edge":292}],405:[function(require,module,exports){
40775 "use strict";
40776 Object.defineProperty(exports, "__esModule", { value: true });
40777 var EdgeCalculatorSettings = /** @class */ (function () {
40778     function EdgeCalculatorSettings() {
40779         this.panoMinDistance = 0.1;
40780         this.panoMaxDistance = 20;
40781         this.panoPreferredDistance = 5;
40782         this.panoMaxItems = 4;
40783         this.panoMaxStepTurnChange = Math.PI / 8;
40784         this.rotationMaxDistance = this.turnMaxRigDistance;
40785         this.rotationMaxDirectionChange = Math.PI / 6;
40786         this.rotationMaxVerticalDirectionChange = Math.PI / 8;
40787         this.similarMaxDirectionChange = Math.PI / 8;
40788         this.similarMaxDistance = 12;
40789         this.similarMinTimeDifference = 12 * 3600 * 1000;
40790         this.stepMaxDistance = 20;
40791         this.stepMaxDirectionChange = Math.PI / 6;
40792         this.stepMaxDrift = Math.PI / 6;
40793         this.stepPreferredDistance = 4;
40794         this.turnMaxDistance = 15;
40795         this.turnMaxDirectionChange = 2 * Math.PI / 9;
40796         this.turnMaxRigDistance = 0.65;
40797         this.turnMinRigDirectionChange = Math.PI / 6;
40798     }
40799     Object.defineProperty(EdgeCalculatorSettings.prototype, "maxDistance", {
40800         get: function () {
40801             return Math.max(this.panoMaxDistance, this.similarMaxDistance, this.stepMaxDistance, this.turnMaxDistance);
40802         },
40803         enumerable: true,
40804         configurable: true
40805     });
40806     return EdgeCalculatorSettings;
40807 }());
40808 exports.EdgeCalculatorSettings = EdgeCalculatorSettings;
40809 exports.default = EdgeCalculatorSettings;
40810
40811 },{}],406:[function(require,module,exports){
40812 "use strict";
40813 Object.defineProperty(exports, "__esModule", { value: true });
40814 /**
40815  * Enumeration for edge directions
40816  * @enum {number}
40817  * @readonly
40818  * @description Directions for edges in node graph describing
40819  * sequence, spatial and node type relations between nodes.
40820  */
40821 var EdgeDirection;
40822 (function (EdgeDirection) {
40823     /**
40824      * Next node in the sequence.
40825      */
40826     EdgeDirection[EdgeDirection["Next"] = 0] = "Next";
40827     /**
40828      * Previous node in the sequence.
40829      */
40830     EdgeDirection[EdgeDirection["Prev"] = 1] = "Prev";
40831     /**
40832      * Step to the left keeping viewing direction.
40833      */
40834     EdgeDirection[EdgeDirection["StepLeft"] = 2] = "StepLeft";
40835     /**
40836      * Step to the right keeping viewing direction.
40837      */
40838     EdgeDirection[EdgeDirection["StepRight"] = 3] = "StepRight";
40839     /**
40840      * Step forward keeping viewing direction.
40841      */
40842     EdgeDirection[EdgeDirection["StepForward"] = 4] = "StepForward";
40843     /**
40844      * Step backward keeping viewing direction.
40845      */
40846     EdgeDirection[EdgeDirection["StepBackward"] = 5] = "StepBackward";
40847     /**
40848      * Turn 90 degrees counter clockwise.
40849      */
40850     EdgeDirection[EdgeDirection["TurnLeft"] = 6] = "TurnLeft";
40851     /**
40852      * Turn 90 degrees clockwise.
40853      */
40854     EdgeDirection[EdgeDirection["TurnRight"] = 7] = "TurnRight";
40855     /**
40856      * Turn 180 degrees.
40857      */
40858     EdgeDirection[EdgeDirection["TurnU"] = 8] = "TurnU";
40859     /**
40860      * Panorama in general direction.
40861      */
40862     EdgeDirection[EdgeDirection["Pano"] = 9] = "Pano";
40863     /**
40864      * Looking in roughly the same direction at rougly the same position.
40865      */
40866     EdgeDirection[EdgeDirection["Similar"] = 10] = "Similar";
40867 })(EdgeDirection = exports.EdgeDirection || (exports.EdgeDirection = {}));
40868
40869 },{}],407:[function(require,module,exports){
40870 "use strict";
40871 /// <reference path="../../typings/index.d.ts" />
40872 Object.defineProperty(exports, "__esModule", { value: true });
40873 var _ = require("underscore");
40874 var vd = require("virtual-dom");
40875 var Subject_1 = require("rxjs/Subject");
40876 require("rxjs/add/operator/combineLatest");
40877 require("rxjs/add/operator/distinctUntilChanged");
40878 require("rxjs/add/operator/filter");
40879 require("rxjs/add/operator/map");
40880 require("rxjs/add/operator/pluck");
40881 require("rxjs/add/operator/scan");
40882 var Render_1 = require("../Render");
40883 var DOMRenderer = /** @class */ (function () {
40884     function DOMRenderer(element, renderService, currentFrame$) {
40885         this._adaptiveOperation$ = new Subject_1.Subject();
40886         this._render$ = new Subject_1.Subject();
40887         this._renderAdaptive$ = new Subject_1.Subject();
40888         this._renderService = renderService;
40889         this._currentFrame$ = currentFrame$;
40890         var rootNode = vd.create(vd.h("div.domRenderer", []));
40891         element.appendChild(rootNode);
40892         this._offset$ = this._adaptiveOperation$
40893             .scan(function (adaptive, operation) {
40894             return operation(adaptive);
40895         }, {
40896             elementHeight: element.offsetHeight,
40897             elementWidth: element.offsetWidth,
40898             imageAspect: 0,
40899             renderMode: Render_1.RenderMode.Fill,
40900         })
40901             .filter(function (adaptive) {
40902             return adaptive.imageAspect > 0 && adaptive.elementWidth > 0 && adaptive.elementHeight > 0;
40903         })
40904             .map(function (adaptive) {
40905             var elementAspect = adaptive.elementWidth / adaptive.elementHeight;
40906             var ratio = adaptive.imageAspect / elementAspect;
40907             var verticalOffset = 0;
40908             var horizontalOffset = 0;
40909             if (adaptive.renderMode === Render_1.RenderMode.Letterbox) {
40910                 if (adaptive.imageAspect > elementAspect) {
40911                     verticalOffset = adaptive.elementHeight * (1 - 1 / ratio) / 2;
40912                 }
40913                 else {
40914                     horizontalOffset = adaptive.elementWidth * (1 - ratio) / 2;
40915                 }
40916             }
40917             else {
40918                 if (adaptive.imageAspect > elementAspect) {
40919                     horizontalOffset = -adaptive.elementWidth * (ratio - 1) / 2;
40920                 }
40921                 else {
40922                     verticalOffset = -adaptive.elementHeight * (1 / ratio - 1) / 2;
40923                 }
40924             }
40925             return {
40926                 bottom: verticalOffset,
40927                 left: horizontalOffset,
40928                 right: horizontalOffset,
40929                 top: verticalOffset,
40930             };
40931         });
40932         this._currentFrame$
40933             .filter(function (frame) {
40934             return frame.state.currentNode != null;
40935         })
40936             .distinctUntilChanged(function (k1, k2) {
40937             return k1 === k2;
40938         }, function (frame) {
40939             return frame.state.currentNode.key;
40940         })
40941             .map(function (frame) {
40942             return frame.state.currentTransform.basicAspect;
40943         })
40944             .map(function (aspect) {
40945             return function (adaptive) {
40946                 adaptive.imageAspect = aspect;
40947                 return adaptive;
40948             };
40949         })
40950             .subscribe(this._adaptiveOperation$);
40951         this._renderAdaptive$
40952             .scan(function (vNodeHashes, vNodeHash) {
40953             if (vNodeHash.vnode == null) {
40954                 delete vNodeHashes[vNodeHash.name];
40955             }
40956             else {
40957                 vNodeHashes[vNodeHash.name] = vNodeHash.vnode;
40958             }
40959             return vNodeHashes;
40960         }, {})
40961             .combineLatest(this._offset$)
40962             .map(function (vo) {
40963             var vNodes = _.values(vo[0]);
40964             var offset = vo[1];
40965             var properties = {
40966                 style: {
40967                     bottom: offset.bottom + "px",
40968                     left: offset.left + "px",
40969                     "pointer-events": "none",
40970                     position: "absolute",
40971                     right: offset.right + "px",
40972                     top: offset.top + "px",
40973                 },
40974             };
40975             return {
40976                 name: "adaptiveDomRenderer",
40977                 vnode: vd.h("div.adaptiveDomRenderer", properties, vNodes),
40978             };
40979         })
40980             .subscribe(this._render$);
40981         this._vNode$ = this._render$
40982             .scan(function (vNodeHashes, vNodeHash) {
40983             if (vNodeHash.vnode == null) {
40984                 delete vNodeHashes[vNodeHash.name];
40985             }
40986             else {
40987                 vNodeHashes[vNodeHash.name] = vNodeHash.vnode;
40988             }
40989             return vNodeHashes;
40990         }, {})
40991             .map(function (vNodeHashes) {
40992             var vNodes = _.values(vNodeHashes);
40993             return vd.h("div.domRenderer", vNodes);
40994         });
40995         this._vPatch$ = this._vNode$
40996             .scan(function (nodePatch, vNode) {
40997             nodePatch.vpatch = vd.diff(nodePatch.vnode, vNode);
40998             nodePatch.vnode = vNode;
40999             return nodePatch;
41000         }, { vnode: vd.h("div.domRenderer", []), vpatch: null })
41001             .pluck("vpatch");
41002         this._element$ = this._vPatch$
41003             .scan(function (oldElement, vPatch) {
41004             return vd.patch(oldElement, vPatch);
41005         }, rootNode)
41006             .publishReplay(1)
41007             .refCount();
41008         this._element$.subscribe(function () { });
41009         this._renderService.size$
41010             .map(function (size) {
41011             return function (adaptive) {
41012                 adaptive.elementWidth = size.width;
41013                 adaptive.elementHeight = size.height;
41014                 return adaptive;
41015             };
41016         })
41017             .subscribe(this._adaptiveOperation$);
41018         this._renderService.renderMode$
41019             .map(function (renderMode) {
41020             return function (adaptive) {
41021                 adaptive.renderMode = renderMode;
41022                 return adaptive;
41023             };
41024         })
41025             .subscribe(this._adaptiveOperation$);
41026     }
41027     Object.defineProperty(DOMRenderer.prototype, "element$", {
41028         get: function () {
41029             return this._element$;
41030         },
41031         enumerable: true,
41032         configurable: true
41033     });
41034     Object.defineProperty(DOMRenderer.prototype, "render$", {
41035         get: function () {
41036             return this._render$;
41037         },
41038         enumerable: true,
41039         configurable: true
41040     });
41041     Object.defineProperty(DOMRenderer.prototype, "renderAdaptive$", {
41042         get: function () {
41043             return this._renderAdaptive$;
41044         },
41045         enumerable: true,
41046         configurable: true
41047     });
41048     DOMRenderer.prototype.clear = function (name) {
41049         this._renderAdaptive$.next({ name: name, vnode: null });
41050         this._render$.next({ name: name, vnode: null });
41051     };
41052     return DOMRenderer;
41053 }());
41054 exports.DOMRenderer = DOMRenderer;
41055 exports.default = DOMRenderer;
41056
41057 },{"../Render":297,"rxjs/Subject":34,"rxjs/add/operator/combineLatest":55,"rxjs/add/operator/distinctUntilChanged":60,"rxjs/add/operator/filter":63,"rxjs/add/operator/map":67,"rxjs/add/operator/pluck":72,"rxjs/add/operator/scan":78,"underscore":243,"virtual-dom":247}],408:[function(require,module,exports){
41058 "use strict";
41059 Object.defineProperty(exports, "__esModule", { value: true });
41060 var GLRenderStage;
41061 (function (GLRenderStage) {
41062     GLRenderStage[GLRenderStage["Background"] = 0] = "Background";
41063     GLRenderStage[GLRenderStage["Foreground"] = 1] = "Foreground";
41064 })(GLRenderStage = exports.GLRenderStage || (exports.GLRenderStage = {}));
41065 exports.default = GLRenderStage;
41066
41067 },{}],409:[function(require,module,exports){
41068 "use strict";
41069 /// <reference path="../../typings/index.d.ts" />
41070 Object.defineProperty(exports, "__esModule", { value: true });
41071 var THREE = require("three");
41072 var Observable_1 = require("rxjs/Observable");
41073 var Subject_1 = require("rxjs/Subject");
41074 require("rxjs/add/observable/combineLatest");
41075 require("rxjs/add/operator/distinctUntilChanged");
41076 require("rxjs/add/operator/filter");
41077 require("rxjs/add/operator/first");
41078 require("rxjs/add/operator/map");
41079 require("rxjs/add/operator/merge");
41080 require("rxjs/add/operator/mergeMap");
41081 require("rxjs/add/operator/scan");
41082 require("rxjs/add/operator/share");
41083 require("rxjs/add/operator/startWith");
41084 var Render_1 = require("../Render");
41085 var Utils_1 = require("../Utils");
41086 var GLRenderer = /** @class */ (function () {
41087     function GLRenderer(canvasContainer, renderService, dom) {
41088         var _this = this;
41089         this._renderFrame$ = new Subject_1.Subject();
41090         this._renderCameraOperation$ = new Subject_1.Subject();
41091         this._render$ = new Subject_1.Subject();
41092         this._clear$ = new Subject_1.Subject();
41093         this._renderOperation$ = new Subject_1.Subject();
41094         this._rendererOperation$ = new Subject_1.Subject();
41095         this._eraserOperation$ = new Subject_1.Subject();
41096         this._renderService = renderService;
41097         this._dom = !!dom ? dom : new Utils_1.DOM();
41098         this._renderer$ = this._rendererOperation$
41099             .scan(function (renderer, operation) {
41100             return operation(renderer);
41101         }, { needsRender: false, renderer: null });
41102         this._renderCollection$ = this._renderOperation$
41103             .scan(function (hashes, operation) {
41104             return operation(hashes);
41105         }, {})
41106             .share();
41107         this._renderCamera$ = this._renderCameraOperation$
41108             .scan(function (rc, operation) {
41109             return operation(rc);
41110         }, { frameId: -1, needsRender: false, perspective: null });
41111         this._eraser$ = this._eraserOperation$
41112             .startWith(function (eraser) {
41113             return eraser;
41114         })
41115             .scan(function (eraser, operation) {
41116             return operation(eraser);
41117         }, { needsRender: false });
41118         Observable_1.Observable
41119             .combineLatest([this._renderer$, this._renderCollection$, this._renderCamera$, this._eraser$], function (renderer, hashes, rc, eraser) {
41120             var renders = Object.keys(hashes)
41121                 .map(function (key) {
41122                 return hashes[key];
41123             });
41124             return { camera: rc, eraser: eraser, renderer: renderer, renders: renders };
41125         })
41126             .filter(function (co) {
41127             var needsRender = co.renderer.needsRender ||
41128                 co.camera.needsRender ||
41129                 co.eraser.needsRender;
41130             var frameId = co.camera.frameId;
41131             for (var _i = 0, _a = co.renders; _i < _a.length; _i++) {
41132                 var render = _a[_i];
41133                 if (render.frameId !== frameId) {
41134                     return false;
41135                 }
41136                 needsRender = needsRender || render.needsRender;
41137             }
41138             return needsRender;
41139         })
41140             .distinctUntilChanged(function (n1, n2) {
41141             return n1 === n2;
41142         }, function (co) {
41143             return co.eraser.needsRender ? -1 : co.camera.frameId;
41144         })
41145             .subscribe(function (co) {
41146             co.renderer.needsRender = false;
41147             co.camera.needsRender = false;
41148             co.eraser.needsRender = false;
41149             var perspectiveCamera = co.camera.perspective;
41150             var backgroundRenders = [];
41151             var foregroundRenders = [];
41152             for (var _i = 0, _a = co.renders; _i < _a.length; _i++) {
41153                 var render = _a[_i];
41154                 if (render.stage === Render_1.GLRenderStage.Background) {
41155                     backgroundRenders.push(render.render);
41156                 }
41157                 else if (render.stage === Render_1.GLRenderStage.Foreground) {
41158                     foregroundRenders.push(render.render);
41159                 }
41160             }
41161             var renderer = co.renderer.renderer;
41162             renderer.clear();
41163             for (var _b = 0, backgroundRenders_1 = backgroundRenders; _b < backgroundRenders_1.length; _b++) {
41164                 var render = backgroundRenders_1[_b];
41165                 render(perspectiveCamera, renderer);
41166             }
41167             renderer.clearDepth();
41168             for (var _c = 0, foregroundRenders_1 = foregroundRenders; _c < foregroundRenders_1.length; _c++) {
41169                 var render = foregroundRenders_1[_c];
41170                 render(perspectiveCamera, renderer);
41171             }
41172         });
41173         this._renderFrame$
41174             .map(function (rc) {
41175             return function (irc) {
41176                 irc.frameId = rc.frameId;
41177                 irc.perspective = rc.perspective;
41178                 if (rc.changed === true) {
41179                     irc.needsRender = true;
41180                 }
41181                 return irc;
41182             };
41183         })
41184             .subscribe(this._renderCameraOperation$);
41185         this._renderFrameSubscribe();
41186         var renderHash$ = this._render$
41187             .map(function (hash) {
41188             return function (hashes) {
41189                 hashes[hash.name] = hash.render;
41190                 return hashes;
41191             };
41192         });
41193         var clearHash$ = this._clear$
41194             .map(function (name) {
41195             return function (hashes) {
41196                 delete hashes[name];
41197                 return hashes;
41198             };
41199         });
41200         Observable_1.Observable
41201             .merge(renderHash$, clearHash$)
41202             .subscribe(this._renderOperation$);
41203         this._webGLRenderer$ = this._render$
41204             .first()
41205             .map(function (hash) {
41206             var canvas = _this._dom.createElement("canvas", "mapillary-js-canvas");
41207             canvas.style.position = "absolute";
41208             canvas.setAttribute("tabindex", "0");
41209             canvasContainer.appendChild(canvas);
41210             var element = renderService.element;
41211             var webGLRenderer = new THREE.WebGLRenderer({ canvas: canvas });
41212             webGLRenderer.setPixelRatio(window.devicePixelRatio);
41213             webGLRenderer.setSize(element.offsetWidth, element.offsetHeight);
41214             webGLRenderer.setClearColor(new THREE.Color(0x202020), 1.0);
41215             webGLRenderer.autoClear = false;
41216             return webGLRenderer;
41217         })
41218             .publishReplay(1)
41219             .refCount();
41220         this._webGLRenderer$.subscribe(function () { });
41221         var createRenderer$ = this._webGLRenderer$
41222             .first()
41223             .map(function (webGLRenderer) {
41224             return function (renderer) {
41225                 renderer.needsRender = true;
41226                 renderer.renderer = webGLRenderer;
41227                 return renderer;
41228             };
41229         });
41230         var resizeRenderer$ = this._renderService.size$
41231             .map(function (size) {
41232             return function (renderer) {
41233                 if (renderer.renderer == null) {
41234                     return renderer;
41235                 }
41236                 renderer.renderer.setSize(size.width, size.height);
41237                 renderer.needsRender = true;
41238                 return renderer;
41239             };
41240         });
41241         var clearRenderer$ = this._clear$
41242             .map(function (name) {
41243             return function (renderer) {
41244                 if (renderer.renderer == null) {
41245                     return renderer;
41246                 }
41247                 renderer.needsRender = true;
41248                 return renderer;
41249             };
41250         });
41251         Observable_1.Observable
41252             .merge(createRenderer$, resizeRenderer$, clearRenderer$)
41253             .subscribe(this._rendererOperation$);
41254         var renderCollectionEmpty$ = this._renderCollection$
41255             .filter(function (hashes) {
41256             return Object.keys(hashes).length === 0;
41257         })
41258             .share();
41259         renderCollectionEmpty$
41260             .subscribe(function (hashes) {
41261             if (_this._renderFrameSubscription == null) {
41262                 return;
41263             }
41264             _this._renderFrameSubscription.unsubscribe();
41265             _this._renderFrameSubscription = null;
41266             _this._renderFrameSubscribe();
41267         });
41268         renderCollectionEmpty$
41269             .map(function (hashes) {
41270             return function (eraser) {
41271                 eraser.needsRender = true;
41272                 return eraser;
41273             };
41274         })
41275             .subscribe(this._eraserOperation$);
41276     }
41277     Object.defineProperty(GLRenderer.prototype, "render$", {
41278         get: function () {
41279             return this._render$;
41280         },
41281         enumerable: true,
41282         configurable: true
41283     });
41284     Object.defineProperty(GLRenderer.prototype, "webGLRenderer$", {
41285         get: function () {
41286             return this._webGLRenderer$;
41287         },
41288         enumerable: true,
41289         configurable: true
41290     });
41291     GLRenderer.prototype.clear = function (name) {
41292         this._clear$.next(name);
41293     };
41294     GLRenderer.prototype._renderFrameSubscribe = function () {
41295         var _this = this;
41296         this._render$
41297             .first()
41298             .map(function (renderHash) {
41299             return function (irc) {
41300                 irc.needsRender = true;
41301                 return irc;
41302             };
41303         })
41304             .subscribe(function (operation) {
41305             _this._renderCameraOperation$.next(operation);
41306         });
41307         this._renderFrameSubscription = this._render$
41308             .first()
41309             .mergeMap(function (hash) {
41310             return _this._renderService.renderCameraFrame$;
41311         })
41312             .subscribe(this._renderFrame$);
41313     };
41314     return GLRenderer;
41315 }());
41316 exports.GLRenderer = GLRenderer;
41317 exports.default = GLRenderer;
41318
41319 },{"../Render":297,"../Utils":301,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/distinctUntilChanged":60,"rxjs/add/operator/filter":63,"rxjs/add/operator/first":65,"rxjs/add/operator/map":67,"rxjs/add/operator/merge":68,"rxjs/add/operator/mergeMap":70,"rxjs/add/operator/scan":78,"rxjs/add/operator/share":79,"rxjs/add/operator/startWith":83,"three":241}],410:[function(require,module,exports){
41320 "use strict";
41321 /// <reference path="../../typings/index.d.ts" />
41322 Object.defineProperty(exports, "__esModule", { value: true });
41323 var THREE = require("three");
41324 var Geo_1 = require("../Geo");
41325 var Render_1 = require("../Render");
41326 var RenderCamera = /** @class */ (function () {
41327     function RenderCamera(elementWidth, elementHeight, renderMode) {
41328         this.alpha = -1;
41329         this.zoom = 0;
41330         this._frameId = -1;
41331         this._changed = false;
41332         this._changedForFrame = -1;
41333         this.currentAspect = 1;
41334         this.currentPano = false;
41335         this.previousAspect = 1;
41336         this.previousPano = false;
41337         this.renderMode = renderMode;
41338         this._spatial = new Geo_1.Spatial();
41339         this._camera = new Geo_1.Camera();
41340         var perspectiveCameraAspect = this._getPerspectiveCameraAspect(elementWidth, elementHeight);
41341         this._perspective = new THREE.PerspectiveCamera(50, perspectiveCameraAspect, 0.4, 10000);
41342         this._perspective.matrixAutoUpdate = false;
41343         this._rotation = { phi: 0, theta: 0 };
41344     }
41345     Object.defineProperty(RenderCamera.prototype, "camera", {
41346         get: function () {
41347             return this._camera;
41348         },
41349         enumerable: true,
41350         configurable: true
41351     });
41352     Object.defineProperty(RenderCamera.prototype, "changed", {
41353         get: function () {
41354             return this.frameId === this._changedForFrame;
41355         },
41356         enumerable: true,
41357         configurable: true
41358     });
41359     Object.defineProperty(RenderCamera.prototype, "frameId", {
41360         get: function () {
41361             return this._frameId;
41362         },
41363         set: function (value) {
41364             this._frameId = value;
41365             if (this._changed) {
41366                 this._changed = false;
41367                 this._changedForFrame = value;
41368             }
41369         },
41370         enumerable: true,
41371         configurable: true
41372     });
41373     Object.defineProperty(RenderCamera.prototype, "perspective", {
41374         get: function () {
41375             return this._perspective;
41376         },
41377         enumerable: true,
41378         configurable: true
41379     });
41380     Object.defineProperty(RenderCamera.prototype, "rotation", {
41381         get: function () {
41382             return this._rotation;
41383         },
41384         enumerable: true,
41385         configurable: true
41386     });
41387     RenderCamera.prototype.updateAspect = function (elementWidth, elementHeight) {
41388         var perspectiveCameraAspect = this._getPerspectiveCameraAspect(elementWidth, elementHeight);
41389         this._perspective.aspect = perspectiveCameraAspect;
41390         this._changed = true;
41391     };
41392     RenderCamera.prototype.updateProjection = function () {
41393         var currentAspect = this._getAspect(this.currentAspect, this.currentPano, this.perspective.aspect);
41394         var previousAspect = this._getAspect(this.previousAspect, this.previousPano, this.perspective.aspect);
41395         var aspect = (1 - this.alpha) * previousAspect + this.alpha * currentAspect;
41396         var verticalFov = this._getVerticalFov(aspect, this._camera.focal, this.zoom);
41397         this._perspective.fov = verticalFov;
41398         this._perspective.updateProjectionMatrix();
41399         this._changed = true;
41400     };
41401     RenderCamera.prototype.updatePerspective = function (camera) {
41402         this._perspective.up.copy(camera.up);
41403         this._perspective.position.copy(camera.position);
41404         this._perspective.lookAt(camera.lookat);
41405         this._perspective.updateMatrix();
41406         this._perspective.updateMatrixWorld(false);
41407         this._changed = true;
41408     };
41409     RenderCamera.prototype.updateRotation = function (camera) {
41410         this._rotation = this._getRotation(camera);
41411     };
41412     RenderCamera.prototype._getVerticalFov = function (aspect, focal, zoom) {
41413         return 2 * Math.atan(0.5 / (Math.pow(2, zoom) * aspect * focal)) * 180 / Math.PI;
41414     };
41415     RenderCamera.prototype._getAspect = function (nodeAspect, pano, perspectiveCameraAspect) {
41416         if (pano) {
41417             return 1;
41418         }
41419         var coeff = Math.max(1, 1 / nodeAspect);
41420         var usePerspective = this.renderMode === Render_1.RenderMode.Letterbox ?
41421             nodeAspect > perspectiveCameraAspect :
41422             nodeAspect < perspectiveCameraAspect;
41423         var aspect = usePerspective ?
41424             coeff * perspectiveCameraAspect :
41425             coeff * nodeAspect;
41426         return aspect;
41427     };
41428     RenderCamera.prototype._getPerspectiveCameraAspect = function (elementWidth, elementHeight) {
41429         return elementWidth === 0 ? 0 : elementWidth / elementHeight;
41430     };
41431     RenderCamera.prototype._getRotation = function (camera) {
41432         var direction = camera.lookat.clone().sub(camera.position);
41433         var up = camera.up.clone();
41434         var upProjection = direction.clone().dot(up);
41435         var planeProjection = direction.clone().sub(up.clone().multiplyScalar(upProjection));
41436         var phi = Math.atan2(planeProjection.y, planeProjection.x);
41437         var theta = Math.PI / 2 - this._spatial.angleToPlane(direction.toArray(), [0, 0, 1]);
41438         return { phi: phi, theta: theta };
41439     };
41440     return RenderCamera;
41441 }());
41442 exports.RenderCamera = RenderCamera;
41443 exports.default = RenderCamera;
41444
41445 },{"../Geo":294,"../Render":297,"three":241}],411:[function(require,module,exports){
41446 "use strict";
41447 Object.defineProperty(exports, "__esModule", { value: true });
41448 /**
41449  * Enumeration for render mode
41450  * @enum {number}
41451  * @readonly
41452  * @description Modes for specifying how rendering is done
41453  * in the viewer. All modes preserves the original aspect
41454  * ratio of the images.
41455  */
41456 var RenderMode;
41457 (function (RenderMode) {
41458     /**
41459      * Displays all content within the viewer.
41460      *
41461      * @description Black bars shown on both
41462      * sides of the content. Bars are shown
41463      * either below and above or to the left
41464      * and right of the content depending on
41465      * the aspect ratio relation between the
41466      * image and the viewer.
41467      */
41468     RenderMode[RenderMode["Letterbox"] = 0] = "Letterbox";
41469     /**
41470      * Fills the viewer by cropping content.
41471      *
41472      * @description Cropping is done either
41473      * in horizontal or vertical direction
41474      * depending on the aspect ratio relation
41475      * between the image and the viewer.
41476      */
41477     RenderMode[RenderMode["Fill"] = 1] = "Fill";
41478 })(RenderMode = exports.RenderMode || (exports.RenderMode = {}));
41479 exports.default = RenderMode;
41480
41481 },{}],412:[function(require,module,exports){
41482 "use strict";
41483 /// <reference path="../../typings/index.d.ts" />
41484 Object.defineProperty(exports, "__esModule", { value: true });
41485 var Subject_1 = require("rxjs/Subject");
41486 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
41487 require("rxjs/add/observable/combineLatest");
41488 require("rxjs/add/operator/do");
41489 require("rxjs/add/operator/filter");
41490 require("rxjs/add/operator/map");
41491 require("rxjs/add/operator/publishReplay");
41492 require("rxjs/add/operator/scan");
41493 require("rxjs/add/operator/skip");
41494 require("rxjs/add/operator/startWith");
41495 require("rxjs/add/operator/withLatestFrom");
41496 var Geo_1 = require("../Geo");
41497 var Render_1 = require("../Render");
41498 var RenderService = /** @class */ (function () {
41499     function RenderService(element, currentFrame$, renderMode) {
41500         var _this = this;
41501         this._element = element;
41502         this._currentFrame$ = currentFrame$;
41503         this._spatial = new Geo_1.Spatial();
41504         renderMode = renderMode != null ? renderMode : Render_1.RenderMode.Fill;
41505         this._resize$ = new Subject_1.Subject();
41506         this._renderCameraOperation$ = new Subject_1.Subject();
41507         this._size$ =
41508             new BehaviorSubject_1.BehaviorSubject({
41509                 height: this._element.offsetHeight,
41510                 width: this._element.offsetWidth,
41511             });
41512         this._resize$
41513             .map(function () {
41514             return { height: _this._element.offsetHeight, width: _this._element.offsetWidth };
41515         })
41516             .subscribe(this._size$);
41517         this._renderMode$ = new BehaviorSubject_1.BehaviorSubject(renderMode);
41518         this._renderCameraHolder$ = this._renderCameraOperation$
41519             .startWith(function (rc) {
41520             return rc;
41521         })
41522             .scan(function (rc, operation) {
41523             return operation(rc);
41524         }, new Render_1.RenderCamera(this._element.offsetWidth, this._element.offsetHeight, renderMode))
41525             .publishReplay(1)
41526             .refCount();
41527         this._renderCameraFrame$ = this._currentFrame$
41528             .withLatestFrom(this._renderCameraHolder$, function (frame, renderCamera) {
41529             return [frame, renderCamera];
41530         })
41531             .do(function (args) {
41532             var frame = args[0];
41533             var rc = args[1];
41534             var camera = frame.state.camera;
41535             if (rc.alpha !== frame.state.alpha ||
41536                 rc.zoom !== frame.state.zoom ||
41537                 rc.camera.diff(camera) > 1e-9) {
41538                 var currentTransform = frame.state.currentTransform;
41539                 var previousTransform = frame.state.previousTransform != null ?
41540                     frame.state.previousTransform :
41541                     frame.state.currentTransform;
41542                 var previousNode = frame.state.previousNode != null ?
41543                     frame.state.previousNode :
41544                     frame.state.currentNode;
41545                 rc.currentAspect = currentTransform.basicAspect;
41546                 rc.currentPano = frame.state.currentNode.pano;
41547                 rc.previousAspect = previousTransform.basicAspect;
41548                 rc.previousPano = previousNode.pano;
41549                 rc.alpha = frame.state.alpha;
41550                 rc.zoom = frame.state.zoom;
41551                 rc.camera.copy(camera);
41552                 rc.updatePerspective(camera);
41553                 rc.updateRotation(camera);
41554                 rc.updateProjection();
41555             }
41556             rc.frameId = frame.id;
41557         })
41558             .map(function (args) {
41559             return args[1];
41560         })
41561             .publishReplay(1)
41562             .refCount();
41563         this._renderCamera$ = this._renderCameraFrame$
41564             .filter(function (rc) {
41565             return rc.changed;
41566         })
41567             .publishReplay(1)
41568             .refCount();
41569         this._bearing$ = this._renderCamera$
41570             .map(function (renderCamera) {
41571             var bearing = _this._spatial.radToDeg(_this._spatial.azimuthalToBearing(renderCamera.rotation.phi));
41572             return _this._spatial.wrap(bearing, 0, 360);
41573         })
41574             .publishReplay(1)
41575             .refCount();
41576         this._size$
41577             .skip(1)
41578             .map(function (size) {
41579             return function (rc) {
41580                 rc.updateAspect(size.width, size.height);
41581                 rc.updateProjection();
41582                 return rc;
41583             };
41584         })
41585             .subscribe(this._renderCameraOperation$);
41586         this._renderMode$
41587             .skip(1)
41588             .map(function (rm) {
41589             return function (rc) {
41590                 rc.renderMode = rm;
41591                 rc.updateProjection();
41592                 return rc;
41593             };
41594         })
41595             .subscribe(this._renderCameraOperation$);
41596         this._bearing$.subscribe(function () { });
41597         this._renderCameraHolder$.subscribe(function () { });
41598         this._size$.subscribe(function () { });
41599         this._renderMode$.subscribe(function () { });
41600         this._renderCamera$.subscribe(function () { });
41601         this._renderCameraFrame$.subscribe(function () { });
41602     }
41603     Object.defineProperty(RenderService.prototype, "bearing$", {
41604         get: function () {
41605             return this._bearing$;
41606         },
41607         enumerable: true,
41608         configurable: true
41609     });
41610     Object.defineProperty(RenderService.prototype, "element", {
41611         get: function () {
41612             return this._element;
41613         },
41614         enumerable: true,
41615         configurable: true
41616     });
41617     Object.defineProperty(RenderService.prototype, "resize$", {
41618         get: function () {
41619             return this._resize$;
41620         },
41621         enumerable: true,
41622         configurable: true
41623     });
41624     Object.defineProperty(RenderService.prototype, "size$", {
41625         get: function () {
41626             return this._size$;
41627         },
41628         enumerable: true,
41629         configurable: true
41630     });
41631     Object.defineProperty(RenderService.prototype, "renderMode$", {
41632         get: function () {
41633             return this._renderMode$;
41634         },
41635         enumerable: true,
41636         configurable: true
41637     });
41638     Object.defineProperty(RenderService.prototype, "renderCameraFrame$", {
41639         get: function () {
41640             return this._renderCameraFrame$;
41641         },
41642         enumerable: true,
41643         configurable: true
41644     });
41645     Object.defineProperty(RenderService.prototype, "renderCamera$", {
41646         get: function () {
41647             return this._renderCamera$;
41648         },
41649         enumerable: true,
41650         configurable: true
41651     });
41652     return RenderService;
41653 }());
41654 exports.RenderService = RenderService;
41655 exports.default = RenderService;
41656
41657 },{"../Geo":294,"../Render":297,"rxjs/BehaviorSubject":26,"rxjs/Subject":34,"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/do":61,"rxjs/add/operator/filter":63,"rxjs/add/operator/map":67,"rxjs/add/operator/publishReplay":74,"rxjs/add/operator/scan":78,"rxjs/add/operator/skip":80,"rxjs/add/operator/startWith":83,"rxjs/add/operator/withLatestFrom":90}],413:[function(require,module,exports){
41658 "use strict";
41659 Object.defineProperty(exports, "__esModule", { value: true });
41660 var State;
41661 (function (State) {
41662     State[State["Traversing"] = 0] = "Traversing";
41663     State[State["Waiting"] = 1] = "Waiting";
41664 })(State = exports.State || (exports.State = {}));
41665 exports.default = State;
41666
41667 },{}],414:[function(require,module,exports){
41668 "use strict";
41669 Object.defineProperty(exports, "__esModule", { value: true });
41670 var State_1 = require("../State");
41671 var Geo_1 = require("../Geo");
41672 var StateContext = /** @class */ (function () {
41673     function StateContext(transitionMode) {
41674         this._state = new State_1.TraversingState({
41675             alpha: 1,
41676             camera: new Geo_1.Camera(),
41677             currentIndex: -1,
41678             reference: { alt: 0, lat: 0, lon: 0 },
41679             trajectory: [],
41680             transitionMode: transitionMode == null ? State_1.TransitionMode.Default : transitionMode,
41681             zoom: 0,
41682         });
41683     }
41684     StateContext.prototype.traverse = function () {
41685         this._state = this._state.traverse();
41686     };
41687     StateContext.prototype.wait = function () {
41688         this._state = this._state.wait();
41689     };
41690     Object.defineProperty(StateContext.prototype, "state", {
41691         get: function () {
41692             if (this._state instanceof State_1.TraversingState) {
41693                 return State_1.State.Traversing;
41694             }
41695             else if (this._state instanceof State_1.WaitingState) {
41696                 return State_1.State.Waiting;
41697             }
41698             throw new Error("Invalid state");
41699         },
41700         enumerable: true,
41701         configurable: true
41702     });
41703     Object.defineProperty(StateContext.prototype, "reference", {
41704         get: function () {
41705             return this._state.reference;
41706         },
41707         enumerable: true,
41708         configurable: true
41709     });
41710     Object.defineProperty(StateContext.prototype, "alpha", {
41711         get: function () {
41712             return this._state.alpha;
41713         },
41714         enumerable: true,
41715         configurable: true
41716     });
41717     Object.defineProperty(StateContext.prototype, "camera", {
41718         get: function () {
41719             return this._state.camera;
41720         },
41721         enumerable: true,
41722         configurable: true
41723     });
41724     Object.defineProperty(StateContext.prototype, "zoom", {
41725         get: function () {
41726             return this._state.zoom;
41727         },
41728         enumerable: true,
41729         configurable: true
41730     });
41731     Object.defineProperty(StateContext.prototype, "currentNode", {
41732         get: function () {
41733             return this._state.currentNode;
41734         },
41735         enumerable: true,
41736         configurable: true
41737     });
41738     Object.defineProperty(StateContext.prototype, "previousNode", {
41739         get: function () {
41740             return this._state.previousNode;
41741         },
41742         enumerable: true,
41743         configurable: true
41744     });
41745     Object.defineProperty(StateContext.prototype, "currentCamera", {
41746         get: function () {
41747             return this._state.currentCamera;
41748         },
41749         enumerable: true,
41750         configurable: true
41751     });
41752     Object.defineProperty(StateContext.prototype, "currentTransform", {
41753         get: function () {
41754             return this._state.currentTransform;
41755         },
41756         enumerable: true,
41757         configurable: true
41758     });
41759     Object.defineProperty(StateContext.prototype, "previousTransform", {
41760         get: function () {
41761             return this._state.previousTransform;
41762         },
41763         enumerable: true,
41764         configurable: true
41765     });
41766     Object.defineProperty(StateContext.prototype, "trajectory", {
41767         get: function () {
41768             return this._state.trajectory;
41769         },
41770         enumerable: true,
41771         configurable: true
41772     });
41773     Object.defineProperty(StateContext.prototype, "currentIndex", {
41774         get: function () {
41775             return this._state.currentIndex;
41776         },
41777         enumerable: true,
41778         configurable: true
41779     });
41780     Object.defineProperty(StateContext.prototype, "lastNode", {
41781         get: function () {
41782             return this._state.trajectory[this._state.trajectory.length - 1];
41783         },
41784         enumerable: true,
41785         configurable: true
41786     });
41787     Object.defineProperty(StateContext.prototype, "nodesAhead", {
41788         get: function () {
41789             return this._state.trajectory.length - 1 - this._state.currentIndex;
41790         },
41791         enumerable: true,
41792         configurable: true
41793     });
41794     Object.defineProperty(StateContext.prototype, "motionless", {
41795         get: function () {
41796             return this._state.motionless;
41797         },
41798         enumerable: true,
41799         configurable: true
41800     });
41801     StateContext.prototype.getCenter = function () {
41802         return this._state.getCenter();
41803     };
41804     StateContext.prototype.setCenter = function (center) {
41805         this._state.setCenter(center);
41806     };
41807     StateContext.prototype.setZoom = function (zoom) {
41808         this._state.setZoom(zoom);
41809     };
41810     StateContext.prototype.update = function (fps) {
41811         this._state.update(fps);
41812     };
41813     StateContext.prototype.append = function (nodes) {
41814         this._state.append(nodes);
41815     };
41816     StateContext.prototype.prepend = function (nodes) {
41817         this._state.prepend(nodes);
41818     };
41819     StateContext.prototype.remove = function (n) {
41820         this._state.remove(n);
41821     };
41822     StateContext.prototype.clear = function () {
41823         this._state.clear();
41824     };
41825     StateContext.prototype.clearPrior = function () {
41826         this._state.clearPrior();
41827     };
41828     StateContext.prototype.cut = function () {
41829         this._state.cut();
41830     };
41831     StateContext.prototype.set = function (nodes) {
41832         this._state.set(nodes);
41833     };
41834     StateContext.prototype.rotate = function (delta) {
41835         this._state.rotate(delta);
41836     };
41837     StateContext.prototype.rotateBasic = function (basicRotation) {
41838         this._state.rotateBasic(basicRotation);
41839     };
41840     StateContext.prototype.rotateBasicUnbounded = function (basicRotation) {
41841         this._state.rotateBasicUnbounded(basicRotation);
41842     };
41843     StateContext.prototype.rotateBasicWithoutInertia = function (basicRotation) {
41844         this._state.rotateBasicWithoutInertia(basicRotation);
41845     };
41846     StateContext.prototype.rotateToBasic = function (basic) {
41847         this._state.rotateToBasic(basic);
41848     };
41849     StateContext.prototype.move = function (delta) {
41850         this._state.move(delta);
41851     };
41852     StateContext.prototype.moveTo = function (delta) {
41853         this._state.moveTo(delta);
41854     };
41855     StateContext.prototype.zoomIn = function (delta, reference) {
41856         this._state.zoomIn(delta, reference);
41857     };
41858     StateContext.prototype.setSpeed = function (speed) {
41859         this._state.setSpeed(speed);
41860     };
41861     StateContext.prototype.setTransitionMode = function (mode) {
41862         this._state.setTransitionMode(mode);
41863     };
41864     return StateContext;
41865 }());
41866 exports.StateContext = StateContext;
41867
41868 },{"../Geo":294,"../State":298}],415:[function(require,module,exports){
41869 "use strict";
41870 Object.defineProperty(exports, "__esModule", { value: true });
41871 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
41872 var Subject_1 = require("rxjs/Subject");
41873 var AnimationFrame_1 = require("rxjs/util/AnimationFrame");
41874 require("rxjs/add/operator/bufferCount");
41875 require("rxjs/add/operator/distinctUntilChanged");
41876 require("rxjs/add/operator/do");
41877 require("rxjs/add/operator/filter");
41878 require("rxjs/add/operator/first");
41879 require("rxjs/add/operator/map");
41880 require("rxjs/add/operator/pairwise");
41881 require("rxjs/add/operator/publishReplay");
41882 require("rxjs/add/operator/scan");
41883 require("rxjs/add/operator/startWith");
41884 require("rxjs/add/operator/switchMap");
41885 require("rxjs/add/operator/withLatestFrom");
41886 var State_1 = require("../State");
41887 var StateService = /** @class */ (function () {
41888     function StateService(transitionMode) {
41889         var _this = this;
41890         this._appendNode$ = new Subject_1.Subject();
41891         this._start$ = new Subject_1.Subject();
41892         this._frame$ = new Subject_1.Subject();
41893         this._fpsSampleRate = 30;
41894         this._contextOperation$ = new BehaviorSubject_1.BehaviorSubject(function (context) {
41895             return context;
41896         });
41897         this._context$ = this._contextOperation$
41898             .scan(function (context, operation) {
41899             return operation(context);
41900         }, new State_1.StateContext(transitionMode))
41901             .publishReplay(1)
41902             .refCount();
41903         this._state$ = this._context$
41904             .map(function (context) {
41905             return context.state;
41906         })
41907             .distinctUntilChanged()
41908             .publishReplay(1)
41909             .refCount();
41910         this._fps$ = this._start$
41911             .switchMap(function () {
41912             return _this._frame$
41913                 .bufferCount(1, _this._fpsSampleRate)
41914                 .map(function (frameIds) {
41915                 return new Date().getTime();
41916             })
41917                 .pairwise()
41918                 .map(function (times) {
41919                 return Math.max(20, 1000 * _this._fpsSampleRate / (times[1] - times[0]));
41920             })
41921                 .startWith(60);
41922         })
41923             .share();
41924         this._currentState$ = this._frame$
41925             .withLatestFrom(this._fps$, this._context$, function (frameId, fps, context) {
41926             return [frameId, fps, context];
41927         })
41928             .filter(function (fc) {
41929             return fc[2].currentNode != null;
41930         })
41931             .do(function (fc) {
41932             fc[2].update(fc[1]);
41933         })
41934             .map(function (fc) {
41935             return { fps: fc[1], id: fc[0], state: fc[2] };
41936         })
41937             .share();
41938         this._lastState$ = this._currentState$
41939             .publishReplay(1)
41940             .refCount();
41941         var nodeChanged$ = this._currentState$
41942             .distinctUntilChanged(undefined, function (f) {
41943             return f.state.currentNode.key;
41944         })
41945             .publishReplay(1)
41946             .refCount();
41947         var nodeChangedSubject$ = new Subject_1.Subject();
41948         nodeChanged$
41949             .subscribe(nodeChangedSubject$);
41950         this._currentKey$ = new BehaviorSubject_1.BehaviorSubject(null);
41951         nodeChangedSubject$
41952             .map(function (f) {
41953             return f.state.currentNode.key;
41954         })
41955             .subscribe(this._currentKey$);
41956         this._currentNode$ = nodeChangedSubject$
41957             .map(function (f) {
41958             return f.state.currentNode;
41959         })
41960             .publishReplay(1)
41961             .refCount();
41962         this._currentCamera$ = nodeChangedSubject$
41963             .map(function (f) {
41964             return f.state.currentCamera;
41965         })
41966             .publishReplay(1)
41967             .refCount();
41968         this._currentTransform$ = nodeChangedSubject$
41969             .map(function (f) {
41970             return f.state.currentTransform;
41971         })
41972             .publishReplay(1)
41973             .refCount();
41974         this._reference$ = nodeChangedSubject$
41975             .map(function (f) {
41976             return f.state.reference;
41977         })
41978             .distinctUntilChanged(function (r1, r2) {
41979             return r1.lat === r2.lat && r1.lon === r2.lon;
41980         }, function (reference) {
41981             return { lat: reference.lat, lon: reference.lon };
41982         })
41983             .publishReplay(1)
41984             .refCount();
41985         this._currentNodeExternal$ = nodeChanged$
41986             .map(function (f) {
41987             return f.state.currentNode;
41988         })
41989             .publishReplay(1)
41990             .refCount();
41991         this._appendNode$
41992             .map(function (node) {
41993             return function (context) {
41994                 context.append([node]);
41995                 return context;
41996             };
41997         })
41998             .subscribe(this._contextOperation$);
41999         this._inMotionOperation$ = new Subject_1.Subject();
42000         nodeChanged$
42001             .map(function (frame) {
42002             return true;
42003         })
42004             .subscribe(this._inMotionOperation$);
42005         this._inMotionOperation$
42006             .distinctUntilChanged()
42007             .filter(function (moving) {
42008             return moving;
42009         })
42010             .switchMap(function (moving) {
42011             return _this._currentState$
42012                 .filter(function (frame) {
42013                 return frame.state.nodesAhead === 0;
42014             })
42015                 .map(function (frame) {
42016                 return [frame.state.camera.clone(), frame.state.zoom];
42017             })
42018                 .pairwise()
42019                 .map(function (pair) {
42020                 var c1 = pair[0][0];
42021                 var c2 = pair[1][0];
42022                 var z1 = pair[0][1];
42023                 var z2 = pair[1][1];
42024                 return c1.diff(c2) > 1e-5 || Math.abs(z1 - z2) > 1e-5;
42025             })
42026                 .first(function (changed) {
42027                 return !changed;
42028             });
42029         })
42030             .subscribe(this._inMotionOperation$);
42031         this._inMotion$ = this._inMotionOperation$
42032             .distinctUntilChanged()
42033             .publishReplay(1)
42034             .refCount();
42035         this._inTranslationOperation$ = new Subject_1.Subject();
42036         nodeChanged$
42037             .map(function (frame) {
42038             return true;
42039         })
42040             .subscribe(this._inTranslationOperation$);
42041         this._inTranslationOperation$
42042             .distinctUntilChanged()
42043             .filter(function (inTranslation) {
42044             return inTranslation;
42045         })
42046             .switchMap(function (inTranslation) {
42047             return _this._currentState$
42048                 .filter(function (frame) {
42049                 return frame.state.nodesAhead === 0;
42050             })
42051                 .map(function (frame) {
42052                 return frame.state.camera.position.clone();
42053             })
42054                 .pairwise()
42055                 .map(function (pair) {
42056                 return pair[0].distanceToSquared(pair[1]) !== 0;
42057             })
42058                 .first(function (changed) {
42059                 return !changed;
42060             });
42061         })
42062             .subscribe(this._inTranslationOperation$);
42063         this._inTranslation$ = this._inTranslationOperation$
42064             .distinctUntilChanged()
42065             .publishReplay(1)
42066             .refCount();
42067         this._state$.subscribe(function () { });
42068         this._currentNode$.subscribe(function () { });
42069         this._currentCamera$.subscribe(function () { });
42070         this._currentTransform$.subscribe(function () { });
42071         this._reference$.subscribe(function () { });
42072         this._currentNodeExternal$.subscribe(function () { });
42073         this._lastState$.subscribe(function () { });
42074         this._inMotion$.subscribe(function () { });
42075         this._inTranslation$.subscribe(function () { });
42076         this._frameId = null;
42077         this._frameGenerator = new AnimationFrame_1.RequestAnimationFrameDefinition(window);
42078     }
42079     Object.defineProperty(StateService.prototype, "currentState$", {
42080         get: function () {
42081             return this._currentState$;
42082         },
42083         enumerable: true,
42084         configurable: true
42085     });
42086     Object.defineProperty(StateService.prototype, "currentNode$", {
42087         get: function () {
42088             return this._currentNode$;
42089         },
42090         enumerable: true,
42091         configurable: true
42092     });
42093     Object.defineProperty(StateService.prototype, "currentKey$", {
42094         get: function () {
42095             return this._currentKey$;
42096         },
42097         enumerable: true,
42098         configurable: true
42099     });
42100     Object.defineProperty(StateService.prototype, "currentNodeExternal$", {
42101         get: function () {
42102             return this._currentNodeExternal$;
42103         },
42104         enumerable: true,
42105         configurable: true
42106     });
42107     Object.defineProperty(StateService.prototype, "currentCamera$", {
42108         get: function () {
42109             return this._currentCamera$;
42110         },
42111         enumerable: true,
42112         configurable: true
42113     });
42114     Object.defineProperty(StateService.prototype, "currentTransform$", {
42115         get: function () {
42116             return this._currentTransform$;
42117         },
42118         enumerable: true,
42119         configurable: true
42120     });
42121     Object.defineProperty(StateService.prototype, "state$", {
42122         get: function () {
42123             return this._state$;
42124         },
42125         enumerable: true,
42126         configurable: true
42127     });
42128     Object.defineProperty(StateService.prototype, "reference$", {
42129         get: function () {
42130             return this._reference$;
42131         },
42132         enumerable: true,
42133         configurable: true
42134     });
42135     Object.defineProperty(StateService.prototype, "inMotion$", {
42136         get: function () {
42137             return this._inMotion$;
42138         },
42139         enumerable: true,
42140         configurable: true
42141     });
42142     Object.defineProperty(StateService.prototype, "inTranslation$", {
42143         get: function () {
42144             return this._inTranslation$;
42145         },
42146         enumerable: true,
42147         configurable: true
42148     });
42149     Object.defineProperty(StateService.prototype, "appendNode$", {
42150         get: function () {
42151             return this._appendNode$;
42152         },
42153         enumerable: true,
42154         configurable: true
42155     });
42156     StateService.prototype.traverse = function () {
42157         this._inMotionOperation$.next(true);
42158         this._invokeContextOperation(function (context) { context.traverse(); });
42159     };
42160     StateService.prototype.wait = function () {
42161         this._invokeContextOperation(function (context) { context.wait(); });
42162     };
42163     StateService.prototype.appendNodes = function (nodes) {
42164         this._invokeContextOperation(function (context) { context.append(nodes); });
42165     };
42166     StateService.prototype.prependNodes = function (nodes) {
42167         this._invokeContextOperation(function (context) { context.prepend(nodes); });
42168     };
42169     StateService.prototype.removeNodes = function (n) {
42170         this._invokeContextOperation(function (context) { context.remove(n); });
42171     };
42172     StateService.prototype.clearNodes = function () {
42173         this._invokeContextOperation(function (context) { context.clear(); });
42174     };
42175     StateService.prototype.clearPriorNodes = function () {
42176         this._invokeContextOperation(function (context) { context.clearPrior(); });
42177     };
42178     StateService.prototype.cutNodes = function () {
42179         this._invokeContextOperation(function (context) { context.cut(); });
42180     };
42181     StateService.prototype.setNodes = function (nodes) {
42182         this._invokeContextOperation(function (context) { context.set(nodes); });
42183     };
42184     StateService.prototype.rotate = function (delta) {
42185         this._inMotionOperation$.next(true);
42186         this._invokeContextOperation(function (context) { context.rotate(delta); });
42187     };
42188     StateService.prototype.rotateBasic = function (basicRotation) {
42189         this._inMotionOperation$.next(true);
42190         this._invokeContextOperation(function (context) { context.rotateBasic(basicRotation); });
42191     };
42192     StateService.prototype.rotateBasicUnbounded = function (basicRotation) {
42193         this._inMotionOperation$.next(true);
42194         this._invokeContextOperation(function (context) { context.rotateBasicUnbounded(basicRotation); });
42195     };
42196     StateService.prototype.rotateBasicWithoutInertia = function (basicRotation) {
42197         this._inMotionOperation$.next(true);
42198         this._invokeContextOperation(function (context) { context.rotateBasicWithoutInertia(basicRotation); });
42199     };
42200     StateService.prototype.rotateToBasic = function (basic) {
42201         this._inMotionOperation$.next(true);
42202         this._invokeContextOperation(function (context) { context.rotateToBasic(basic); });
42203     };
42204     StateService.prototype.move = function (delta) {
42205         this._inMotionOperation$.next(true);
42206         this._invokeContextOperation(function (context) { context.move(delta); });
42207     };
42208     StateService.prototype.moveTo = function (position) {
42209         this._inMotionOperation$.next(true);
42210         this._invokeContextOperation(function (context) { context.moveTo(position); });
42211     };
42212     /**
42213      * Change zoom level while keeping the reference point position approximately static.
42214      *
42215      * @parameter {number} delta - Change in zoom level.
42216      * @parameter {Array<number>} reference - Reference point in basic coordinates.
42217      */
42218     StateService.prototype.zoomIn = function (delta, reference) {
42219         this._inMotionOperation$.next(true);
42220         this._invokeContextOperation(function (context) { context.zoomIn(delta, reference); });
42221     };
42222     StateService.prototype.getCenter = function () {
42223         return this._lastState$
42224             .first()
42225             .map(function (frame) {
42226             return frame.state.getCenter();
42227         });
42228     };
42229     StateService.prototype.getZoom = function () {
42230         return this._lastState$
42231             .first()
42232             .map(function (frame) {
42233             return frame.state.zoom;
42234         });
42235     };
42236     StateService.prototype.setCenter = function (center) {
42237         this._inMotionOperation$.next(true);
42238         this._invokeContextOperation(function (context) { context.setCenter(center); });
42239     };
42240     StateService.prototype.setSpeed = function (speed) {
42241         this._invokeContextOperation(function (context) { context.setSpeed(speed); });
42242     };
42243     StateService.prototype.setTransitionMode = function (mode) {
42244         this._invokeContextOperation(function (context) { context.setTransitionMode(mode); });
42245     };
42246     StateService.prototype.setZoom = function (zoom) {
42247         this._inMotionOperation$.next(true);
42248         this._invokeContextOperation(function (context) { context.setZoom(zoom); });
42249     };
42250     StateService.prototype.start = function () {
42251         if (this._frameId == null) {
42252             this._start$.next(null);
42253             this._frameId = this._frameGenerator.requestAnimationFrame(this._frame.bind(this));
42254             this._frame$.next(this._frameId);
42255         }
42256     };
42257     StateService.prototype.stop = function () {
42258         if (this._frameId != null) {
42259             this._frameGenerator.cancelAnimationFrame(this._frameId);
42260             this._frameId = null;
42261         }
42262     };
42263     StateService.prototype._invokeContextOperation = function (action) {
42264         this._contextOperation$
42265             .next(function (context) {
42266             action(context);
42267             return context;
42268         });
42269     };
42270     StateService.prototype._frame = function (time) {
42271         this._frameId = this._frameGenerator.requestAnimationFrame(this._frame.bind(this));
42272         this._frame$.next(this._frameId);
42273     };
42274     return StateService;
42275 }());
42276 exports.StateService = StateService;
42277
42278 },{"../State":298,"rxjs/BehaviorSubject":26,"rxjs/Subject":34,"rxjs/add/operator/bufferCount":52,"rxjs/add/operator/distinctUntilChanged":60,"rxjs/add/operator/do":61,"rxjs/add/operator/filter":63,"rxjs/add/operator/first":65,"rxjs/add/operator/map":67,"rxjs/add/operator/pairwise":71,"rxjs/add/operator/publishReplay":74,"rxjs/add/operator/scan":78,"rxjs/add/operator/startWith":83,"rxjs/add/operator/switchMap":84,"rxjs/add/operator/withLatestFrom":90,"rxjs/util/AnimationFrame":218}],416:[function(require,module,exports){
42279 "use strict";
42280 Object.defineProperty(exports, "__esModule", { value: true });
42281 /**
42282  * Enumeration for transition mode
42283  * @enum {number}
42284  * @readonly
42285  * @description Modes for specifying how transitions
42286  * between nodes are performed.
42287  */
42288 var TransitionMode;
42289 (function (TransitionMode) {
42290     /**
42291      * Default transitions.
42292      *
42293      * @description The viewer dynamically determines
42294      * whether transitions should be performed with or
42295      * without motion and blending for each transition
42296      * based on the underlying data.
42297      */
42298     TransitionMode[TransitionMode["Default"] = 0] = "Default";
42299     /**
42300      * Instantaneous transitions.
42301      *
42302      * @description All transitions are performed
42303      * without motion or blending.
42304      */
42305     TransitionMode[TransitionMode["Instantaneous"] = 1] = "Instantaneous";
42306 })(TransitionMode = exports.TransitionMode || (exports.TransitionMode = {}));
42307 exports.default = TransitionMode;
42308
42309 },{}],417:[function(require,module,exports){
42310 "use strict";
42311 /// <reference path="../../../typings/index.d.ts" />
42312 Object.defineProperty(exports, "__esModule", { value: true });
42313 var Error_1 = require("../../Error");
42314 var Geo_1 = require("../../Geo");
42315 var State_1 = require("../../State");
42316 var StateBase = /** @class */ (function () {
42317     function StateBase(state) {
42318         this._spatial = new Geo_1.Spatial();
42319         this._geoCoords = new Geo_1.GeoCoords();
42320         this._referenceThreshold = 0.01;
42321         this._transitionMode = state.transitionMode;
42322         this._reference = state.reference;
42323         this._alpha = state.alpha;
42324         this._camera = state.camera.clone();
42325         this._zoom = state.zoom;
42326         this._currentIndex = state.currentIndex;
42327         this._trajectory = state.trajectory.slice();
42328         this._trajectoryTransforms = [];
42329         this._trajectoryCameras = [];
42330         for (var _i = 0, _a = this._trajectory; _i < _a.length; _i++) {
42331             var node = _a[_i];
42332             var translation = this._nodeToTranslation(node);
42333             var transform = new Geo_1.Transform(node, node.image, translation);
42334             this._trajectoryTransforms.push(transform);
42335             this._trajectoryCameras.push(new Geo_1.Camera(transform));
42336         }
42337         this._currentNode = this._trajectory.length > 0 ?
42338             this._trajectory[this._currentIndex] :
42339             null;
42340         this._previousNode = this._trajectory.length > 1 && this.currentIndex > 0 ?
42341             this._trajectory[this._currentIndex - 1] :
42342             null;
42343         this._currentCamera = this._trajectoryCameras.length > 0 ?
42344             this._trajectoryCameras[this._currentIndex].clone() :
42345             new Geo_1.Camera();
42346         this._previousCamera = this._trajectoryCameras.length > 1 && this.currentIndex > 0 ?
42347             this._trajectoryCameras[this._currentIndex - 1].clone() :
42348             this._currentCamera.clone();
42349     }
42350     Object.defineProperty(StateBase.prototype, "reference", {
42351         get: function () {
42352             return this._reference;
42353         },
42354         enumerable: true,
42355         configurable: true
42356     });
42357     Object.defineProperty(StateBase.prototype, "alpha", {
42358         get: function () {
42359             return this._getAlpha();
42360         },
42361         enumerable: true,
42362         configurable: true
42363     });
42364     Object.defineProperty(StateBase.prototype, "camera", {
42365         get: function () {
42366             return this._camera;
42367         },
42368         enumerable: true,
42369         configurable: true
42370     });
42371     Object.defineProperty(StateBase.prototype, "zoom", {
42372         get: function () {
42373             return this._zoom;
42374         },
42375         enumerable: true,
42376         configurable: true
42377     });
42378     Object.defineProperty(StateBase.prototype, "trajectory", {
42379         get: function () {
42380             return this._trajectory;
42381         },
42382         enumerable: true,
42383         configurable: true
42384     });
42385     Object.defineProperty(StateBase.prototype, "currentIndex", {
42386         get: function () {
42387             return this._currentIndex;
42388         },
42389         enumerable: true,
42390         configurable: true
42391     });
42392     Object.defineProperty(StateBase.prototype, "currentNode", {
42393         get: function () {
42394             return this._currentNode;
42395         },
42396         enumerable: true,
42397         configurable: true
42398     });
42399     Object.defineProperty(StateBase.prototype, "previousNode", {
42400         get: function () {
42401             return this._previousNode;
42402         },
42403         enumerable: true,
42404         configurable: true
42405     });
42406     Object.defineProperty(StateBase.prototype, "currentCamera", {
42407         get: function () {
42408             return this._currentCamera;
42409         },
42410         enumerable: true,
42411         configurable: true
42412     });
42413     Object.defineProperty(StateBase.prototype, "currentTransform", {
42414         get: function () {
42415             return this._trajectoryTransforms.length > 0 ?
42416                 this._trajectoryTransforms[this.currentIndex] : null;
42417         },
42418         enumerable: true,
42419         configurable: true
42420     });
42421     Object.defineProperty(StateBase.prototype, "previousTransform", {
42422         get: function () {
42423             return this._trajectoryTransforms.length > 1 && this.currentIndex > 0 ?
42424                 this._trajectoryTransforms[this.currentIndex - 1] : null;
42425         },
42426         enumerable: true,
42427         configurable: true
42428     });
42429     Object.defineProperty(StateBase.prototype, "motionless", {
42430         get: function () {
42431             return this._motionless;
42432         },
42433         enumerable: true,
42434         configurable: true
42435     });
42436     Object.defineProperty(StateBase.prototype, "transitionMode", {
42437         get: function () {
42438             return this._transitionMode;
42439         },
42440         enumerable: true,
42441         configurable: true
42442     });
42443     StateBase.prototype.append = function (nodes) {
42444         if (nodes.length < 1) {
42445             throw Error("Trajectory can not be empty");
42446         }
42447         if (this._currentIndex < 0) {
42448             this.set(nodes);
42449         }
42450         else {
42451             this._trajectory = this._trajectory.concat(nodes);
42452             this._appendToTrajectories(nodes);
42453         }
42454     };
42455     StateBase.prototype.prepend = function (nodes) {
42456         if (nodes.length < 1) {
42457             throw Error("Trajectory can not be empty");
42458         }
42459         this._trajectory = nodes.slice().concat(this._trajectory);
42460         this._currentIndex += nodes.length;
42461         this._setCurrentNode();
42462         var referenceReset = this._setReference(this._currentNode);
42463         if (referenceReset) {
42464             this._setTrajectories();
42465         }
42466         else {
42467             this._prependToTrajectories(nodes);
42468         }
42469         this._setCurrentCamera();
42470     };
42471     StateBase.prototype.remove = function (n) {
42472         if (n < 0) {
42473             throw Error("n must be a positive integer");
42474         }
42475         if (this._currentIndex - 1 < n) {
42476             throw Error("Current and previous nodes can not be removed");
42477         }
42478         for (var i = 0; i < n; i++) {
42479             this._trajectory.shift();
42480             this._trajectoryTransforms.shift();
42481             this._trajectoryCameras.shift();
42482             this._currentIndex--;
42483         }
42484         this._setCurrentNode();
42485     };
42486     StateBase.prototype.clearPrior = function () {
42487         if (this._currentIndex > 0) {
42488             this.remove(this._currentIndex - 1);
42489         }
42490     };
42491     StateBase.prototype.clear = function () {
42492         this.cut();
42493         if (this._currentIndex > 0) {
42494             this.remove(this._currentIndex - 1);
42495         }
42496     };
42497     StateBase.prototype.cut = function () {
42498         while (this._trajectory.length - 1 > this._currentIndex) {
42499             this._trajectory.pop();
42500             this._trajectoryTransforms.pop();
42501             this._trajectoryCameras.pop();
42502         }
42503     };
42504     StateBase.prototype.set = function (nodes) {
42505         this._setTrajectory(nodes);
42506         this._setCurrentNode();
42507         this._setReference(this._currentNode);
42508         this._setTrajectories();
42509         this._setCurrentCamera();
42510     };
42511     StateBase.prototype.getCenter = function () {
42512         return this._currentNode != null ?
42513             this.currentTransform.projectBasic(this._camera.lookat.toArray()) :
42514             [0.5, 0.5];
42515     };
42516     StateBase.prototype.setTransitionMode = function (mode) {
42517         this._transitionMode = mode;
42518     };
42519     StateBase.prototype._setCurrent = function () {
42520         this._setCurrentNode();
42521         var referenceReset = this._setReference(this._currentNode);
42522         if (referenceReset) {
42523             this._setTrajectories();
42524         }
42525         this._setCurrentCamera();
42526     };
42527     StateBase.prototype._setCurrentCamera = function () {
42528         this._currentCamera = this._trajectoryCameras[this._currentIndex].clone();
42529         this._previousCamera = this._currentIndex > 0 ?
42530             this._trajectoryCameras[this._currentIndex - 1].clone() :
42531             this._currentCamera.clone();
42532     };
42533     StateBase.prototype._motionlessTransition = function () {
42534         var nodesSet = this._currentNode != null && this._previousNode != null;
42535         return nodesSet && (this._transitionMode === State_1.TransitionMode.Instantaneous || !(this._currentNode.merged &&
42536             this._previousNode.merged &&
42537             this._withinOriginalDistance() &&
42538             this._sameConnectedComponent()));
42539     };
42540     StateBase.prototype._setReference = function (node) {
42541         // do not reset reference if node is within threshold distance
42542         if (Math.abs(node.latLon.lat - this.reference.lat) < this._referenceThreshold &&
42543             Math.abs(node.latLon.lon - this.reference.lon) < this._referenceThreshold) {
42544             return false;
42545         }
42546         // do not reset reference if previous node exist and transition is with motion
42547         if (this._previousNode != null && !this._motionlessTransition()) {
42548             return false;
42549         }
42550         this._reference.lat = node.latLon.lat;
42551         this._reference.lon = node.latLon.lon;
42552         this._reference.alt = node.alt;
42553         return true;
42554     };
42555     StateBase.prototype._setCurrentNode = function () {
42556         this._currentNode = this._trajectory.length > 0 ?
42557             this._trajectory[this._currentIndex] :
42558             null;
42559         this._previousNode = this._currentIndex > 0 ?
42560             this._trajectory[this._currentIndex - 1] :
42561             null;
42562     };
42563     StateBase.prototype._setTrajectory = function (nodes) {
42564         if (nodes.length < 1) {
42565             throw new Error_1.ArgumentMapillaryError("Trajectory can not be empty");
42566         }
42567         if (this._currentNode != null) {
42568             this._trajectory = [this._currentNode].concat(nodes);
42569             this._currentIndex = 1;
42570         }
42571         else {
42572             this._trajectory = nodes.slice();
42573             this._currentIndex = 0;
42574         }
42575     };
42576     StateBase.prototype._setTrajectories = function () {
42577         this._trajectoryTransforms.length = 0;
42578         this._trajectoryCameras.length = 0;
42579         this._appendToTrajectories(this._trajectory);
42580     };
42581     StateBase.prototype._appendToTrajectories = function (nodes) {
42582         for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
42583             var node = nodes_1[_i];
42584             if (!node.assetsCached) {
42585                 throw new Error_1.ArgumentMapillaryError("Assets must be cached when node is added to trajectory");
42586             }
42587             var translation = this._nodeToTranslation(node);
42588             var transform = new Geo_1.Transform(node, node.image, translation);
42589             this._trajectoryTransforms.push(transform);
42590             this._trajectoryCameras.push(new Geo_1.Camera(transform));
42591         }
42592     };
42593     StateBase.prototype._prependToTrajectories = function (nodes) {
42594         for (var _i = 0, _a = nodes.reverse(); _i < _a.length; _i++) {
42595             var node = _a[_i];
42596             if (!node.assetsCached) {
42597                 throw new Error_1.ArgumentMapillaryError("Assets must be cached when added to trajectory");
42598             }
42599             var translation = this._nodeToTranslation(node);
42600             var transform = new Geo_1.Transform(node, node.image, translation);
42601             this._trajectoryTransforms.unshift(transform);
42602             this._trajectoryCameras.unshift(new Geo_1.Camera(transform));
42603         }
42604     };
42605     StateBase.prototype._nodeToTranslation = function (node) {
42606         var C = this._geoCoords.geodeticToEnu(node.latLon.lat, node.latLon.lon, node.alt, this._reference.lat, this._reference.lon, this._reference.alt);
42607         var RC = this._spatial.rotate(C, node.rotation);
42608         return [-RC.x, -RC.y, -RC.z];
42609     };
42610     StateBase.prototype._sameConnectedComponent = function () {
42611         var current = this._currentNode;
42612         var previous = this._previousNode;
42613         if (!current ||
42614             !current.mergeCC ||
42615             !previous ||
42616             !previous.mergeCC) {
42617             return true;
42618         }
42619         return current.mergeCC === previous.mergeCC;
42620     };
42621     StateBase.prototype._withinOriginalDistance = function () {
42622         var current = this._currentNode;
42623         var previous = this._previousNode;
42624         if (!current || !previous) {
42625             return true;
42626         }
42627         // 50 km/h moves 28m in 2s
42628         var distance = this._spatial.distanceFromLatLon(current.originalLatLon.lat, current.originalLatLon.lon, previous.originalLatLon.lat, previous.originalLatLon.lon);
42629         return distance < 25;
42630     };
42631     return StateBase;
42632 }());
42633 exports.StateBase = StateBase;
42634
42635 },{"../../Error":293,"../../Geo":294,"../../State":298}],418:[function(require,module,exports){
42636 "use strict";
42637 /// <reference path="../../../typings/index.d.ts" />
42638 var __extends = (this && this.__extends) || (function () {
42639     var extendStatics = Object.setPrototypeOf ||
42640         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
42641         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
42642     return function (d, b) {
42643         extendStatics(d, b);
42644         function __() { this.constructor = d; }
42645         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
42646     };
42647 })();
42648 Object.defineProperty(exports, "__esModule", { value: true });
42649 var THREE = require("three");
42650 var UnitBezier = require("@mapbox/unitbezier");
42651 var State_1 = require("../../State");
42652 var RotationDelta = /** @class */ (function () {
42653     function RotationDelta(phi, theta) {
42654         this._phi = phi;
42655         this._theta = theta;
42656     }
42657     Object.defineProperty(RotationDelta.prototype, "phi", {
42658         get: function () {
42659             return this._phi;
42660         },
42661         set: function (value) {
42662             this._phi = value;
42663         },
42664         enumerable: true,
42665         configurable: true
42666     });
42667     Object.defineProperty(RotationDelta.prototype, "theta", {
42668         get: function () {
42669             return this._theta;
42670         },
42671         set: function (value) {
42672             this._theta = value;
42673         },
42674         enumerable: true,
42675         configurable: true
42676     });
42677     Object.defineProperty(RotationDelta.prototype, "isZero", {
42678         get: function () {
42679             return this._phi === 0 && this._theta === 0;
42680         },
42681         enumerable: true,
42682         configurable: true
42683     });
42684     RotationDelta.prototype.copy = function (delta) {
42685         this._phi = delta.phi;
42686         this._theta = delta.theta;
42687     };
42688     RotationDelta.prototype.lerp = function (other, alpha) {
42689         this._phi = (1 - alpha) * this._phi + alpha * other.phi;
42690         this._theta = (1 - alpha) * this._theta + alpha * other.theta;
42691     };
42692     RotationDelta.prototype.multiply = function (value) {
42693         this._phi *= value;
42694         this._theta *= value;
42695     };
42696     RotationDelta.prototype.threshold = function (value) {
42697         this._phi = Math.abs(this._phi) > value ? this._phi : 0;
42698         this._theta = Math.abs(this._theta) > value ? this._theta : 0;
42699     };
42700     RotationDelta.prototype.lengthSquared = function () {
42701         return this._phi * this._phi + this._theta * this._theta;
42702     };
42703     RotationDelta.prototype.reset = function () {
42704         this._phi = 0;
42705         this._theta = 0;
42706     };
42707     return RotationDelta;
42708 }());
42709 var TraversingState = /** @class */ (function (_super) {
42710     __extends(TraversingState, _super);
42711     function TraversingState(state) {
42712         var _this = _super.call(this, state) || this;
42713         _this._adjustCameras();
42714         _this._motionless = _this._motionlessTransition();
42715         _this._baseAlpha = _this._alpha;
42716         _this._animationSpeed = 1 / 40;
42717         _this._speedCoefficient = 1;
42718         _this._unitBezier = new UnitBezier(0.74, 0.67, 0.38, 0.96);
42719         _this._useBezier = false;
42720         _this._rotationDelta = new RotationDelta(0, 0);
42721         _this._requestedRotationDelta = null;
42722         _this._basicRotation = [0, 0];
42723         _this._requestedBasicRotation = null;
42724         _this._requestedBasicRotationUnbounded = null;
42725         _this._rotationAcceleration = 0.86;
42726         _this._rotationIncreaseAlpha = 0.97;
42727         _this._rotationDecreaseAlpha = 0.9;
42728         _this._rotationThreshold = 1e-3;
42729         _this._unboundedRotationAlpha = 0.8;
42730         _this._desiredZoom = state.zoom;
42731         _this._minZoom = 0;
42732         _this._maxZoom = 3;
42733         _this._lookatDepth = 10;
42734         _this._desiredLookat = null;
42735         _this._desiredCenter = null;
42736         return _this;
42737     }
42738     TraversingState.prototype.traverse = function () {
42739         throw new Error("Not implemented");
42740     };
42741     TraversingState.prototype.wait = function () {
42742         return new State_1.WaitingState(this);
42743     };
42744     TraversingState.prototype.append = function (nodes) {
42745         var emptyTrajectory = this._trajectory.length === 0;
42746         if (emptyTrajectory) {
42747             this._resetTransition();
42748         }
42749         _super.prototype.append.call(this, nodes);
42750         if (emptyTrajectory) {
42751             this._setDesiredCenter();
42752             this._setDesiredZoom();
42753         }
42754     };
42755     TraversingState.prototype.prepend = function (nodes) {
42756         var emptyTrajectory = this._trajectory.length === 0;
42757         if (emptyTrajectory) {
42758             this._resetTransition();
42759         }
42760         _super.prototype.prepend.call(this, nodes);
42761         if (emptyTrajectory) {
42762             this._setDesiredCenter();
42763             this._setDesiredZoom();
42764         }
42765     };
42766     TraversingState.prototype.set = function (nodes) {
42767         _super.prototype.set.call(this, nodes);
42768         this._desiredLookat = null;
42769         this._resetTransition();
42770         this._clearRotation();
42771         this._setDesiredCenter();
42772         this._setDesiredZoom();
42773         if (this._trajectory.length < 3) {
42774             this._useBezier = true;
42775         }
42776     };
42777     TraversingState.prototype.move = function (delta) {
42778         throw new Error("Not implemented");
42779     };
42780     TraversingState.prototype.moveTo = function (delta) {
42781         throw new Error("Not implemented");
42782     };
42783     TraversingState.prototype.rotate = function (rotationDelta) {
42784         if (this._currentNode == null) {
42785             return;
42786         }
42787         this._desiredZoom = this._zoom;
42788         this._desiredLookat = null;
42789         this._requestedBasicRotation = null;
42790         if (this._requestedRotationDelta != null) {
42791             this._requestedRotationDelta.phi = this._requestedRotationDelta.phi + rotationDelta.phi;
42792             this._requestedRotationDelta.theta = this._requestedRotationDelta.theta + rotationDelta.theta;
42793         }
42794         else {
42795             this._requestedRotationDelta = new RotationDelta(rotationDelta.phi, rotationDelta.theta);
42796         }
42797     };
42798     TraversingState.prototype.rotateBasic = function (basicRotation) {
42799         if (this._currentNode == null) {
42800             return;
42801         }
42802         this._desiredZoom = this._zoom;
42803         this._desiredLookat = null;
42804         this._requestedRotationDelta = null;
42805         if (this._requestedBasicRotation != null) {
42806             this._requestedBasicRotation[0] += basicRotation[0];
42807             this._requestedBasicRotation[1] += basicRotation[1];
42808             var threshold = 0.05 / Math.pow(2, this._zoom);
42809             this._requestedBasicRotation[0] =
42810                 this._spatial.clamp(this._requestedBasicRotation[0], -threshold, threshold);
42811             this._requestedBasicRotation[1] =
42812                 this._spatial.clamp(this._requestedBasicRotation[1], -threshold, threshold);
42813         }
42814         else {
42815             this._requestedBasicRotation = basicRotation.slice();
42816         }
42817     };
42818     TraversingState.prototype.rotateBasicUnbounded = function (basicRotation) {
42819         if (this._currentNode == null) {
42820             return;
42821         }
42822         if (this._requestedBasicRotationUnbounded != null) {
42823             this._requestedBasicRotationUnbounded[0] += basicRotation[0];
42824             this._requestedBasicRotationUnbounded[1] += basicRotation[1];
42825         }
42826         else {
42827             this._requestedBasicRotationUnbounded = basicRotation.slice();
42828         }
42829     };
42830     TraversingState.prototype.rotateBasicWithoutInertia = function (basic) {
42831         if (this._currentNode == null) {
42832             return;
42833         }
42834         this._desiredZoom = this._zoom;
42835         this._desiredLookat = null;
42836         this._requestedRotationDelta = null;
42837         this._requestedBasicRotation = null;
42838         var threshold = 0.05 / Math.pow(2, this._zoom);
42839         var basicRotation = basic.slice();
42840         basicRotation[0] = this._spatial.clamp(basicRotation[0], -threshold, threshold);
42841         basicRotation[1] = this._spatial.clamp(basicRotation[1], -threshold, threshold);
42842         this._applyRotationBasic(basicRotation);
42843     };
42844     TraversingState.prototype.rotateToBasic = function (basic) {
42845         if (this._currentNode == null) {
42846             return;
42847         }
42848         this._desiredZoom = this._zoom;
42849         this._desiredLookat = null;
42850         basic[0] = this._spatial.clamp(basic[0], 0, 1);
42851         basic[1] = this._spatial.clamp(basic[1], 0, 1);
42852         var lookat = this.currentTransform.unprojectBasic(basic, this._lookatDepth);
42853         this._currentCamera.lookat.fromArray(lookat);
42854     };
42855     TraversingState.prototype.setSpeed = function (speed) {
42856         this._speedCoefficient = this._spatial.clamp(speed, 0, 10);
42857     };
42858     TraversingState.prototype.zoomIn = function (delta, reference) {
42859         if (this._currentNode == null) {
42860             return;
42861         }
42862         this._desiredZoom = Math.max(this._minZoom, Math.min(this._maxZoom, this._desiredZoom + delta));
42863         var currentCenter = this.currentTransform.projectBasic(this._currentCamera.lookat.toArray());
42864         var currentCenterX = currentCenter[0];
42865         var currentCenterY = currentCenter[1];
42866         var zoom0 = Math.pow(2, this._zoom);
42867         var zoom1 = Math.pow(2, this._desiredZoom);
42868         var refX = reference[0];
42869         var refY = reference[1];
42870         if (this.currentTransform.gpano != null &&
42871             this.currentTransform.gpano.CroppedAreaImageWidthPixels === this.currentTransform.gpano.FullPanoWidthPixels) {
42872             if (refX - currentCenterX > 0.5) {
42873                 refX = refX - 1;
42874             }
42875             else if (currentCenterX - refX > 0.5) {
42876                 refX = 1 + refX;
42877             }
42878         }
42879         var newCenterX = refX - zoom0 / zoom1 * (refX - currentCenterX);
42880         var newCenterY = refY - zoom0 / zoom1 * (refY - currentCenterY);
42881         var gpano = this.currentTransform.gpano;
42882         if (this._currentNode.fullPano) {
42883             newCenterX = this._spatial.wrap(newCenterX + this._basicRotation[0], 0, 1);
42884             newCenterY = this._spatial.clamp(newCenterY + this._basicRotation[1], 0.05, 0.95);
42885         }
42886         else if (gpano != null &&
42887             this.currentTransform.gpano.CroppedAreaImageWidthPixels === this.currentTransform.gpano.FullPanoWidthPixels) {
42888             newCenterX = this._spatial.wrap(newCenterX + this._basicRotation[0], 0, 1);
42889             newCenterY = this._spatial.clamp(newCenterY + this._basicRotation[1], 0, 1);
42890         }
42891         else {
42892             newCenterX = this._spatial.clamp(newCenterX, 0, 1);
42893             newCenterY = this._spatial.clamp(newCenterY, 0, 1);
42894         }
42895         this._desiredLookat = new THREE.Vector3()
42896             .fromArray(this.currentTransform.unprojectBasic([newCenterX, newCenterY], this._lookatDepth));
42897     };
42898     TraversingState.prototype.setCenter = function (center) {
42899         this._desiredLookat = null;
42900         this._requestedRotationDelta = null;
42901         this._requestedBasicRotation = null;
42902         this._desiredZoom = this._zoom;
42903         var clamped = [
42904             this._spatial.clamp(center[0], 0, 1),
42905             this._spatial.clamp(center[1], 0, 1),
42906         ];
42907         if (this._currentNode == null) {
42908             this._desiredCenter = clamped;
42909             return;
42910         }
42911         this._desiredCenter = null;
42912         var currentLookat = new THREE.Vector3()
42913             .fromArray(this.currentTransform.unprojectBasic(clamped, this._lookatDepth));
42914         var previousTransform = this.previousTransform != null ?
42915             this.previousTransform :
42916             this.currentTransform;
42917         var previousLookat = new THREE.Vector3()
42918             .fromArray(previousTransform.unprojectBasic(clamped, this._lookatDepth));
42919         this._currentCamera.lookat.copy(currentLookat);
42920         this._previousCamera.lookat.copy(previousLookat);
42921     };
42922     TraversingState.prototype.setZoom = function (zoom) {
42923         this._desiredLookat = null;
42924         this._requestedRotationDelta = null;
42925         this._requestedBasicRotation = null;
42926         this._zoom = this._spatial.clamp(zoom, this._minZoom, this._maxZoom);
42927         this._desiredZoom = this._zoom;
42928     };
42929     TraversingState.prototype.update = function (fps) {
42930         if (this._alpha === 1 && this._currentIndex + this._alpha < this._trajectory.length) {
42931             this._currentIndex += 1;
42932             this._useBezier = this._trajectory.length < 3 &&
42933                 this._currentIndex + 1 === this._trajectory.length;
42934             this._setCurrent();
42935             this._resetTransition();
42936             this._clearRotation();
42937             this._desiredZoom = this._currentNode.fullPano ? this._zoom : 0;
42938             this._desiredLookat = null;
42939         }
42940         var animationSpeed = this._animationSpeed * (60 / fps);
42941         this._baseAlpha = Math.min(1, this._baseAlpha + this._speedCoefficient * animationSpeed);
42942         if (this._useBezier) {
42943             this._alpha = this._unitBezier.solve(this._baseAlpha);
42944         }
42945         else {
42946             this._alpha = this._baseAlpha;
42947         }
42948         this._updateRotation();
42949         if (!this._rotationDelta.isZero) {
42950             this._applyRotation(this._previousCamera);
42951             this._applyRotation(this._currentCamera);
42952         }
42953         this._updateRotationBasic();
42954         if (this._basicRotation[0] !== 0 || this._basicRotation[1] !== 0) {
42955             this._applyRotationBasic(this._basicRotation);
42956         }
42957         this._updateZoom(animationSpeed);
42958         this._updateLookat(animationSpeed);
42959         this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha);
42960     };
42961     TraversingState.prototype._getAlpha = function () {
42962         return this._motionless ? Math.ceil(this._alpha) : this._alpha;
42963     };
42964     TraversingState.prototype._setCurrentCamera = function () {
42965         _super.prototype._setCurrentCamera.call(this);
42966         this._adjustCameras();
42967     };
42968     TraversingState.prototype._adjustCameras = function () {
42969         if (this._previousNode == null) {
42970             return;
42971         }
42972         var lookat = this._camera.lookat.clone().sub(this._camera.position);
42973         this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position));
42974         if (this._currentNode.fullPano) {
42975             this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position));
42976         }
42977     };
42978     TraversingState.prototype._resetTransition = function () {
42979         this._alpha = 0;
42980         this._baseAlpha = 0;
42981         this._motionless = this._motionlessTransition();
42982     };
42983     TraversingState.prototype._applyRotation = function (camera) {
42984         if (camera == null) {
42985             return;
42986         }
42987         var q = new THREE.Quaternion().setFromUnitVectors(camera.up, new THREE.Vector3(0, 0, 1));
42988         var qInverse = q.clone().inverse();
42989         var offset = new THREE.Vector3();
42990         offset.copy(camera.lookat).sub(camera.position);
42991         offset.applyQuaternion(q);
42992         var length = offset.length();
42993         var phi = Math.atan2(offset.y, offset.x);
42994         phi += this._rotationDelta.phi;
42995         var theta = Math.atan2(Math.sqrt(offset.x * offset.x + offset.y * offset.y), offset.z);
42996         theta += this._rotationDelta.theta;
42997         theta = Math.max(0.1, Math.min(Math.PI - 0.1, theta));
42998         offset.x = Math.sin(theta) * Math.cos(phi);
42999         offset.y = Math.sin(theta) * Math.sin(phi);
43000         offset.z = Math.cos(theta);
43001         offset.applyQuaternion(qInverse);
43002         camera.lookat.copy(camera.position).add(offset.multiplyScalar(length));
43003     };
43004     TraversingState.prototype._applyRotationBasic = function (basicRotation) {
43005         var currentNode = this._currentNode;
43006         var previousNode = this._previousNode != null ?
43007             this.previousNode :
43008             this.currentNode;
43009         var currentCamera = this._currentCamera;
43010         var previousCamera = this._previousCamera;
43011         var currentTransform = this.currentTransform;
43012         var previousTransform = this.previousTransform != null ?
43013             this.previousTransform :
43014             this.currentTransform;
43015         var currentBasic = currentTransform.projectBasic(currentCamera.lookat.toArray());
43016         var previousBasic = previousTransform.projectBasic(previousCamera.lookat.toArray());
43017         var currentGPano = currentTransform.gpano;
43018         var previousGPano = previousTransform.gpano;
43019         if (currentNode.fullPano) {
43020             currentBasic[0] = this._spatial.wrap(currentBasic[0] + basicRotation[0], 0, 1);
43021             currentBasic[1] = this._spatial.clamp(currentBasic[1] + basicRotation[1], 0.05, 0.95);
43022         }
43023         else if (currentGPano != null &&
43024             currentTransform.gpano.CroppedAreaImageWidthPixels === currentTransform.gpano.FullPanoWidthPixels) {
43025             currentBasic[0] = this._spatial.wrap(currentBasic[0] + basicRotation[0], 0, 1);
43026             currentBasic[1] = this._spatial.clamp(currentBasic[1] + basicRotation[1], 0, 1);
43027         }
43028         else {
43029             currentBasic[0] = this._spatial.clamp(currentBasic[0] + basicRotation[0], 0, 1);
43030             currentBasic[1] = this._spatial.clamp(currentBasic[1] + basicRotation[1], 0, 1);
43031         }
43032         if (previousNode.fullPano) {
43033             previousBasic[0] = this._spatial.wrap(previousBasic[0] + basicRotation[0], 0, 1);
43034             previousBasic[1] = this._spatial.clamp(previousBasic[1] + basicRotation[1], 0.05, 0.95);
43035         }
43036         else if (previousGPano != null &&
43037             previousTransform.gpano.CroppedAreaImageWidthPixels === previousTransform.gpano.FullPanoWidthPixels) {
43038             previousBasic[0] = this._spatial.wrap(previousBasic[0] + basicRotation[0], 0, 1);
43039             previousBasic[1] = this._spatial.clamp(previousBasic[1] + basicRotation[1], 0, 1);
43040         }
43041         else {
43042             previousBasic[0] = this._spatial.clamp(previousBasic[0] + basicRotation[0], 0, 1);
43043             previousBasic[1] = this._spatial.clamp(currentBasic[1] + basicRotation[1], 0, 1);
43044         }
43045         var currentLookat = currentTransform.unprojectBasic(currentBasic, this._lookatDepth);
43046         currentCamera.lookat.fromArray(currentLookat);
43047         var previousLookat = previousTransform.unprojectBasic(previousBasic, this._lookatDepth);
43048         previousCamera.lookat.fromArray(previousLookat);
43049     };
43050     TraversingState.prototype._updateZoom = function (animationSpeed) {
43051         var diff = this._desiredZoom - this._zoom;
43052         var sign = diff > 0 ? 1 : diff < 0 ? -1 : 0;
43053         if (diff === 0) {
43054             return;
43055         }
43056         else if (Math.abs(diff) < 2e-3) {
43057             this._zoom = this._desiredZoom;
43058             if (this._desiredLookat != null) {
43059                 this._desiredLookat = null;
43060             }
43061         }
43062         else {
43063             this._zoom += sign * Math.max(Math.abs(5 * animationSpeed * diff), 2e-3);
43064         }
43065     };
43066     TraversingState.prototype._updateLookat = function (animationSpeed) {
43067         if (this._desiredLookat === null) {
43068             return;
43069         }
43070         var diff = this._desiredLookat.distanceToSquared(this._currentCamera.lookat);
43071         if (Math.abs(diff) < 1e-6) {
43072             this._currentCamera.lookat.copy(this._desiredLookat);
43073             this._desiredLookat = null;
43074         }
43075         else {
43076             this._currentCamera.lookat.lerp(this._desiredLookat, 5 * animationSpeed);
43077         }
43078     };
43079     TraversingState.prototype._updateRotation = function () {
43080         if (this._requestedRotationDelta != null) {
43081             var length_1 = this._rotationDelta.lengthSquared();
43082             var requestedLength = this._requestedRotationDelta.lengthSquared();
43083             if (requestedLength > length_1) {
43084                 this._rotationDelta.lerp(this._requestedRotationDelta, this._rotationIncreaseAlpha);
43085             }
43086             else {
43087                 this._rotationDelta.lerp(this._requestedRotationDelta, this._rotationDecreaseAlpha);
43088             }
43089             this._requestedRotationDelta = null;
43090             return;
43091         }
43092         if (this._rotationDelta.isZero) {
43093             return;
43094         }
43095         this._rotationDelta.multiply(this._rotationAcceleration);
43096         this._rotationDelta.threshold(this._rotationThreshold);
43097     };
43098     TraversingState.prototype._updateRotationBasic = function () {
43099         if (this._requestedBasicRotation != null) {
43100             var x = this._basicRotation[0];
43101             var y = this._basicRotation[1];
43102             var reqX = this._requestedBasicRotation[0];
43103             var reqY = this._requestedBasicRotation[1];
43104             if (Math.abs(reqX) > Math.abs(x)) {
43105                 this._basicRotation[0] = (1 - this._rotationIncreaseAlpha) * x + this._rotationIncreaseAlpha * reqX;
43106             }
43107             else {
43108                 this._basicRotation[0] = (1 - this._rotationDecreaseAlpha) * x + this._rotationDecreaseAlpha * reqX;
43109             }
43110             if (Math.abs(reqY) > Math.abs(y)) {
43111                 this._basicRotation[1] = (1 - this._rotationIncreaseAlpha) * y + this._rotationIncreaseAlpha * reqY;
43112             }
43113             else {
43114                 this._basicRotation[1] = (1 - this._rotationDecreaseAlpha) * y + this._rotationDecreaseAlpha * reqY;
43115             }
43116             this._requestedBasicRotation = null;
43117             return;
43118         }
43119         if (this._requestedBasicRotationUnbounded != null) {
43120             var reqX = this._requestedBasicRotationUnbounded[0];
43121             var reqY = this._requestedBasicRotationUnbounded[1];
43122             if (Math.abs(reqX) > 0) {
43123                 this._basicRotation[0] = (1 - this._unboundedRotationAlpha) * this._basicRotation[0] + this._unboundedRotationAlpha * reqX;
43124             }
43125             if (Math.abs(reqY) > 0) {
43126                 this._basicRotation[1] = (1 - this._unboundedRotationAlpha) * this._basicRotation[1] + this._unboundedRotationAlpha * reqY;
43127             }
43128             if (this._desiredLookat != null) {
43129                 var desiredBasicLookat = this.currentTransform.projectBasic(this._desiredLookat.toArray());
43130                 desiredBasicLookat[0] += reqX;
43131                 desiredBasicLookat[1] += reqY;
43132                 this._desiredLookat = new THREE.Vector3()
43133                     .fromArray(this.currentTransform.unprojectBasic(desiredBasicLookat, this._lookatDepth));
43134             }
43135             this._requestedBasicRotationUnbounded = null;
43136         }
43137         if (this._basicRotation[0] === 0 && this._basicRotation[1] === 0) {
43138             return;
43139         }
43140         this._basicRotation[0] = this._rotationAcceleration * this._basicRotation[0];
43141         this._basicRotation[1] = this._rotationAcceleration * this._basicRotation[1];
43142         if (Math.abs(this._basicRotation[0]) < this._rotationThreshold / Math.pow(2, this._zoom) &&
43143             Math.abs(this._basicRotation[1]) < this._rotationThreshold / Math.pow(2, this._zoom)) {
43144             this._basicRotation = [0, 0];
43145         }
43146     };
43147     TraversingState.prototype._clearRotation = function () {
43148         if (this._currentNode.fullPano) {
43149             return;
43150         }
43151         if (this._requestedRotationDelta != null) {
43152             this._requestedRotationDelta = null;
43153         }
43154         if (!this._rotationDelta.isZero) {
43155             this._rotationDelta.reset();
43156         }
43157         if (this._requestedBasicRotation != null) {
43158             this._requestedBasicRotation = null;
43159         }
43160         if (this._basicRotation[0] > 0 || this._basicRotation[1] > 0) {
43161             this._basicRotation = [0, 0];
43162         }
43163     };
43164     TraversingState.prototype._setDesiredCenter = function () {
43165         if (this._desiredCenter == null) {
43166             return;
43167         }
43168         var lookatDirection = new THREE.Vector3()
43169             .fromArray(this.currentTransform.unprojectBasic(this._desiredCenter, this._lookatDepth))
43170             .sub(this._currentCamera.position);
43171         this._currentCamera.lookat.copy(this._currentCamera.position.clone().add(lookatDirection));
43172         this._previousCamera.lookat.copy(this._previousCamera.position.clone().add(lookatDirection));
43173         this._desiredCenter = null;
43174     };
43175     TraversingState.prototype._setDesiredZoom = function () {
43176         this._desiredZoom =
43177             this._currentNode.fullPano || this._previousNode == null ?
43178                 this._zoom : 0;
43179     };
43180     return TraversingState;
43181 }(State_1.StateBase));
43182 exports.TraversingState = TraversingState;
43183
43184 },{"../../State":298,"@mapbox/unitbezier":2,"three":241}],419:[function(require,module,exports){
43185 "use strict";
43186 var __extends = (this && this.__extends) || (function () {
43187     var extendStatics = Object.setPrototypeOf ||
43188         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
43189         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
43190     return function (d, b) {
43191         extendStatics(d, b);
43192         function __() { this.constructor = d; }
43193         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
43194     };
43195 })();
43196 Object.defineProperty(exports, "__esModule", { value: true });
43197 var State_1 = require("../../State");
43198 var WaitingState = /** @class */ (function (_super) {
43199     __extends(WaitingState, _super);
43200     function WaitingState(state) {
43201         var _this = _super.call(this, state) || this;
43202         _this._zoom = 0;
43203         _this._adjustCameras();
43204         _this._motionless = _this._motionlessTransition();
43205         return _this;
43206     }
43207     WaitingState.prototype.traverse = function () {
43208         return new State_1.TraversingState(this);
43209     };
43210     WaitingState.prototype.wait = function () {
43211         throw new Error("Not implemented");
43212     };
43213     WaitingState.prototype.prepend = function (nodes) {
43214         _super.prototype.prepend.call(this, nodes);
43215         this._motionless = this._motionlessTransition();
43216     };
43217     WaitingState.prototype.set = function (nodes) {
43218         _super.prototype.set.call(this, nodes);
43219         this._motionless = this._motionlessTransition();
43220     };
43221     WaitingState.prototype.rotate = function (delta) { return; };
43222     WaitingState.prototype.rotateBasic = function (basicRotation) { return; };
43223     WaitingState.prototype.rotateBasicUnbounded = function (basicRotation) { return; };
43224     WaitingState.prototype.rotateBasicWithoutInertia = function (basicRotation) { return; };
43225     WaitingState.prototype.rotateToBasic = function (basic) { return; };
43226     WaitingState.prototype.setSpeed = function (speed) { return; };
43227     WaitingState.prototype.zoomIn = function (delta, reference) { return; };
43228     WaitingState.prototype.move = function (delta) {
43229         this._alpha = Math.max(0, Math.min(1, this._alpha + delta));
43230     };
43231     WaitingState.prototype.moveTo = function (position) {
43232         this._alpha = Math.max(0, Math.min(1, position));
43233     };
43234     WaitingState.prototype.update = function (fps) {
43235         this._camera.lerpCameras(this._previousCamera, this._currentCamera, this.alpha);
43236     };
43237     WaitingState.prototype.setCenter = function (center) { return; };
43238     WaitingState.prototype.setZoom = function (zoom) { return; };
43239     WaitingState.prototype._getAlpha = function () {
43240         return this._motionless ? Math.round(this._alpha) : this._alpha;
43241     };
43242     WaitingState.prototype._setCurrentCamera = function () {
43243         _super.prototype._setCurrentCamera.call(this);
43244         this._adjustCameras();
43245     };
43246     WaitingState.prototype._adjustCameras = function () {
43247         if (this._previousNode == null) {
43248             return;
43249         }
43250         if (this._currentNode.fullPano) {
43251             var lookat = this._camera.lookat.clone().sub(this._camera.position);
43252             this._currentCamera.lookat.copy(lookat.clone().add(this._currentCamera.position));
43253         }
43254         if (this._previousNode.fullPano) {
43255             var lookat = this._currentCamera.lookat.clone().sub(this._currentCamera.position);
43256             this._previousCamera.lookat.copy(lookat.clone().add(this._previousCamera.position));
43257         }
43258     };
43259     return WaitingState;
43260 }(State_1.StateBase));
43261 exports.WaitingState = WaitingState;
43262
43263 },{"../../State":298}],420:[function(require,module,exports){
43264 "use strict";
43265 Object.defineProperty(exports, "__esModule", { value: true });
43266 var Observable_1 = require("rxjs/Observable");
43267 /**
43268  * @class ImageTileLoader
43269  *
43270  * @classdesc Represents a loader of image tiles.
43271  */
43272 var ImageTileLoader = /** @class */ (function () {
43273     /**
43274      * Create a new node image tile loader instance.
43275      *
43276      * @param {string} scheme - The URI scheme.
43277      * @param {string} host - The URI host.
43278      * @param {string} [origin] - The origin query param.
43279      */
43280     function ImageTileLoader(scheme, host, origin) {
43281         this._scheme = scheme;
43282         this._host = host;
43283         this._origin = origin != null ? "?origin=" + origin : "";
43284     }
43285     /**
43286      * Retrieve an image tile.
43287      *
43288      * @description Retrieve an image tile by specifying the area
43289      * as well as the scaled size.
43290      *
43291      * @param {string} identifier - The identifier of the image.
43292      * @param {number} x - The top left x pixel coordinate for the tile
43293      * in the original image.
43294      * @param {number} y - The top left y pixel coordinate for the tile
43295      * in the original image.
43296      * @param {number} w - The pixel width of the tile in the original image.
43297      * @param {number} h - The pixel height of the tile in the original image.
43298      * @param {number} scaledW - The scaled width of the returned tile.
43299      * @param {number} scaledH - The scaled height of the returned tile.
43300      */
43301     ImageTileLoader.prototype.getTile = function (identifier, x, y, w, h, scaledW, scaledH) {
43302         var characteristics = "/" + identifier + "/" + x + "," + y + "," + w + "," + h + "/" + scaledW + "," + scaledH + "/0/default.jpg";
43303         var url = this._scheme +
43304             "://" +
43305             this._host +
43306             characteristics +
43307             this._origin;
43308         var xmlHTTP = null;
43309         return [Observable_1.Observable.create(function (subscriber) {
43310                 xmlHTTP = new XMLHttpRequest();
43311                 xmlHTTP.open("GET", url, true);
43312                 xmlHTTP.responseType = "arraybuffer";
43313                 xmlHTTP.timeout = 15000;
43314                 xmlHTTP.onload = function (event) {
43315                     if (xmlHTTP.status !== 200) {
43316                         subscriber.error(new Error("Failed to fetch tile (" + identifier + ": " + x + "," + y + "," + w + "," + h + "). " +
43317                             ("Status: " + xmlHTTP.status + ", " + xmlHTTP.statusText)));
43318                         return;
43319                     }
43320                     var image = new Image();
43321                     image.crossOrigin = "Anonymous";
43322                     image.onload = function (e) {
43323                         subscriber.next(image);
43324                         subscriber.complete();
43325                     };
43326                     image.onerror = function (error) {
43327                         subscriber.error(new Error("Failed to load tile image (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
43328                     };
43329                     var blob = new Blob([xmlHTTP.response]);
43330                     image.src = window.URL.createObjectURL(blob);
43331                 };
43332                 xmlHTTP.onerror = function (error) {
43333                     subscriber.error(new Error("Failed to fetch tile (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
43334                 };
43335                 xmlHTTP.ontimeout = function (error) {
43336                     subscriber.error(new Error("Tile request timed out (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
43337                 };
43338                 xmlHTTP.onabort = function (event) {
43339                     subscriber.error(new Error("Tile request was aborted (" + identifier + ": " + x + "," + y + "," + w + "," + h + ")"));
43340                 };
43341                 xmlHTTP.send(null);
43342             }),
43343             function () {
43344                 if (xmlHTTP != null) {
43345                     xmlHTTP.abort();
43346                 }
43347             },
43348         ];
43349     };
43350     return ImageTileLoader;
43351 }());
43352 exports.ImageTileLoader = ImageTileLoader;
43353 exports.default = ImageTileLoader;
43354
43355 },{"rxjs/Observable":29}],421:[function(require,module,exports){
43356 "use strict";
43357 Object.defineProperty(exports, "__esModule", { value: true });
43358 /**
43359  * @class ImageTileStore
43360  *
43361  * @classdesc Represents a store for image tiles.
43362  */
43363 var ImageTileStore = /** @class */ (function () {
43364     /**
43365      * Create a new node image tile store instance.
43366      */
43367     function ImageTileStore() {
43368         this._images = {};
43369     }
43370     /**
43371      * Add an image tile to the store.
43372      *
43373      * @param {HTMLImageElement} image - The image tile.
43374      * @param {string} key - The identifier for the tile.
43375      * @param {number} level - The level of the tile.
43376      */
43377     ImageTileStore.prototype.addImage = function (image, key, level) {
43378         if (!(level in this._images)) {
43379             this._images[level] = {};
43380         }
43381         this._images[level][key] = image;
43382     };
43383     /**
43384      * Dispose the store.
43385      *
43386      * @description Disposes all cached assets.
43387      */
43388     ImageTileStore.prototype.dispose = function () {
43389         for (var _i = 0, _a = Object.keys(this._images); _i < _a.length; _i++) {
43390             var level = _a[_i];
43391             var levelImages = this._images[level];
43392             for (var _b = 0, _c = Object.keys(levelImages); _b < _c.length; _b++) {
43393                 var key = _c[_b];
43394                 window.URL.revokeObjectURL(levelImages[key].src);
43395                 delete levelImages[key];
43396             }
43397             delete this._images[level];
43398         }
43399     };
43400     /**
43401      * Get an image tile from the store.
43402      *
43403      * @param {string} key - The identifier for the tile.
43404      * @param {number} level - The level of the tile.
43405      */
43406     ImageTileStore.prototype.getImage = function (key, level) {
43407         return this._images[level][key];
43408     };
43409     /**
43410      * Check if an image tile exist in the store.
43411      *
43412      * @param {string} key - The identifier for the tile.
43413      * @param {number} level - The level of the tile.
43414      */
43415     ImageTileStore.prototype.hasImage = function (key, level) {
43416         return level in this._images && key in this._images[level];
43417     };
43418     return ImageTileStore;
43419 }());
43420 exports.ImageTileStore = ImageTileStore;
43421 exports.default = ImageTileStore;
43422
43423 },{}],422:[function(require,module,exports){
43424 "use strict";
43425 /// <reference path="../../typings/index.d.ts" />
43426 Object.defineProperty(exports, "__esModule", { value: true });
43427 var Geo_1 = require("../Geo");
43428 /**
43429  * @class RegionOfInterestCalculator
43430  *
43431  * @classdesc Represents a calculator for regions of interest.
43432  */
43433 var RegionOfInterestCalculator = /** @class */ (function () {
43434     function RegionOfInterestCalculator() {
43435         this._viewportCoords = new Geo_1.ViewportCoords();
43436     }
43437     /**
43438      * Compute a region of interest based on the current render camera
43439      * and the viewport size.
43440      *
43441      * @param {RenderCamera} renderCamera - Render camera used for unprojections.
43442      * @param {ISize} size - Viewport size in pixels.
43443      * @param {Transform} transform - Transform used for projections.
43444      *
43445      * @returns {IRegionOfInterest} A region of interest.
43446      */
43447     RegionOfInterestCalculator.prototype.computeRegionOfInterest = function (renderCamera, size, transform) {
43448         var viewportBoundaryPoints = this._viewportBoundaryPoints(4);
43449         var bbox = this._viewportPointsBoundingBox(viewportBoundaryPoints, renderCamera, transform);
43450         this._clipBoundingBox(bbox);
43451         var viewportPixelWidth = 2 / size.width;
43452         var viewportPixelHeight = 2 / size.height;
43453         var centralViewportPixel = [
43454             [-0.5 * viewportPixelWidth, 0.5 * viewportPixelHeight],
43455             [0.5 * viewportPixelWidth, 0.5 * viewportPixelHeight],
43456             [0.5 * viewportPixelWidth, -0.5 * viewportPixelHeight],
43457             [-0.5 * viewportPixelWidth, -0.5 * viewportPixelHeight],
43458         ];
43459         var cpbox = this._viewportPointsBoundingBox(centralViewportPixel, renderCamera, transform);
43460         return {
43461             bbox: bbox,
43462             pixelHeight: cpbox.maxY - cpbox.minY,
43463             pixelWidth: cpbox.maxX - cpbox.minX + (cpbox.minX < cpbox.maxX ? 0 : 1),
43464         };
43465     };
43466     RegionOfInterestCalculator.prototype._viewportBoundaryPoints = function (pointsPerSide) {
43467         var points = [];
43468         var os = [[-1, 1], [1, 1], [1, -1], [-1, -1]];
43469         var ds = [[2, 0], [0, -2], [-2, 0], [0, 2]];
43470         for (var side = 0; side < 4; ++side) {
43471             var o = os[side];
43472             var d = ds[side];
43473             for (var i = 0; i < pointsPerSide; ++i) {
43474                 points.push([o[0] + d[0] * i / pointsPerSide,
43475                     o[1] + d[1] * i / pointsPerSide]);
43476             }
43477         }
43478         return points;
43479     };
43480     RegionOfInterestCalculator.prototype._viewportPointsBoundingBox = function (viewportPoints, renderCamera, transform) {
43481         var _this = this;
43482         var basicPoints = viewportPoints
43483             .map(function (point) {
43484             return _this._viewportCoords
43485                 .viewportToBasic(point[0], point[1], transform, renderCamera.perspective);
43486         });
43487         if (transform.gpano != null) {
43488             return this._boundingBoxPano(basicPoints);
43489         }
43490         else {
43491             return this._boundingBox(basicPoints);
43492         }
43493     };
43494     RegionOfInterestCalculator.prototype._boundingBox = function (points) {
43495         var bbox = {
43496             maxX: Number.NEGATIVE_INFINITY,
43497             maxY: Number.NEGATIVE_INFINITY,
43498             minX: Number.POSITIVE_INFINITY,
43499             minY: Number.POSITIVE_INFINITY,
43500         };
43501         for (var i = 0; i < points.length; ++i) {
43502             bbox.minX = Math.min(bbox.minX, points[i][0]);
43503             bbox.maxX = Math.max(bbox.maxX, points[i][0]);
43504             bbox.minY = Math.min(bbox.minY, points[i][1]);
43505             bbox.maxY = Math.max(bbox.maxY, points[i][1]);
43506         }
43507         return bbox;
43508     };
43509     RegionOfInterestCalculator.prototype._boundingBoxPano = function (points) {
43510         var _this = this;
43511         var xs = [];
43512         var ys = [];
43513         for (var i = 0; i < points.length; ++i) {
43514             xs.push(points[i][0]);
43515             ys.push(points[i][1]);
43516         }
43517         xs.sort(function (a, b) { return _this._sign(a - b); });
43518         ys.sort(function (a, b) { return _this._sign(a - b); });
43519         var intervalX = this._intervalPano(xs);
43520         return {
43521             maxX: intervalX[1],
43522             maxY: ys[ys.length - 1],
43523             minX: intervalX[0],
43524             minY: ys[0],
43525         };
43526     };
43527     /**
43528      * Find the max interval between consecutive numbers.
43529      * Assumes numbers are between 0 and 1, sorted and that
43530      * x is equivalent to x + 1.
43531      */
43532     RegionOfInterestCalculator.prototype._intervalPano = function (xs) {
43533         var maxdx = 0;
43534         var maxi = -1;
43535         for (var i = 0; i < xs.length - 1; ++i) {
43536             var dx = xs[i + 1] - xs[i];
43537             if (dx > maxdx) {
43538                 maxdx = dx;
43539                 maxi = i;
43540             }
43541         }
43542         var loopdx = xs[0] + 1 - xs[xs.length - 1];
43543         if (loopdx > maxdx) {
43544             return [xs[0], xs[xs.length - 1]];
43545         }
43546         else {
43547             return [xs[maxi + 1], xs[maxi]];
43548         }
43549     };
43550     RegionOfInterestCalculator.prototype._clipBoundingBox = function (bbox) {
43551         bbox.minX = Math.max(0, Math.min(1, bbox.minX));
43552         bbox.maxX = Math.max(0, Math.min(1, bbox.maxX));
43553         bbox.minY = Math.max(0, Math.min(1, bbox.minY));
43554         bbox.maxY = Math.max(0, Math.min(1, bbox.maxY));
43555     };
43556     RegionOfInterestCalculator.prototype._sign = function (n) {
43557         return n > 0 ? 1 : n < 0 ? -1 : 0;
43558     };
43559     return RegionOfInterestCalculator;
43560 }());
43561 exports.RegionOfInterestCalculator = RegionOfInterestCalculator;
43562 exports.default = RegionOfInterestCalculator;
43563
43564 },{"../Geo":294}],423:[function(require,module,exports){
43565 "use strict";
43566 /// <reference path="../../typings/index.d.ts" />
43567 Object.defineProperty(exports, "__esModule", { value: true });
43568 var THREE = require("three");
43569 var Subject_1 = require("rxjs/Subject");
43570 /**
43571  * @class TextureProvider
43572  *
43573  * @classdesc Represents a provider of textures.
43574  */
43575 var TextureProvider = /** @class */ (function () {
43576     /**
43577      * Create a new node texture provider instance.
43578      *
43579      * @param {string} key - The identifier of the image for which to request tiles.
43580      * @param {number} width - The full width of the original image.
43581      * @param {number} height - The full height of the original image.
43582      * @param {number} tileSize - The size used when requesting tiles.
43583      * @param {HTMLImageElement} background - Image to use as background.
43584      * @param {ImageTileLoader} imageTileLoader - Loader for retrieving tiles.
43585      * @param {ImageTileStore} imageTileStore - Store for saving tiles.
43586      * @param {THREE.WebGLRenderer} renderer - Renderer used for rendering tiles to texture.
43587      */
43588     function TextureProvider(key, width, height, tileSize, background, imageTileLoader, imageTileStore, renderer) {
43589         this._disposed = false;
43590         this._key = key;
43591         if (width <= 0 || height <= 0) {
43592             console.warn("Original image size (" + width + ", " + height + ") is invalid (" + key + "). Tiles will not be loaded.");
43593         }
43594         this._width = width;
43595         this._height = height;
43596         this._maxLevel = Math.ceil(Math.log(Math.max(height, width)) / Math.log(2));
43597         this._currentLevel = -1;
43598         this._tileSize = tileSize;
43599         this._updated$ = new Subject_1.Subject();
43600         this._createdSubject$ = new Subject_1.Subject();
43601         this._created$ = this._createdSubject$
43602             .publishReplay(1)
43603             .refCount();
43604         this._createdSubscription = this._created$.subscribe(function () { });
43605         this._hasSubject$ = new Subject_1.Subject();
43606         this._has$ = this._hasSubject$
43607             .startWith(false)
43608             .publishReplay(1)
43609             .refCount();
43610         this._hasSubscription = this._has$.subscribe(function () { });
43611         this._abortFunctions = [];
43612         this._tileSubscriptions = {};
43613         this._renderedCurrentLevelTiles = {};
43614         this._renderedTiles = {};
43615         this._background = background;
43616         this._camera = null;
43617         this._imageTileLoader = imageTileLoader;
43618         this._imageTileStore = imageTileStore;
43619         this._renderer = renderer;
43620         this._renderTarget = null;
43621         this._roi = null;
43622     }
43623     Object.defineProperty(TextureProvider.prototype, "disposed", {
43624         /**
43625          * Get disposed.
43626          *
43627          * @returns {boolean} Value indicating whether provider has
43628          * been disposed.
43629          */
43630         get: function () {
43631             return this._disposed;
43632         },
43633         enumerable: true,
43634         configurable: true
43635     });
43636     Object.defineProperty(TextureProvider.prototype, "hasTexture$", {
43637         /**
43638          * Get hasTexture$.
43639          *
43640          * @returns {Observable<boolean>} Observable emitting
43641          * values indicating when the existance of a texture
43642          * changes.
43643          */
43644         get: function () {
43645             return this._has$;
43646         },
43647         enumerable: true,
43648         configurable: true
43649     });
43650     Object.defineProperty(TextureProvider.prototype, "key", {
43651         /**
43652          * Get key.
43653          *
43654          * @returns {boolean} The identifier of the image for
43655          * which to render textures.
43656          */
43657         get: function () {
43658             return this._key;
43659         },
43660         enumerable: true,
43661         configurable: true
43662     });
43663     Object.defineProperty(TextureProvider.prototype, "textureUpdated$", {
43664         /**
43665          * Get textureUpdated$.
43666          *
43667          * @returns {Observable<boolean>} Observable emitting
43668          * values when an existing texture has been updated.
43669          */
43670         get: function () {
43671             return this._updated$;
43672         },
43673         enumerable: true,
43674         configurable: true
43675     });
43676     Object.defineProperty(TextureProvider.prototype, "textureCreated$", {
43677         /**
43678          * Get textureCreated$.
43679          *
43680          * @returns {Observable<boolean>} Observable emitting
43681          * values when a new texture has been created.
43682          */
43683         get: function () {
43684             return this._created$;
43685         },
43686         enumerable: true,
43687         configurable: true
43688     });
43689     /**
43690      * Abort all outstanding image tile requests.
43691      */
43692     TextureProvider.prototype.abort = function () {
43693         for (var key in this._tileSubscriptions) {
43694             if (!this._tileSubscriptions.hasOwnProperty(key)) {
43695                 continue;
43696             }
43697             this._tileSubscriptions[key].unsubscribe();
43698         }
43699         this._tileSubscriptions = {};
43700         for (var _i = 0, _a = this._abortFunctions; _i < _a.length; _i++) {
43701             var abort = _a[_i];
43702             abort();
43703         }
43704         this._abortFunctions = [];
43705     };
43706     /**
43707      * Dispose the provider.
43708      *
43709      * @description Disposes all cached assets and
43710      * aborts all outstanding image tile requests.
43711      */
43712     TextureProvider.prototype.dispose = function () {
43713         if (this._disposed) {
43714             console.warn("Texture already disposed (" + this._key + ")");
43715             return;
43716         }
43717         this.abort();
43718         if (this._renderTarget != null) {
43719             this._renderTarget.dispose();
43720             this._renderTarget = null;
43721         }
43722         this._imageTileStore.dispose();
43723         this._imageTileStore = null;
43724         this._background = null;
43725         this._camera = null;
43726         this._imageTileLoader = null;
43727         this._renderer = null;
43728         this._roi = null;
43729         this._createdSubscription.unsubscribe();
43730         this._hasSubscription.unsubscribe();
43731         this._disposed = true;
43732     };
43733     /**
43734      * Set the region of interest.
43735      *
43736      * @description When the region of interest is set the
43737      * the tile level is determined and tiles for the region
43738      * are fetched from the store or the loader and renderedLevel
43739      * to the texture.
43740      *
43741      * @param {IRegionOfInterest} roi - Spatial edges to cache.
43742      */
43743     TextureProvider.prototype.setRegionOfInterest = function (roi) {
43744         if (this._width <= 0 || this._height <= 0) {
43745             return;
43746         }
43747         this._roi = roi;
43748         var width = 1 / this._roi.pixelWidth;
43749         var height = 1 / this._roi.pixelHeight;
43750         var size = Math.max(height, width);
43751         var currentLevel = Math.max(0, Math.min(this._maxLevel, Math.ceil(Math.log(size) / Math.log(2))));
43752         if (currentLevel !== this._currentLevel) {
43753             this.abort();
43754             this._currentLevel = currentLevel;
43755             if (!(this._currentLevel in this._renderedTiles)) {
43756                 this._renderedTiles[this._currentLevel] = [];
43757             }
43758             this._renderedCurrentLevelTiles = {};
43759             for (var _i = 0, _a = this._renderedTiles[this._currentLevel]; _i < _a.length; _i++) {
43760                 var tile = _a[_i];
43761                 this._renderedCurrentLevelTiles[this._tileKey(this._tileSize, tile)] = true;
43762             }
43763         }
43764         var topLeft = this._getTileCoords([this._roi.bbox.minX, this._roi.bbox.minY]);
43765         var bottomRight = this._getTileCoords([this._roi.bbox.maxX, this._roi.bbox.maxY]);
43766         var tiles = this._getTiles(topLeft, bottomRight);
43767         if (this._camera == null) {
43768             this._camera = new THREE.OrthographicCamera(-this._width / 2, this._width / 2, this._height / 2, -this._height / 2, -1, 1);
43769             this._camera.position.z = 1;
43770             var gl = this._renderer.getContext();
43771             var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
43772             var backgroundSize = Math.max(this._width, this._height);
43773             var scale = maxTextureSize > backgroundSize ? 1 : maxTextureSize / backgroundSize;
43774             var targetWidth = Math.floor(scale * this._width);
43775             var targetHeight = Math.floor(scale * this._height);
43776             this._renderTarget = new THREE.WebGLRenderTarget(targetWidth, targetHeight, {
43777                 depthBuffer: false,
43778                 format: THREE.RGBFormat,
43779                 magFilter: THREE.LinearFilter,
43780                 minFilter: THREE.LinearFilter,
43781                 stencilBuffer: false,
43782             });
43783             this._renderToTarget(0, 0, this._width, this._height, this._background);
43784             this._createdSubject$.next(this._renderTarget.texture);
43785             this._hasSubject$.next(true);
43786         }
43787         this._fetchTiles(tiles);
43788     };
43789     TextureProvider.prototype.setTileSize = function (tileSize) {
43790         this._tileSize = tileSize;
43791     };
43792     /**
43793      * Update the image used as background for the texture.
43794      *
43795      * @param {HTMLImageElement} background - The background image.
43796      */
43797     TextureProvider.prototype.updateBackground = function (background) {
43798         this._background = background;
43799     };
43800     /**
43801      * Retrieve an image tile.
43802      *
43803      * @description Retrieve an image tile and render it to the
43804      * texture. Add the tile to the store and emit to the updated
43805      * observable.
43806      *
43807      * @param {Array<number>} tile - The tile coordinates.
43808      * @param {number} level - The tile level.
43809      * @param {number} x - The top left x pixel coordinate of the tile.
43810      * @param {number} y - The top left y pixel coordinate of the tile.
43811      * @param {number} w - The pixel width of the tile.
43812      * @param {number} h - The pixel height of the tile.
43813      * @param {number} scaledW - The scaled width of the returned tile.
43814      * @param {number} scaledH - The scaled height of the returned tile.
43815      */
43816     TextureProvider.prototype._fetchTile = function (tile, level, x, y, w, h, scaledX, scaledY) {
43817         var _this = this;
43818         var getTile = this._imageTileLoader.getTile(this._key, x, y, w, h, scaledX, scaledY);
43819         var tile$ = getTile[0];
43820         var abort = getTile[1];
43821         this._abortFunctions.push(abort);
43822         var tileKey = this._tileKey(this._tileSize, tile);
43823         var subscription = tile$
43824             .subscribe(function (image) {
43825             _this._renderToTarget(x, y, w, h, image);
43826             _this._removeFromDictionary(tileKey, _this._tileSubscriptions);
43827             _this._removeFromArray(abort, _this._abortFunctions);
43828             _this._setTileRendered(tile, _this._currentLevel);
43829             _this._imageTileStore.addImage(image, tileKey, level);
43830             _this._updated$.next(true);
43831         }, function (error) {
43832             _this._removeFromDictionary(tileKey, _this._tileSubscriptions);
43833             _this._removeFromArray(abort, _this._abortFunctions);
43834             console.error(error);
43835         });
43836         if (!subscription.closed) {
43837             this._tileSubscriptions[tileKey] = subscription;
43838         }
43839     };
43840     /**
43841      * Retrieve image tiles.
43842      *
43843      * @description Retrieve a image tiles and render them to the
43844      * texture. Retrieve from store if it exists, otherwise Retrieve
43845      * from loader.
43846      *
43847      * @param {Array<Array<number>>} tiles - Array of tile coordinates to
43848      * retrieve.
43849      */
43850     TextureProvider.prototype._fetchTiles = function (tiles) {
43851         var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
43852         for (var _i = 0, tiles_1 = tiles; _i < tiles_1.length; _i++) {
43853             var tile = tiles_1[_i];
43854             var tileKey = this._tileKey(this._tileSize, tile);
43855             if (tileKey in this._renderedCurrentLevelTiles ||
43856                 tileKey in this._tileSubscriptions) {
43857                 continue;
43858             }
43859             var tileX = tileSize * tile[0];
43860             var tileY = tileSize * tile[1];
43861             var tileWidth = tileX + tileSize > this._width ? this._width - tileX : tileSize;
43862             var tileHeight = tileY + tileSize > this._height ? this._height - tileY : tileSize;
43863             if (this._imageTileStore.hasImage(tileKey, this._currentLevel)) {
43864                 this._renderToTarget(tileX, tileY, tileWidth, tileHeight, this._imageTileStore.getImage(tileKey, this._currentLevel));
43865                 this._setTileRendered(tile, this._currentLevel);
43866                 this._updated$.next(true);
43867                 continue;
43868             }
43869             var scaledX = Math.floor(tileWidth / tileSize * this._tileSize);
43870             var scaledY = Math.floor(tileHeight / tileSize * this._tileSize);
43871             this._fetchTile(tile, this._currentLevel, tileX, tileY, tileWidth, tileHeight, scaledX, scaledY);
43872         }
43873     };
43874     /**
43875      * Get tile coordinates for a point using the current level.
43876      *
43877      * @param {Array<number>} point - Point in basic coordinates.
43878      *
43879      * @returns {Array<number>} x and y tile coodinates.
43880      */
43881     TextureProvider.prototype._getTileCoords = function (point) {
43882         var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
43883         var maxX = Math.ceil(this._width / tileSize) - 1;
43884         var maxY = Math.ceil(this._height / tileSize) - 1;
43885         return [
43886             Math.min(Math.floor(this._width * point[0] / tileSize), maxX),
43887             Math.min(Math.floor(this._height * point[1] / tileSize), maxY),
43888         ];
43889     };
43890     /**
43891      * Get tile coordinates for all tiles contained in a bounding
43892      * box.
43893      *
43894      * @param {Array<number>} topLeft - Top left tile coordinate of bounding box.
43895      * @param {Array<number>} bottomRight - Bottom right tile coordinate of bounding box.
43896      *
43897      * @returns {Array<Array<number>>} Array of x, y tile coodinates.
43898      */
43899     TextureProvider.prototype._getTiles = function (topLeft, bottomRight) {
43900         var xs = [];
43901         if (topLeft[0] > bottomRight[0]) {
43902             var tileSize = this._tileSize * Math.pow(2, this._maxLevel - this._currentLevel);
43903             var maxX = Math.ceil(this._width / tileSize) - 1;
43904             for (var x = topLeft[0]; x <= maxX; x++) {
43905                 xs.push(x);
43906             }
43907             for (var x = 0; x <= bottomRight[0]; x++) {
43908                 xs.push(x);
43909             }
43910         }
43911         else {
43912             for (var x = topLeft[0]; x <= bottomRight[0]; x++) {
43913                 xs.push(x);
43914             }
43915         }
43916         var tiles = [];
43917         for (var _i = 0, xs_1 = xs; _i < xs_1.length; _i++) {
43918             var x = xs_1[_i];
43919             for (var y = topLeft[1]; y <= bottomRight[1]; y++) {
43920                 tiles.push([x, y]);
43921             }
43922         }
43923         return tiles;
43924     };
43925     /**
43926      * Remove an item from an array if it exists in array.
43927      *
43928      * @param {T} item - Item to remove.
43929      * @param {Array<T>} array - Array from which item should be removed.
43930      */
43931     TextureProvider.prototype._removeFromArray = function (item, array) {
43932         var index = array.indexOf(item);
43933         if (index !== -1) {
43934             array.splice(index, 1);
43935         }
43936     };
43937     /**
43938      * Remove an item from a dictionary.
43939      *
43940      * @param {string} key - Key of the item to remove.
43941      * @param {Object} dict - Dictionary from which item should be removed.
43942      */
43943     TextureProvider.prototype._removeFromDictionary = function (key, dict) {
43944         if (key in dict) {
43945             delete dict[key];
43946         }
43947     };
43948     /**
43949      * Render an image tile to the target texture.
43950      *
43951      * @param {number} x - The top left x pixel coordinate of the tile.
43952      * @param {number} y - The top left y pixel coordinate of the tile.
43953      * @param {number} w - The pixel width of the tile.
43954      * @param {number} h - The pixel height of the tile.
43955      * @param {HTMLImageElement} background - The image tile to render.
43956      */
43957     TextureProvider.prototype._renderToTarget = function (x, y, w, h, image) {
43958         var texture = new THREE.Texture(image);
43959         texture.minFilter = THREE.LinearFilter;
43960         texture.needsUpdate = true;
43961         var geometry = new THREE.PlaneGeometry(w, h);
43962         var material = new THREE.MeshBasicMaterial({ map: texture, side: THREE.FrontSide });
43963         var mesh = new THREE.Mesh(geometry, material);
43964         mesh.position.x = -this._width / 2 + x + w / 2;
43965         mesh.position.y = this._height / 2 - y - h / 2;
43966         var scene = new THREE.Scene();
43967         scene.add(mesh);
43968         this._renderer.render(scene, this._camera, this._renderTarget);
43969         this._renderer.setRenderTarget(undefined);
43970         scene.remove(mesh);
43971         geometry.dispose();
43972         material.dispose();
43973         texture.dispose();
43974     };
43975     /**
43976      * Mark a tile as rendered.
43977      *
43978      * @description Clears tiles marked as rendered in other
43979      * levels of the tile pyramid  if they were rendered on
43980      * top of or below the tile.
43981      *
43982      * @param {Arrary<number>} tile - The tile coordinates.
43983      * @param {number} level - Tile level of the tile coordinates.
43984      */
43985     TextureProvider.prototype._setTileRendered = function (tile, level) {
43986         var otherLevels = Object.keys(this._renderedTiles)
43987             .map(function (key) {
43988             return parseInt(key, 10);
43989         })
43990             .filter(function (renderedLevel) {
43991             return renderedLevel !== level;
43992         });
43993         for (var _i = 0, otherLevels_1 = otherLevels; _i < otherLevels_1.length; _i++) {
43994             var otherLevel = otherLevels_1[_i];
43995             var scale = Math.pow(2, otherLevel - level);
43996             if (otherLevel < level) {
43997                 var x = Math.floor(scale * tile[0]);
43998                 var y = Math.floor(scale * tile[1]);
43999                 for (var _a = 0, _b = this._renderedTiles[otherLevel].slice(); _a < _b.length; _a++) {
44000                     var otherTile = _b[_a];
44001                     if (otherTile[0] === x && otherTile[1] === y) {
44002                         var index = this._renderedTiles[otherLevel].indexOf(otherTile);
44003                         this._renderedTiles[otherLevel].splice(index, 1);
44004                     }
44005                 }
44006             }
44007             else {
44008                 var startX = scale * tile[0];
44009                 var endX = startX + scale - 1;
44010                 var startY = scale * tile[1];
44011                 var endY = startY + scale - 1;
44012                 for (var _c = 0, _d = this._renderedTiles[otherLevel].slice(); _c < _d.length; _c++) {
44013                     var otherTile = _d[_c];
44014                     if (otherTile[0] >= startX && otherTile[0] <= endX &&
44015                         otherTile[1] >= startY && otherTile[1] <= endY) {
44016                         var index = this._renderedTiles[otherLevel].indexOf(otherTile);
44017                         this._renderedTiles[otherLevel].splice(index, 1);
44018                     }
44019                 }
44020             }
44021             if (this._renderedTiles[otherLevel].length === 0) {
44022                 delete this._renderedTiles[otherLevel];
44023             }
44024         }
44025         this._renderedTiles[level].push(tile);
44026         this._renderedCurrentLevelTiles[this._tileKey(this._tileSize, tile)] = true;
44027     };
44028     /**
44029      * Create a tile key from a tile coordinates.
44030      *
44031      * @description Tile keys are used as a hash for
44032      * storing the tile in a dictionary.
44033      *
44034      * @param {number} tileSize - The tile size.
44035      * @param {Arrary<number>} tile - The tile coordinates.
44036      */
44037     TextureProvider.prototype._tileKey = function (tileSize, tile) {
44038         return tileSize + "-" + tile[0] + "-" + tile[1];
44039     };
44040     return TextureProvider;
44041 }());
44042 exports.TextureProvider = TextureProvider;
44043 exports.default = TextureProvider;
44044
44045 },{"rxjs/Subject":34,"three":241}],424:[function(require,module,exports){
44046 "use strict";
44047 Object.defineProperty(exports, "__esModule", { value: true });
44048 var DOM = /** @class */ (function () {
44049     function DOM(doc) {
44050         this._document = !!doc ? doc : document;
44051     }
44052     Object.defineProperty(DOM.prototype, "document", {
44053         get: function () {
44054             return this._document;
44055         },
44056         enumerable: true,
44057         configurable: true
44058     });
44059     DOM.prototype.createElement = function (tagName, className, container) {
44060         var element = this._document.createElement(tagName);
44061         if (!!className) {
44062             element.className = className;
44063         }
44064         if (!!container) {
44065             container.appendChild(element);
44066         }
44067         return element;
44068     };
44069     return DOM;
44070 }());
44071 exports.DOM = DOM;
44072 exports.default = DOM;
44073
44074 },{}],425:[function(require,module,exports){
44075 "use strict";
44076 Object.defineProperty(exports, "__esModule", { value: true });
44077 var EventEmitter = /** @class */ (function () {
44078     function EventEmitter() {
44079         this._events = {};
44080     }
44081     /**
44082      * Subscribe to an event by its name.
44083      * @param {string }eventType - The name of the event to subscribe to.
44084      * @param {any} fn - The handler called when the event occurs.
44085      */
44086     EventEmitter.prototype.on = function (eventType, fn) {
44087         this._events[eventType] = this._events[eventType] || [];
44088         this._events[eventType].push(fn);
44089         return;
44090     };
44091     /**
44092      * Unsubscribe from an event by its name.
44093      * @param {string} eventType - The name of the event to subscribe to.
44094      * @param {any} fn - The handler to remove.
44095      */
44096     EventEmitter.prototype.off = function (eventType, fn) {
44097         if (!eventType) {
44098             this._events = {};
44099             return;
44100         }
44101         if (!this._listens(eventType)) {
44102             var idx = this._events[eventType].indexOf(fn);
44103             if (idx >= 0) {
44104                 this._events[eventType].splice(idx, 1);
44105             }
44106             if (this._events[eventType].length) {
44107                 delete this._events[eventType];
44108             }
44109         }
44110         else {
44111             delete this._events[eventType];
44112         }
44113         return;
44114     };
44115     EventEmitter.prototype.fire = function (eventType, data) {
44116         if (!this._listens(eventType)) {
44117             return;
44118         }
44119         for (var _i = 0, _a = this._events[eventType]; _i < _a.length; _i++) {
44120             var fn = _a[_i];
44121             fn.call(this, data);
44122         }
44123         return;
44124     };
44125     EventEmitter.prototype._listens = function (eventType) {
44126         return !!(this._events && this._events[eventType]);
44127     };
44128     return EventEmitter;
44129 }());
44130 exports.EventEmitter = EventEmitter;
44131 exports.default = EventEmitter;
44132
44133 },{}],426:[function(require,module,exports){
44134 "use strict";
44135 Object.defineProperty(exports, "__esModule", { value: true });
44136 var Viewer_1 = require("../Viewer");
44137 var Settings = /** @class */ (function () {
44138     function Settings() {
44139     }
44140     Settings.setOptions = function (options) {
44141         Settings._baseImageSize = options.baseImageSize != null ?
44142             options.baseImageSize :
44143             Viewer_1.ImageSize.Size640;
44144         Settings._basePanoramaSize = options.basePanoramaSize != null ?
44145             options.basePanoramaSize :
44146             Viewer_1.ImageSize.Size2048;
44147         Settings._maxImageSize = options.maxImageSize != null ?
44148             options.maxImageSize :
44149             Viewer_1.ImageSize.Size2048;
44150     };
44151     Object.defineProperty(Settings, "baseImageSize", {
44152         get: function () {
44153             return Settings._baseImageSize;
44154         },
44155         enumerable: true,
44156         configurable: true
44157     });
44158     Object.defineProperty(Settings, "basePanoramaSize", {
44159         get: function () {
44160             return Settings._basePanoramaSize;
44161         },
44162         enumerable: true,
44163         configurable: true
44164     });
44165     Object.defineProperty(Settings, "maxImageSize", {
44166         get: function () {
44167             return Settings._maxImageSize;
44168         },
44169         enumerable: true,
44170         configurable: true
44171     });
44172     return Settings;
44173 }());
44174 exports.Settings = Settings;
44175 exports.default = Settings;
44176
44177 },{"../Viewer":302}],427:[function(require,module,exports){
44178 "use strict";
44179 Object.defineProperty(exports, "__esModule", { value: true });
44180 function isBrowser() {
44181     return typeof window !== "undefined" && typeof document !== "undefined";
44182 }
44183 exports.isBrowser = isBrowser;
44184 function isArraySupported() {
44185     return !!(Array.prototype &&
44186         Array.prototype.filter &&
44187         Array.prototype.indexOf &&
44188         Array.prototype.map &&
44189         Array.prototype.reverse);
44190 }
44191 exports.isArraySupported = isArraySupported;
44192 function isFunctionSupported() {
44193     return !!(Function.prototype && Function.prototype.bind);
44194 }
44195 exports.isFunctionSupported = isFunctionSupported;
44196 function isJSONSupported() {
44197     return "JSON" in window && "parse" in JSON && "stringify" in JSON;
44198 }
44199 exports.isJSONSupported = isJSONSupported;
44200 function isObjectSupported() {
44201     return !!(Object.keys &&
44202         Object.assign);
44203 }
44204 exports.isObjectSupported = isObjectSupported;
44205 var isWebGLSupportedCache = undefined;
44206 function isWebGLSupportedCached() {
44207     if (isWebGLSupportedCache === undefined) {
44208         isWebGLSupportedCache = isWebGLSupported();
44209     }
44210     return isWebGLSupportedCache;
44211 }
44212 exports.isWebGLSupportedCached = isWebGLSupportedCached;
44213 function isWebGLSupported() {
44214     var webGLContextAttributes = {
44215         alpha: false,
44216         antialias: false,
44217         depth: true,
44218         failIfMajorPerformanceCaveat: false,
44219         premultipliedAlpha: true,
44220         preserveDrawingBuffer: false,
44221         stencil: true,
44222     };
44223     var canvas = document.createElement("canvas");
44224     var context = canvas.getContext("webgl", webGLContextAttributes) ||
44225         canvas.getContext("experimental-webgl", webGLContextAttributes);
44226     if (!context) {
44227         return false;
44228     }
44229     var requiredExtensions = [
44230         "OES_standard_derivatives",
44231     ];
44232     var supportedExtensions = context.getSupportedExtensions();
44233     for (var _i = 0, requiredExtensions_1 = requiredExtensions; _i < requiredExtensions_1.length; _i++) {
44234         var requiredExtension = requiredExtensions_1[_i];
44235         if (supportedExtensions.indexOf(requiredExtension) === -1) {
44236             return false;
44237         }
44238     }
44239     return true;
44240 }
44241 exports.isWebGLSupported = isWebGLSupported;
44242
44243 },{}],428:[function(require,module,exports){
44244 "use strict";
44245 Object.defineProperty(exports, "__esModule", { value: true });
44246 var Urls = /** @class */ (function () {
44247     function Urls() {
44248     }
44249     Object.defineProperty(Urls, "explore", {
44250         get: function () {
44251             return Urls._scheme + "://" + Urls._exploreHost;
44252         },
44253         enumerable: true,
44254         configurable: true
44255     });
44256     Object.defineProperty(Urls, "origin", {
44257         get: function () {
44258             return Urls._origin;
44259         },
44260         enumerable: true,
44261         configurable: true
44262     });
44263     Object.defineProperty(Urls, "tileScheme", {
44264         get: function () {
44265             return Urls._scheme;
44266         },
44267         enumerable: true,
44268         configurable: true
44269     });
44270     Object.defineProperty(Urls, "tileDomain", {
44271         get: function () {
44272             return Urls._imageTileHost;
44273         },
44274         enumerable: true,
44275         configurable: true
44276     });
44277     Urls.exporeImage = function (key) {
44278         return Urls._scheme + "://" + Urls._exploreHost + "/app/?pKey=" + key + "&focus=photo";
44279     };
44280     Urls.exporeUser = function (username) {
44281         return Urls._scheme + "://" + Urls._exploreHost + "/app/user/" + username;
44282     };
44283     Urls.falcorModel = function (clientId) {
44284         return Urls._scheme + "://" + Urls._apiHost + "/v3/model.json?client_id=" + clientId;
44285     };
44286     Urls.protoMesh = function (key) {
44287         return Urls._scheme + "://" + Urls._meshHost + "/v2/mesh/" + key;
44288     };
44289     Urls.thumbnail = function (key, size, origin) {
44290         var query = !!origin ? "?origin=" + origin : "";
44291         return Urls._scheme + "://" + Urls._imageHost + "/" + key + "/thumb-" + size + ".jpg" + query;
44292     };
44293     Urls.setOptions = function (options) {
44294         if (!options) {
44295             return;
44296         }
44297         if (!!options.apiHost) {
44298             Urls._apiHost = options.apiHost;
44299         }
44300         if (!!options.exploreHost) {
44301             Urls._exploreHost = options.exploreHost;
44302         }
44303         if (!!options.imageHost) {
44304             Urls._imageHost = options.imageHost;
44305         }
44306         if (!!options.imageTileHost) {
44307             Urls._imageTileHost = options.imageTileHost;
44308         }
44309         if (!!options.meshHost) {
44310             Urls._meshHost = options.meshHost;
44311         }
44312         if (!!options.scheme) {
44313             Urls._scheme = options.scheme;
44314         }
44315     };
44316     Urls._apiHost = "a.mapillary.com";
44317     Urls._exploreHost = "www.mapillary.com";
44318     Urls._imageHost = "d1cuyjsrcm0gby.cloudfront.net";
44319     Urls._imageTileHost = "d2qb1440i7l50o.cloudfront.net";
44320     Urls._meshHost = "d1brzeo354iq2l.cloudfront.net";
44321     Urls._origin = "mapillary.webgl";
44322     Urls._scheme = "https";
44323     return Urls;
44324 }());
44325 exports.Urls = Urls;
44326 exports.default = Urls;
44327
44328 },{}],429:[function(require,module,exports){
44329 "use strict";
44330 Object.defineProperty(exports, "__esModule", { value: true });
44331 /**
44332  * Enumeration for alignments
44333  * @enum {number}
44334  * @readonly
44335  */
44336 var Alignment;
44337 (function (Alignment) {
44338     /**
44339      * Align to bottom
44340      */
44341     Alignment[Alignment["Bottom"] = 0] = "Bottom";
44342     /**
44343      * Align to bottom left
44344      */
44345     Alignment[Alignment["BottomLeft"] = 1] = "BottomLeft";
44346     /**
44347      * Align to bottom right
44348      */
44349     Alignment[Alignment["BottomRight"] = 2] = "BottomRight";
44350     /**
44351      * Align to center
44352      */
44353     Alignment[Alignment["Center"] = 3] = "Center";
44354     /**
44355      * Align to left
44356      */
44357     Alignment[Alignment["Left"] = 4] = "Left";
44358     /**
44359      * Align to right
44360      */
44361     Alignment[Alignment["Right"] = 5] = "Right";
44362     /**
44363      * Align to top
44364      */
44365     Alignment[Alignment["Top"] = 6] = "Top";
44366     /**
44367      * Align to top left
44368      */
44369     Alignment[Alignment["TopLeft"] = 7] = "TopLeft";
44370     /**
44371      * Align to top right
44372      */
44373     Alignment[Alignment["TopRight"] = 8] = "TopRight";
44374 })(Alignment = exports.Alignment || (exports.Alignment = {}));
44375 exports.default = Alignment;
44376
44377 },{}],430:[function(require,module,exports){
44378 "use strict";
44379 Object.defineProperty(exports, "__esModule", { value: true });
44380 var Observable_1 = require("rxjs/Observable");
44381 require("rxjs/add/operator/bufferCount");
44382 require("rxjs/add/operator/delay");
44383 require("rxjs/add/operator/distinctUntilChanged");
44384 require("rxjs/add/operator/map");
44385 require("rxjs/add/operator/switchMap");
44386 require("rxjs/add/operator/timeout");
44387 var Graph_1 = require("../Graph");
44388 var CacheService = /** @class */ (function () {
44389     function CacheService(graphService, stateService) {
44390         this._graphService = graphService;
44391         this._stateService = stateService;
44392         this._started = false;
44393     }
44394     Object.defineProperty(CacheService.prototype, "started", {
44395         get: function () {
44396             return this._started;
44397         },
44398         enumerable: true,
44399         configurable: true
44400     });
44401     CacheService.prototype.start = function () {
44402         var _this = this;
44403         if (this._started) {
44404             return;
44405         }
44406         this._uncacheSubscription = this._stateService.currentState$
44407             .distinctUntilChanged(undefined, function (frame) {
44408             return frame.state.currentNode.key;
44409         })
44410             .map(function (frame) {
44411             var trajectory = frame.state.trajectory;
44412             var trajectoryKeys = trajectory
44413                 .map(function (n) {
44414                 return n.key;
44415             });
44416             var sequenceKey = trajectory[trajectory.length - 1].sequenceKey;
44417             return [trajectoryKeys, sequenceKey];
44418         })
44419             .bufferCount(1, 5)
44420             .withLatestFrom(this._graphService.graphMode$)
44421             .switchMap(function (_a) {
44422             var keepBuffer = _a[0], graphMode = _a[1];
44423             var keepKeys = keepBuffer[0][0];
44424             var keepSequenceKey = graphMode === Graph_1.GraphMode.Sequence ?
44425                 keepBuffer[0][1] : undefined;
44426             return _this._graphService.uncache$(keepKeys, keepSequenceKey);
44427         })
44428             .subscribe(function () { });
44429         this._cacheNodeSubscription = this._graphService.graphMode$
44430             .skip(1)
44431             .withLatestFrom(this._stateService.currentState$)
44432             .switchMap(function (_a) {
44433             var mode = _a[0], frame = _a[1];
44434             return mode === Graph_1.GraphMode.Sequence ?
44435                 _this._keyToEdges(frame.state.currentNode.key, function (node) {
44436                     return node.sequenceEdges$;
44437                 }) :
44438                 Observable_1.Observable
44439                     .from(frame.state.trajectory
44440                     .map(function (node) {
44441                     return node.key;
44442                 })
44443                     .slice(frame.state.currentIndex))
44444                     .mergeMap(function (key) {
44445                     return _this._keyToEdges(key, function (node) {
44446                         return node.spatialEdges$;
44447                     });
44448                 }, 6);
44449         })
44450             .subscribe(function () { });
44451         this._started = true;
44452     };
44453     CacheService.prototype.stop = function () {
44454         if (!this._started) {
44455             return;
44456         }
44457         this._uncacheSubscription.unsubscribe();
44458         this._uncacheSubscription = null;
44459         this._cacheNodeSubscription.unsubscribe();
44460         this._cacheNodeSubscription = null;
44461         this._started = false;
44462     };
44463     CacheService.prototype._keyToEdges = function (key, nodeToEdgeMap) {
44464         return this._graphService.cacheNode$(key)
44465             .switchMap(nodeToEdgeMap)
44466             .first(function (status) {
44467             return status.cached;
44468         })
44469             .timeout(15000)
44470             .catch(function (error) {
44471             console.error("Failed to cache edges (" + key + ").", error);
44472             return Observable_1.Observable.empty();
44473         });
44474     };
44475     return CacheService;
44476 }());
44477 exports.CacheService = CacheService;
44478 exports.default = CacheService;
44479
44480 },{"../Graph":295,"rxjs/Observable":29,"rxjs/add/operator/bufferCount":52,"rxjs/add/operator/delay":58,"rxjs/add/operator/distinctUntilChanged":60,"rxjs/add/operator/map":67,"rxjs/add/operator/switchMap":84,"rxjs/add/operator/timeout":89}],431:[function(require,module,exports){
44481 "use strict";
44482 Object.defineProperty(exports, "__esModule", { value: true });
44483 var Component_1 = require("../Component");
44484 var ComponentController = /** @class */ (function () {
44485     function ComponentController(container, navigator, observer, key, options, componentService) {
44486         var _this = this;
44487         this._container = container;
44488         this._observer = observer;
44489         this._navigator = navigator;
44490         this._options = options != null ? options : {};
44491         this._key = key;
44492         this._navigable = key == null;
44493         this._componentService = !!componentService ?
44494             componentService :
44495             new Component_1.ComponentService(this._container, this._navigator);
44496         this._coverComponent = this._componentService.getCover();
44497         this._initializeComponents();
44498         if (key) {
44499             this._initilizeCoverComponent();
44500             this._subscribeCoverComponent();
44501         }
44502         else {
44503             this._navigator.movedToKey$
44504                 .first(function (k) {
44505                 return k != null;
44506             })
44507                 .subscribe(function (k) {
44508                 _this._key = k;
44509                 _this._componentService.deactivateCover();
44510                 _this._coverComponent.configure({ key: _this._key, state: Component_1.CoverState.Hidden });
44511                 _this._subscribeCoverComponent();
44512                 _this._navigator.stateService.start();
44513                 _this._navigator.cacheService.start();
44514                 _this._observer.startEmit();
44515             });
44516         }
44517     }
44518     Object.defineProperty(ComponentController.prototype, "navigable", {
44519         get: function () {
44520             return this._navigable;
44521         },
44522         enumerable: true,
44523         configurable: true
44524     });
44525     ComponentController.prototype.get = function (name) {
44526         return this._componentService.get(name);
44527     };
44528     ComponentController.prototype.activate = function (name) {
44529         this._componentService.activate(name);
44530     };
44531     ComponentController.prototype.activateCover = function () {
44532         this._coverComponent.configure({ state: Component_1.CoverState.Visible });
44533     };
44534     ComponentController.prototype.deactivate = function (name) {
44535         this._componentService.deactivate(name);
44536     };
44537     ComponentController.prototype.deactivateCover = function () {
44538         this._coverComponent.configure({ state: Component_1.CoverState.Loading });
44539     };
44540     ComponentController.prototype.resize = function () {
44541         this._componentService.resize();
44542     };
44543     ComponentController.prototype._initializeComponents = function () {
44544         var options = this._options;
44545         this._uFalse(options.background, "background");
44546         this._uFalse(options.debug, "debug");
44547         this._uFalse(options.image, "image");
44548         this._uFalse(options.marker, "marker");
44549         this._uFalse(options.navigation, "navigation");
44550         this._uFalse(options.popup, "popup");
44551         this._uFalse(options.route, "route");
44552         this._uFalse(options.slider, "slider");
44553         this._uFalse(options.tag, "tag");
44554         this._uTrue(options.attribution, "attribution");
44555         this._uTrue(options.bearing, "bearing");
44556         this._uTrue(options.cache, "cache");
44557         this._uTrue(options.direction, "direction");
44558         this._uTrue(options.imagePlane, "imagePlane");
44559         this._uTrue(options.keyboard, "keyboard");
44560         this._uTrue(options.loading, "loading");
44561         this._uTrue(options.mouse, "mouse");
44562         this._uTrue(options.sequence, "sequence");
44563         this._uTrue(options.stats, "stats");
44564     };
44565     ComponentController.prototype._initilizeCoverComponent = function () {
44566         var options = this._options;
44567         this._coverComponent.configure({ key: this._key });
44568         if (options.cover === undefined || options.cover) {
44569             this.activateCover();
44570         }
44571         else {
44572             this.deactivateCover();
44573         }
44574     };
44575     ComponentController.prototype._setNavigable = function (navigable) {
44576         if (this._navigable === navigable) {
44577             return;
44578         }
44579         this._navigable = navigable;
44580         this._observer.navigable$.next(navigable);
44581     };
44582     ComponentController.prototype._subscribeCoverComponent = function () {
44583         var _this = this;
44584         this._coverComponent.configuration$.subscribe(function (conf) {
44585             if (conf.state === Component_1.CoverState.Loading) {
44586                 _this._navigator.stateService.currentKey$
44587                     .first()
44588                     .switchMap(function (key) {
44589                     var keyChanged = key == null || key !== conf.key;
44590                     if (keyChanged) {
44591                         _this._setNavigable(false);
44592                     }
44593                     return keyChanged ?
44594                         _this._navigator.moveToKey$(conf.key) :
44595                         _this._navigator.stateService.currentNode$
44596                             .first();
44597                 })
44598                     .subscribe(function (node) {
44599                     _this._navigator.stateService.start();
44600                     _this._navigator.cacheService.start();
44601                     _this._observer.startEmit();
44602                     _this._coverComponent.configure({ state: Component_1.CoverState.Hidden });
44603                     _this._componentService.deactivateCover();
44604                     _this._setNavigable(true);
44605                 }, function (error) {
44606                     console.error("Failed to deactivate cover.", error);
44607                     _this._coverComponent.configure({ state: Component_1.CoverState.Visible });
44608                 });
44609             }
44610             else if (conf.state === Component_1.CoverState.Visible) {
44611                 _this._observer.stopEmit();
44612                 _this._navigator.stateService.stop();
44613                 _this._navigator.cacheService.stop();
44614                 _this._navigator.playService.stop();
44615                 _this._componentService.activateCover();
44616                 _this._setNavigable(conf.key == null);
44617             }
44618         });
44619     };
44620     ComponentController.prototype._uFalse = function (option, name) {
44621         if (option === undefined) {
44622             this._componentService.deactivate(name);
44623             return;
44624         }
44625         if (typeof option === "boolean") {
44626             if (option) {
44627                 this._componentService.activate(name);
44628             }
44629             else {
44630                 this._componentService.deactivate(name);
44631             }
44632             return;
44633         }
44634         this._componentService.configure(name, option);
44635         this._componentService.activate(name);
44636     };
44637     ComponentController.prototype._uTrue = function (option, name) {
44638         if (option === undefined) {
44639             this._componentService.activate(name);
44640             return;
44641         }
44642         if (typeof option === "boolean") {
44643             if (option) {
44644                 this._componentService.activate(name);
44645             }
44646             else {
44647                 this._componentService.deactivate(name);
44648             }
44649             return;
44650         }
44651         this._componentService.configure(name, option);
44652         this._componentService.activate(name);
44653     };
44654     return ComponentController;
44655 }());
44656 exports.ComponentController = ComponentController;
44657
44658 },{"../Component":291}],432:[function(require,module,exports){
44659 "use strict";
44660 Object.defineProperty(exports, "__esModule", { value: true });
44661 var Render_1 = require("../Render");
44662 var Utils_1 = require("../Utils");
44663 var Viewer_1 = require("../Viewer");
44664 var Container = /** @class */ (function () {
44665     function Container(id, stateService, options, dom) {
44666         this.id = id;
44667         this._dom = !!dom ? dom : new Utils_1.DOM();
44668         this._container = this._dom.document.getElementById(id);
44669         if (!this._container) {
44670             throw new Error("Container '" + id + "' not found.");
44671         }
44672         this._container.classList.add("mapillary-js");
44673         this._canvasContainer = this._dom.createElement("div", "mapillary-js-interactive", this._container);
44674         this._domContainer = this._dom.createElement("div", "mapillary-js-dom", this._container);
44675         this.renderService = new Render_1.RenderService(this._container, stateService.currentState$, options.renderMode);
44676         this.glRenderer = new Render_1.GLRenderer(this._canvasContainer, this.renderService, this._dom);
44677         this.domRenderer = new Render_1.DOMRenderer(this._domContainer, this.renderService, stateService.currentState$);
44678         this.keyboardService = new Viewer_1.KeyboardService(this._canvasContainer);
44679         this.mouseService = new Viewer_1.MouseService(this._container, this._canvasContainer, this._domContainer, document);
44680         this.touchService = new Viewer_1.TouchService(this._canvasContainer, this._domContainer);
44681         this.spriteService = new Viewer_1.SpriteService(options.sprite);
44682     }
44683     Object.defineProperty(Container.prototype, "element", {
44684         get: function () {
44685             return this._container;
44686         },
44687         enumerable: true,
44688         configurable: true
44689     });
44690     Object.defineProperty(Container.prototype, "canvasContainer", {
44691         get: function () {
44692             return this._canvasContainer;
44693         },
44694         enumerable: true,
44695         configurable: true
44696     });
44697     Object.defineProperty(Container.prototype, "domContainer", {
44698         get: function () {
44699             return this._domContainer;
44700         },
44701         enumerable: true,
44702         configurable: true
44703     });
44704     return Container;
44705 }());
44706 exports.Container = Container;
44707 exports.default = Container;
44708
44709 },{"../Render":297,"../Utils":301,"../Viewer":302}],433:[function(require,module,exports){
44710 "use strict";
44711 Object.defineProperty(exports, "__esModule", { value: true });
44712 /**
44713  * Enumeration for image sizes
44714  * @enum {number}
44715  * @readonly
44716  * @description Image sizes in pixels for the long side of the image.
44717  */
44718 var ImageSize;
44719 (function (ImageSize) {
44720     /**
44721      * 320 pixels image size
44722      */
44723     ImageSize[ImageSize["Size320"] = 320] = "Size320";
44724     /**
44725      * 640 pixels image size
44726      */
44727     ImageSize[ImageSize["Size640"] = 640] = "Size640";
44728     /**
44729      * 1024 pixels image size
44730      */
44731     ImageSize[ImageSize["Size1024"] = 1024] = "Size1024";
44732     /**
44733      * 2048 pixels image size
44734      */
44735     ImageSize[ImageSize["Size2048"] = 2048] = "Size2048";
44736 })(ImageSize = exports.ImageSize || (exports.ImageSize = {}));
44737
44738 },{}],434:[function(require,module,exports){
44739 "use strict";
44740 Object.defineProperty(exports, "__esModule", { value: true });
44741 var Observable_1 = require("rxjs/Observable");
44742 var KeyboardService = /** @class */ (function () {
44743     function KeyboardService(canvasContainer) {
44744         this._keyDown$ = Observable_1.Observable.fromEvent(canvasContainer, "keydown");
44745     }
44746     Object.defineProperty(KeyboardService.prototype, "keyDown$", {
44747         get: function () {
44748             return this._keyDown$;
44749         },
44750         enumerable: true,
44751         configurable: true
44752     });
44753     return KeyboardService;
44754 }());
44755 exports.KeyboardService = KeyboardService;
44756 exports.default = KeyboardService;
44757
44758 },{"rxjs/Observable":29}],435:[function(require,module,exports){
44759 "use strict";
44760 /// <reference path="../../typings/index.d.ts" />
44761 Object.defineProperty(exports, "__esModule", { value: true });
44762 var _ = require("underscore");
44763 var Subject_1 = require("rxjs/Subject");
44764 require("rxjs/add/operator/debounceTime");
44765 require("rxjs/add/operator/distinctUntilChanged");
44766 require("rxjs/add/operator/map");
44767 require("rxjs/add/operator/publishReplay");
44768 require("rxjs/add/operator/scan");
44769 require("rxjs/add/operator/startWith");
44770 var LoadingService = /** @class */ (function () {
44771     function LoadingService() {
44772         this._loadersSubject$ = new Subject_1.Subject();
44773         this._loaders$ = this._loadersSubject$
44774             .scan(function (loaders, loader) {
44775             if (loader.task !== undefined) {
44776                 loaders[loader.task] = loader.loading;
44777             }
44778             return loaders;
44779         }, {})
44780             .startWith({})
44781             .publishReplay(1)
44782             .refCount();
44783     }
44784     Object.defineProperty(LoadingService.prototype, "loading$", {
44785         get: function () {
44786             return this._loaders$
44787                 .map(function (loaders) {
44788                 return _.reduce(loaders, function (loader, acc) {
44789                     return (loader || acc);
44790                 }, false);
44791             })
44792                 .debounceTime(100)
44793                 .distinctUntilChanged();
44794         },
44795         enumerable: true,
44796         configurable: true
44797     });
44798     LoadingService.prototype.taskLoading$ = function (task) {
44799         return this._loaders$
44800             .map(function (loaders) {
44801             return !!loaders[task];
44802         })
44803             .debounceTime(100)
44804             .distinctUntilChanged();
44805     };
44806     LoadingService.prototype.startLoading = function (task) {
44807         this._loadersSubject$.next({ loading: true, task: task });
44808     };
44809     LoadingService.prototype.stopLoading = function (task) {
44810         this._loadersSubject$.next({ loading: false, task: task });
44811     };
44812     return LoadingService;
44813 }());
44814 exports.LoadingService = LoadingService;
44815 exports.default = LoadingService;
44816
44817 },{"rxjs/Subject":34,"rxjs/add/operator/debounceTime":57,"rxjs/add/operator/distinctUntilChanged":60,"rxjs/add/operator/map":67,"rxjs/add/operator/publishReplay":74,"rxjs/add/operator/scan":78,"rxjs/add/operator/startWith":83,"underscore":243}],436:[function(require,module,exports){
44818 "use strict";
44819 Object.defineProperty(exports, "__esModule", { value: true });
44820 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
44821 var Observable_1 = require("rxjs/Observable");
44822 var Subject_1 = require("rxjs/Subject");
44823 require("rxjs/add/observable/fromEvent");
44824 require("rxjs/add/operator/distinctUntilChanged");
44825 require("rxjs/add/operator/filter");
44826 require("rxjs/add/operator/map");
44827 require("rxjs/add/operator/merge");
44828 require("rxjs/add/operator/mergeMap");
44829 require("rxjs/add/operator/publishReplay");
44830 require("rxjs/add/operator/scan");
44831 require("rxjs/add/operator/switchMap");
44832 require("rxjs/add/operator/withLatestFrom");
44833 var Geo_1 = require("../Geo");
44834 var MouseService = /** @class */ (function () {
44835     function MouseService(container, canvasContainer, domContainer, doc, viewportCoords) {
44836         var _this = this;
44837         viewportCoords = viewportCoords != null ? viewportCoords : new Geo_1.ViewportCoords();
44838         this._activeSubject$ = new BehaviorSubject_1.BehaviorSubject(false);
44839         this._active$ = this._activeSubject$
44840             .distinctUntilChanged()
44841             .publishReplay(1)
44842             .refCount();
44843         this._claimMouse$ = new Subject_1.Subject();
44844         this._claimWheel$ = new Subject_1.Subject();
44845         this._deferPixelClaims$ = new Subject_1.Subject();
44846         this._deferPixels$ = this._deferPixelClaims$
44847             .scan(function (claims, claim) {
44848             if (claim.deferPixels == null) {
44849                 delete claims[claim.name];
44850             }
44851             else {
44852                 claims[claim.name] = claim.deferPixels;
44853             }
44854             return claims;
44855         }, {})
44856             .map(function (claims) {
44857             var deferPixelMax = -1;
44858             for (var key in claims) {
44859                 if (!claims.hasOwnProperty(key)) {
44860                     continue;
44861                 }
44862                 var deferPixels = claims[key];
44863                 if (deferPixels > deferPixelMax) {
44864                     deferPixelMax = deferPixels;
44865                 }
44866             }
44867             return deferPixelMax;
44868         })
44869             .startWith(-1)
44870             .publishReplay(1)
44871             .refCount();
44872         this._deferPixels$.subscribe(function () { });
44873         this._documentMouseMove$ = Observable_1.Observable.fromEvent(doc, "mousemove");
44874         this._documentMouseUp$ = Observable_1.Observable.fromEvent(doc, "mouseup");
44875         this._mouseDown$ = Observable_1.Observable.fromEvent(canvasContainer, "mousedown");
44876         this._mouseLeave$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseleave");
44877         this._mouseMove$ = Observable_1.Observable.fromEvent(canvasContainer, "mousemove");
44878         this._mouseUp$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseup");
44879         this._mouseOut$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseout");
44880         this._mouseOver$ = Observable_1.Observable.fromEvent(canvasContainer, "mouseover");
44881         this._domMouseDown$ = Observable_1.Observable.fromEvent(domContainer, "mousedown");
44882         this._domMouseMove$ = Observable_1.Observable.fromEvent(domContainer, "mousemove");
44883         this._click$ = Observable_1.Observable.fromEvent(canvasContainer, "click");
44884         this._contextMenu$ = Observable_1.Observable.fromEvent(canvasContainer, "contextmenu");
44885         this._dblClick$ = Observable_1.Observable
44886             .merge(Observable_1.Observable.fromEvent(container, "click"), Observable_1.Observable.fromEvent(canvasContainer, "dblclick"))
44887             .bufferCount(3, 1)
44888             .filter(function (events) {
44889             var event1 = events[0];
44890             var event2 = events[1];
44891             var event3 = events[2];
44892             return event1.type === "click" &&
44893                 event2.type === "click" &&
44894                 event3.type === "dblclick" &&
44895                 event1.target.parentNode === canvasContainer &&
44896                 event2.target.parentNode === canvasContainer;
44897         })
44898             .map(function (events) {
44899             return events[2];
44900         })
44901             .share();
44902         Observable_1.Observable
44903             .merge(this._domMouseDown$, this._domMouseMove$, this._dblClick$, this._contextMenu$)
44904             .subscribe(function (event) {
44905             event.preventDefault();
44906         });
44907         this._mouseWheel$ = Observable_1.Observable
44908             .merge(Observable_1.Observable.fromEvent(canvasContainer, "wheel"), Observable_1.Observable.fromEvent(domContainer, "wheel"))
44909             .share();
44910         this._consistentContextMenu$ = Observable_1.Observable
44911             .merge(this._mouseDown$, this._mouseMove$, this._mouseOut$, this._mouseUp$, this._contextMenu$)
44912             .bufferCount(3, 1)
44913             .filter(function (events) {
44914             // fire context menu on mouse up both on mac and windows
44915             return events[0].type === "mousedown" &&
44916                 events[1].type === "contextmenu" &&
44917                 events[2].type === "mouseup";
44918         })
44919             .map(function (events) {
44920             return events[1];
44921         })
44922             .share();
44923         var dragStop$ = Observable_1.Observable
44924             .merge(Observable_1.Observable.fromEvent(window, "blur"), this._documentMouseUp$
44925             .filter(function (e) {
44926             return e.button === 0;
44927         }))
44928             .share();
44929         var mouseDragInitiate$ = this._createMouseDragInitiate$(this._mouseDown$, dragStop$, true).share();
44930         this._mouseDragStart$ = this._createMouseDragStart$(mouseDragInitiate$).share();
44931         this._mouseDrag$ = this._createMouseDrag$(mouseDragInitiate$, dragStop$).share();
44932         this._mouseDragEnd$ = this._createMouseDragEnd$(this._mouseDragStart$, dragStop$).share();
44933         var domMouseDragInitiate$ = this._createMouseDragInitiate$(this._domMouseDown$, dragStop$, false).share();
44934         this._domMouseDragStart$ = this._createMouseDragStart$(domMouseDragInitiate$).share();
44935         this._domMouseDrag$ = this._createMouseDrag$(domMouseDragInitiate$, dragStop$).share();
44936         this._domMouseDragEnd$ = this._createMouseDragEnd$(this._domMouseDragStart$, dragStop$).share();
44937         this._proximateClick$ = this._mouseDown$
44938             .switchMap(function (mouseDown) {
44939             return _this._click$
44940                 .takeUntil(_this._createDeferredMouseMove$(mouseDown, _this._documentMouseMove$))
44941                 .take(1);
44942         })
44943             .share();
44944         this._staticClick$ = this._mouseDown$
44945             .switchMap(function (e) {
44946             return _this._click$
44947                 .takeUntil(_this._documentMouseMove$)
44948                 .take(1);
44949         })
44950             .share();
44951         this._mouseDragStart$.subscribe();
44952         this._mouseDrag$.subscribe();
44953         this._mouseDragEnd$.subscribe();
44954         this._domMouseDragStart$.subscribe();
44955         this._domMouseDrag$.subscribe();
44956         this._domMouseDragEnd$.subscribe();
44957         this._staticClick$.subscribe();
44958         this._mouseOwner$ = this._createOwner$(this._claimMouse$)
44959             .publishReplay(1)
44960             .refCount();
44961         this._wheelOwner$ = this._createOwner$(this._claimWheel$)
44962             .publishReplay(1)
44963             .refCount();
44964         this._mouseOwner$.subscribe(function () { });
44965         this._wheelOwner$.subscribe(function () { });
44966     }
44967     Object.defineProperty(MouseService.prototype, "active$", {
44968         get: function () {
44969             return this._active$;
44970         },
44971         enumerable: true,
44972         configurable: true
44973     });
44974     Object.defineProperty(MouseService.prototype, "activate$", {
44975         get: function () {
44976             return this._activeSubject$;
44977         },
44978         enumerable: true,
44979         configurable: true
44980     });
44981     Object.defineProperty(MouseService.prototype, "documentMouseMove$", {
44982         get: function () {
44983             return this._documentMouseMove$;
44984         },
44985         enumerable: true,
44986         configurable: true
44987     });
44988     Object.defineProperty(MouseService.prototype, "documentMouseUp$", {
44989         get: function () {
44990             return this._documentMouseUp$;
44991         },
44992         enumerable: true,
44993         configurable: true
44994     });
44995     Object.defineProperty(MouseService.prototype, "domMouseDragStart$", {
44996         get: function () {
44997             return this._domMouseDragStart$;
44998         },
44999         enumerable: true,
45000         configurable: true
45001     });
45002     Object.defineProperty(MouseService.prototype, "domMouseDrag$", {
45003         get: function () {
45004             return this._domMouseDrag$;
45005         },
45006         enumerable: true,
45007         configurable: true
45008     });
45009     Object.defineProperty(MouseService.prototype, "domMouseDragEnd$", {
45010         get: function () {
45011             return this._domMouseDragEnd$;
45012         },
45013         enumerable: true,
45014         configurable: true
45015     });
45016     Object.defineProperty(MouseService.prototype, "domMouseDown$", {
45017         get: function () {
45018             return this._domMouseDown$;
45019         },
45020         enumerable: true,
45021         configurable: true
45022     });
45023     Object.defineProperty(MouseService.prototype, "domMouseMove$", {
45024         get: function () {
45025             return this._domMouseMove$;
45026         },
45027         enumerable: true,
45028         configurable: true
45029     });
45030     Object.defineProperty(MouseService.prototype, "mouseOwner$", {
45031         get: function () {
45032             return this._mouseOwner$;
45033         },
45034         enumerable: true,
45035         configurable: true
45036     });
45037     Object.defineProperty(MouseService.prototype, "mouseDown$", {
45038         get: function () {
45039             return this._mouseDown$;
45040         },
45041         enumerable: true,
45042         configurable: true
45043     });
45044     Object.defineProperty(MouseService.prototype, "mouseMove$", {
45045         get: function () {
45046             return this._mouseMove$;
45047         },
45048         enumerable: true,
45049         configurable: true
45050     });
45051     Object.defineProperty(MouseService.prototype, "mouseLeave$", {
45052         get: function () {
45053             return this._mouseLeave$;
45054         },
45055         enumerable: true,
45056         configurable: true
45057     });
45058     Object.defineProperty(MouseService.prototype, "mouseOut$", {
45059         get: function () {
45060             return this._mouseOut$;
45061         },
45062         enumerable: true,
45063         configurable: true
45064     });
45065     Object.defineProperty(MouseService.prototype, "mouseOver$", {
45066         get: function () {
45067             return this._mouseOver$;
45068         },
45069         enumerable: true,
45070         configurable: true
45071     });
45072     Object.defineProperty(MouseService.prototype, "mouseUp$", {
45073         get: function () {
45074             return this._mouseUp$;
45075         },
45076         enumerable: true,
45077         configurable: true
45078     });
45079     Object.defineProperty(MouseService.prototype, "click$", {
45080         get: function () {
45081             return this._click$;
45082         },
45083         enumerable: true,
45084         configurable: true
45085     });
45086     Object.defineProperty(MouseService.prototype, "dblClick$", {
45087         get: function () {
45088             return this._dblClick$;
45089         },
45090         enumerable: true,
45091         configurable: true
45092     });
45093     Object.defineProperty(MouseService.prototype, "contextMenu$", {
45094         get: function () {
45095             return this._consistentContextMenu$;
45096         },
45097         enumerable: true,
45098         configurable: true
45099     });
45100     Object.defineProperty(MouseService.prototype, "mouseWheel$", {
45101         get: function () {
45102             return this._mouseWheel$;
45103         },
45104         enumerable: true,
45105         configurable: true
45106     });
45107     Object.defineProperty(MouseService.prototype, "mouseDragStart$", {
45108         get: function () {
45109             return this._mouseDragStart$;
45110         },
45111         enumerable: true,
45112         configurable: true
45113     });
45114     Object.defineProperty(MouseService.prototype, "mouseDrag$", {
45115         get: function () {
45116             return this._mouseDrag$;
45117         },
45118         enumerable: true,
45119         configurable: true
45120     });
45121     Object.defineProperty(MouseService.prototype, "mouseDragEnd$", {
45122         get: function () {
45123             return this._mouseDragEnd$;
45124         },
45125         enumerable: true,
45126         configurable: true
45127     });
45128     Object.defineProperty(MouseService.prototype, "proximateClick$", {
45129         get: function () {
45130             return this._proximateClick$;
45131         },
45132         enumerable: true,
45133         configurable: true
45134     });
45135     Object.defineProperty(MouseService.prototype, "staticClick$", {
45136         get: function () {
45137             return this._staticClick$;
45138         },
45139         enumerable: true,
45140         configurable: true
45141     });
45142     MouseService.prototype.claimMouse = function (name, zindex) {
45143         this._claimMouse$.next({ name: name, zindex: zindex });
45144     };
45145     MouseService.prototype.unclaimMouse = function (name) {
45146         this._claimMouse$.next({ name: name, zindex: null });
45147     };
45148     MouseService.prototype.deferPixels = function (name, deferPixels) {
45149         this._deferPixelClaims$.next({ name: name, deferPixels: deferPixels });
45150     };
45151     MouseService.prototype.undeferPixels = function (name) {
45152         this._deferPixelClaims$.next({ name: name, deferPixels: null });
45153     };
45154     MouseService.prototype.claimWheel = function (name, zindex) {
45155         this._claimWheel$.next({ name: name, zindex: zindex });
45156     };
45157     MouseService.prototype.unclaimWheel = function (name) {
45158         this._claimWheel$.next({ name: name, zindex: null });
45159     };
45160     MouseService.prototype.filtered$ = function (name, observable$) {
45161         return this._filtered(name, observable$, this._mouseOwner$);
45162     };
45163     MouseService.prototype.filteredWheel$ = function (name, observable$) {
45164         return this._filtered(name, observable$, this._wheelOwner$);
45165     };
45166     MouseService.prototype._createDeferredMouseMove$ = function (origin, mouseMove$) {
45167         return mouseMove$
45168             .map(function (mouseMove) {
45169             var deltaX = mouseMove.clientX - origin.clientX;
45170             var deltaY = mouseMove.clientY - origin.clientY;
45171             return [mouseMove, Math.sqrt(deltaX * deltaX + deltaY * deltaY)];
45172         })
45173             .withLatestFrom(this._deferPixels$)
45174             .filter(function (_a) {
45175             var _b = _a[0], mouseMove = _b[0], delta = _b[1], deferPixels = _a[1];
45176             return delta > deferPixels;
45177         })
45178             .map(function (_a) {
45179             var _b = _a[0], mouseMove = _b[0], delta = _b[1], deferPixels = _a[1];
45180             return mouseMove;
45181         });
45182     };
45183     MouseService.prototype._createMouseDrag$ = function (mouseDragStartInitiate$, stop$) {
45184         var _this = this;
45185         return mouseDragStartInitiate$
45186             .map(function (_a) {
45187             var mouseDown = _a[0], mouseMove = _a[1];
45188             return mouseMove;
45189         })
45190             .switchMap(function (mouseMove) {
45191             return Observable_1.Observable
45192                 .of(mouseMove)
45193                 .concat(_this._documentMouseMove$)
45194                 .takeUntil(stop$);
45195         });
45196     };
45197     MouseService.prototype._createMouseDragEnd$ = function (mouseDragStart$, stop$) {
45198         return mouseDragStart$
45199             .switchMap(function (event) {
45200             return stop$.first();
45201         });
45202     };
45203     MouseService.prototype._createMouseDragStart$ = function (mouseDragStartInitiate$) {
45204         return mouseDragStartInitiate$
45205             .map(function (_a) {
45206             var mouseDown = _a[0], mouseMove = _a[1];
45207             return mouseDown;
45208         });
45209     };
45210     MouseService.prototype._createMouseDragInitiate$ = function (mouseDown$, stop$, defer) {
45211         var _this = this;
45212         return mouseDown$
45213             .filter(function (mouseDown) {
45214             return mouseDown.button === 0;
45215         })
45216             .switchMap(function (mouseDown) {
45217             return Observable_1.Observable
45218                 .combineLatest(Observable_1.Observable.of(mouseDown), defer ?
45219                 _this._createDeferredMouseMove$(mouseDown, _this._documentMouseMove$) :
45220                 _this._documentMouseMove$)
45221                 .takeUntil(stop$)
45222                 .take(1);
45223         });
45224     };
45225     MouseService.prototype._createOwner$ = function (claim$) {
45226         return claim$
45227             .scan(function (claims, claim) {
45228             if (claim.zindex == null) {
45229                 delete claims[claim.name];
45230             }
45231             else {
45232                 claims[claim.name] = claim.zindex;
45233             }
45234             return claims;
45235         }, {})
45236             .map(function (claims) {
45237             var owner = null;
45238             var zIndexMax = -1;
45239             for (var name_1 in claims) {
45240                 if (!claims.hasOwnProperty(name_1)) {
45241                     continue;
45242                 }
45243                 if (claims[name_1] > zIndexMax) {
45244                     zIndexMax = claims[name_1];
45245                     owner = name_1;
45246                 }
45247             }
45248             return owner;
45249         })
45250             .startWith(null);
45251     };
45252     MouseService.prototype._filtered = function (name, observable$, owner$) {
45253         return observable$
45254             .withLatestFrom(owner$)
45255             .filter(function (_a) {
45256             var item = _a[0], owner = _a[1];
45257             return owner === name;
45258         })
45259             .map(function (_a) {
45260             var item = _a[0], owner = _a[1];
45261             return item;
45262         });
45263     };
45264     return MouseService;
45265 }());
45266 exports.MouseService = MouseService;
45267 exports.default = MouseService;
45268
45269 },{"../Geo":294,"rxjs/BehaviorSubject":26,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/fromEvent":43,"rxjs/add/operator/distinctUntilChanged":60,"rxjs/add/operator/filter":63,"rxjs/add/operator/map":67,"rxjs/add/operator/merge":68,"rxjs/add/operator/mergeMap":70,"rxjs/add/operator/publishReplay":74,"rxjs/add/operator/scan":78,"rxjs/add/operator/switchMap":84,"rxjs/add/operator/withLatestFrom":90}],437:[function(require,module,exports){
45270 "use strict";
45271 /// <reference path="../../typings/index.d.ts" />
45272 Object.defineProperty(exports, "__esModule", { value: true });
45273 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
45274 var Observable_1 = require("rxjs/Observable");
45275 var ReplaySubject_1 = require("rxjs/ReplaySubject");
45276 require("rxjs/add/observable/throw");
45277 require("rxjs/add/operator/do");
45278 require("rxjs/add/operator/finally");
45279 require("rxjs/add/operator/first");
45280 require("rxjs/add/operator/map");
45281 require("rxjs/add/operator/mergeMap");
45282 var API_1 = require("../API");
45283 var Graph_1 = require("../Graph");
45284 var Edge_1 = require("../Edge");
45285 var Error_1 = require("../Error");
45286 var State_1 = require("../State");
45287 var Viewer_1 = require("../Viewer");
45288 var Navigator = /** @class */ (function () {
45289     function Navigator(clientId, options, token, apiV3, graphService, imageLoadingService, loadingService, stateService, cacheService, playService) {
45290         this._apiV3 = apiV3 != null ? apiV3 : new API_1.APIv3(clientId, token);
45291         this._imageLoadingService = imageLoadingService != null ? imageLoadingService : new Graph_1.ImageLoadingService();
45292         this._graphService = graphService != null ?
45293             graphService :
45294             new Graph_1.GraphService(new Graph_1.Graph(this.apiV3), this._imageLoadingService);
45295         this._loadingService = loadingService != null ? loadingService : new Viewer_1.LoadingService();
45296         this._loadingName = "navigator";
45297         this._stateService = stateService != null ? stateService : new State_1.StateService(options.transitionMode);
45298         this._cacheService = cacheService != null ?
45299             cacheService :
45300             new Viewer_1.CacheService(this._graphService, this._stateService);
45301         this._playService = playService != null ?
45302             playService :
45303             new Viewer_1.PlayService(this._graphService, this._stateService);
45304         this._keyRequested$ = new BehaviorSubject_1.BehaviorSubject(null);
45305         this._movedToKey$ = new BehaviorSubject_1.BehaviorSubject(null);
45306         this._request$ = null;
45307         this._requestSubscription = null;
45308         this._nodeRequestSubscription = null;
45309     }
45310     Object.defineProperty(Navigator.prototype, "apiV3", {
45311         get: function () {
45312             return this._apiV3;
45313         },
45314         enumerable: true,
45315         configurable: true
45316     });
45317     Object.defineProperty(Navigator.prototype, "cacheService", {
45318         get: function () {
45319             return this._cacheService;
45320         },
45321         enumerable: true,
45322         configurable: true
45323     });
45324     Object.defineProperty(Navigator.prototype, "graphService", {
45325         get: function () {
45326             return this._graphService;
45327         },
45328         enumerable: true,
45329         configurable: true
45330     });
45331     Object.defineProperty(Navigator.prototype, "imageLoadingService", {
45332         get: function () {
45333             return this._imageLoadingService;
45334         },
45335         enumerable: true,
45336         configurable: true
45337     });
45338     Object.defineProperty(Navigator.prototype, "loadingService", {
45339         get: function () {
45340             return this._loadingService;
45341         },
45342         enumerable: true,
45343         configurable: true
45344     });
45345     Object.defineProperty(Navigator.prototype, "movedToKey$", {
45346         get: function () {
45347             return this._movedToKey$;
45348         },
45349         enumerable: true,
45350         configurable: true
45351     });
45352     Object.defineProperty(Navigator.prototype, "playService", {
45353         get: function () {
45354             return this._playService;
45355         },
45356         enumerable: true,
45357         configurable: true
45358     });
45359     Object.defineProperty(Navigator.prototype, "stateService", {
45360         get: function () {
45361             return this._stateService;
45362         },
45363         enumerable: true,
45364         configurable: true
45365     });
45366     Navigator.prototype.moveToKey$ = function (key) {
45367         this._abortRequest("to key " + key);
45368         this._loadingService.startLoading(this._loadingName);
45369         var node$ = this._moveToKey$(key);
45370         return this._makeRequest$(node$);
45371     };
45372     Navigator.prototype.moveDir$ = function (direction) {
45373         var _this = this;
45374         this._abortRequest("in dir " + Edge_1.EdgeDirection[direction]);
45375         this._loadingService.startLoading(this._loadingName);
45376         var node$ = this.stateService.currentNode$
45377             .first()
45378             .mergeMap(function (node) {
45379             return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
45380                 node.sequenceEdges$ :
45381                 node.spatialEdges$)
45382                 .first()
45383                 .map(function (status) {
45384                 for (var _i = 0, _a = status.edges; _i < _a.length; _i++) {
45385                     var edge = _a[_i];
45386                     if (edge.data.direction === direction) {
45387                         return edge.to;
45388                     }
45389                 }
45390                 return null;
45391             });
45392         })
45393             .mergeMap(function (directionKey) {
45394             if (directionKey == null) {
45395                 _this._loadingService.stopLoading(_this._loadingName);
45396                 return Observable_1.Observable
45397                     .throw(new Error("Direction (" + direction + ") does not exist for current node."));
45398             }
45399             return _this._moveToKey$(directionKey);
45400         });
45401         return this._makeRequest$(node$);
45402     };
45403     Navigator.prototype.moveCloseTo$ = function (lat, lon) {
45404         var _this = this;
45405         this._abortRequest("to lat " + lat + ", lon " + lon);
45406         this._loadingService.startLoading(this._loadingName);
45407         var node$ = this.apiV3.imageCloseTo$(lat, lon)
45408             .mergeMap(function (fullNode) {
45409             if (fullNode == null) {
45410                 _this._loadingService.stopLoading(_this._loadingName);
45411                 return Observable_1.Observable
45412                     .throw(new Error("No image found close to lat " + lat + ", lon " + lon + "."));
45413             }
45414             return _this._moveToKey$(fullNode.key);
45415         });
45416         return this._makeRequest$(node$);
45417     };
45418     Navigator.prototype.setFilter$ = function (filter) {
45419         var _this = this;
45420         this._stateService.clearNodes();
45421         return this._movedToKey$
45422             .first()
45423             .mergeMap(function (key) {
45424             if (key != null) {
45425                 return _this._trajectoryKeys$()
45426                     .mergeMap(function (keys) {
45427                     return _this._graphService.setFilter$(filter)
45428                         .mergeMap(function () {
45429                         return _this._cacheKeys$(keys);
45430                     });
45431                 })
45432                     .last();
45433             }
45434             return _this._keyRequested$
45435                 .first()
45436                 .mergeMap(function (requestedKey) {
45437                 if (requestedKey != null) {
45438                     return _this._graphService.setFilter$(filter)
45439                         .mergeMap(function () {
45440                         return _this._graphService.cacheNode$(requestedKey);
45441                     });
45442                 }
45443                 return _this._graphService.setFilter$(filter)
45444                     .map(function () {
45445                     return undefined;
45446                 });
45447             });
45448         })
45449             .map(function (node) {
45450             return undefined;
45451         });
45452     };
45453     Navigator.prototype.setToken$ = function (token) {
45454         var _this = this;
45455         this._abortRequest("to set token");
45456         this._stateService.clearNodes();
45457         return this._movedToKey$
45458             .first()
45459             .do(function (key) {
45460             _this._apiV3.setToken(token);
45461         })
45462             .mergeMap(function (key) {
45463             return key == null ?
45464                 _this._graphService.reset$([]) :
45465                 _this._trajectoryKeys$()
45466                     .mergeMap(function (keys) {
45467                     return _this._graphService.reset$(keys)
45468                         .mergeMap(function () {
45469                         return _this._cacheKeys$(keys);
45470                     });
45471                 })
45472                     .last()
45473                     .map(function (node) {
45474                     return undefined;
45475                 });
45476         });
45477     };
45478     Navigator.prototype._cacheKeys$ = function (keys) {
45479         var _this = this;
45480         var cacheNodes$ = keys
45481             .map(function (key) {
45482             return _this._graphService.cacheNode$(key);
45483         });
45484         return Observable_1.Observable
45485             .from(cacheNodes$)
45486             .mergeAll();
45487     };
45488     Navigator.prototype._abortRequest = function (reason) {
45489         if (this._requestSubscription != null) {
45490             this._requestSubscription.unsubscribe();
45491             this._requestSubscription = null;
45492         }
45493         if (this._nodeRequestSubscription != null) {
45494             this._nodeRequestSubscription.unsubscribe();
45495             this._nodeRequestSubscription = null;
45496         }
45497         if (this._request$ != null) {
45498             this._request$.error(new Error_1.AbortMapillaryError("Request aborted by a subsequent request " + reason + "."));
45499             this._request$ = null;
45500         }
45501     };
45502     Navigator.prototype._makeRequest$ = function (node$) {
45503         var _this = this;
45504         this._request$ = new ReplaySubject_1.ReplaySubject(1);
45505         this._requestSubscription = this._request$
45506             .subscribe(undefined, function (e) { });
45507         this._nodeRequestSubscription = node$
45508             .subscribe(function (node) {
45509             _this._request$.next(node);
45510             _this._request$.complete();
45511         }, function (error) {
45512             _this._request$.error(error);
45513         });
45514         return this._request$;
45515     };
45516     Navigator.prototype._moveToKey$ = function (key) {
45517         var _this = this;
45518         this._keyRequested$.next(key);
45519         return this._graphService.cacheNode$(key)
45520             .do(function (node) {
45521             _this._stateService.setNodes([node]);
45522             _this._movedToKey$.next(node.key);
45523         })
45524             .finally(function () {
45525             _this._loadingService.stopLoading(_this._loadingName);
45526         });
45527     };
45528     Navigator.prototype._trajectoryKeys$ = function () {
45529         return this._stateService.currentState$
45530             .first()
45531             .map(function (frame) {
45532             return frame.state.trajectory
45533                 .map(function (node) {
45534                 return node.key;
45535             });
45536         });
45537     };
45538     return Navigator;
45539 }());
45540 exports.Navigator = Navigator;
45541 exports.default = Navigator;
45542
45543 },{"../API":290,"../Edge":292,"../Error":293,"../Graph":295,"../State":298,"../Viewer":302,"rxjs/BehaviorSubject":26,"rxjs/Observable":29,"rxjs/ReplaySubject":32,"rxjs/add/observable/throw":47,"rxjs/add/operator/do":61,"rxjs/add/operator/finally":64,"rxjs/add/operator/first":65,"rxjs/add/operator/map":67,"rxjs/add/operator/mergeMap":70}],438:[function(require,module,exports){
45544 "use strict";
45545 Object.defineProperty(exports, "__esModule", { value: true });
45546 var Observable_1 = require("rxjs/Observable");
45547 var Subject_1 = require("rxjs/Subject");
45548 require("rxjs/add/observable/combineLatest");
45549 require("rxjs/add/operator/distinctUntilChanged");
45550 require("rxjs/add/operator/map");
45551 require("rxjs/add/operator/throttleTime");
45552 var Viewer_1 = require("../Viewer");
45553 var Observer = /** @class */ (function () {
45554     function Observer(eventEmitter, navigator, container) {
45555         var _this = this;
45556         this._container = container;
45557         this._eventEmitter = eventEmitter;
45558         this._navigator = navigator;
45559         this._projection = new Viewer_1.Projection();
45560         this._started = false;
45561         this._navigable$ = new Subject_1.Subject();
45562         // navigable and loading should always emit, also when cover is activated.
45563         this._navigable$
45564             .subscribe(function (navigable) {
45565             _this._eventEmitter.fire(Viewer_1.Viewer.navigablechanged, navigable);
45566         });
45567         this._navigator.loadingService.loading$
45568             .subscribe(function (loading) {
45569             _this._eventEmitter.fire(Viewer_1.Viewer.loadingchanged, loading);
45570         });
45571     }
45572     Object.defineProperty(Observer.prototype, "started", {
45573         get: function () {
45574             return this._started;
45575         },
45576         enumerable: true,
45577         configurable: true
45578     });
45579     Object.defineProperty(Observer.prototype, "navigable$", {
45580         get: function () {
45581             return this._navigable$;
45582         },
45583         enumerable: true,
45584         configurable: true
45585     });
45586     Observer.prototype.projectBasic$ = function (basicPoint) {
45587         var _this = this;
45588         return Observable_1.Observable
45589             .combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
45590             .first()
45591             .map(function (_a) {
45592             var render = _a[0], transform = _a[1];
45593             var canvasPoint = _this._projection.basicToCanvas(basicPoint, _this._container.element, render, transform);
45594             return [Math.round(canvasPoint[0]), Math.round(canvasPoint[1])];
45595         });
45596     };
45597     Observer.prototype.startEmit = function () {
45598         var _this = this;
45599         if (this._started) {
45600             return;
45601         }
45602         this._started = true;
45603         this._currentNodeSubscription = this._navigator.stateService.currentNodeExternal$
45604             .subscribe(function (node) {
45605             _this._eventEmitter.fire(Viewer_1.Viewer.nodechanged, node);
45606         });
45607         this._sequenceEdgesSubscription = this._navigator.stateService.currentNodeExternal$
45608             .switchMap(function (node) {
45609             return node.sequenceEdges$;
45610         })
45611             .subscribe(function (status) {
45612             _this._eventEmitter.fire(Viewer_1.Viewer.sequenceedgeschanged, status);
45613         });
45614         this._spatialEdgesSubscription = this._navigator.stateService.currentNodeExternal$
45615             .switchMap(function (node) {
45616             return node.spatialEdges$;
45617         })
45618             .subscribe(function (status) {
45619             _this._eventEmitter.fire(Viewer_1.Viewer.spatialedgeschanged, status);
45620         });
45621         this._moveSubscription = Observable_1.Observable
45622             .combineLatest(this._navigator.stateService.inMotion$, this._container.mouseService.active$, this._container.touchService.active$)
45623             .map(function (values) {
45624             return values[0] || values[1] || values[2];
45625         })
45626             .distinctUntilChanged()
45627             .subscribe(function (started) {
45628             if (started) {
45629                 _this._eventEmitter.fire(Viewer_1.Viewer.movestart, null);
45630             }
45631             else {
45632                 _this._eventEmitter.fire(Viewer_1.Viewer.moveend, null);
45633             }
45634         });
45635         this._bearingSubscription = this._container.renderService.bearing$
45636             .throttleTime(100)
45637             .distinctUntilChanged(function (b1, b2) {
45638             return Math.abs(b2 - b1) < 1;
45639         })
45640             .subscribe(function (bearing) {
45641             _this._eventEmitter.fire(Viewer_1.Viewer.bearingchanged, bearing);
45642         });
45643         var mouseMove$ = this._container.mouseService.active$
45644             .switchMap(function (active) {
45645             return active ?
45646                 Observable_1.Observable.empty() :
45647                 _this._container.mouseService.mouseMove$;
45648         });
45649         this._viewerMouseEventSubscription = Observable_1.Observable
45650             .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$))
45651             .withLatestFrom(this._container.renderService.renderCamera$, this._navigator.stateService.reference$, this._navigator.stateService.currentTransform$)
45652             .map(function (_a) {
45653             var _b = _a[0], type = _b[0], event = _b[1], render = _a[1], reference = _a[2], transform = _a[3];
45654             var unprojection = _this._projection.eventToUnprojection(event, _this._container.element, render, reference, transform);
45655             return {
45656                 basicPoint: unprojection.basicPoint,
45657                 latLon: unprojection.latLon,
45658                 originalEvent: event,
45659                 pixelPoint: unprojection.pixelPoint,
45660                 target: _this._eventEmitter,
45661                 type: type,
45662             };
45663         })
45664             .subscribe(function (event) {
45665             _this._eventEmitter.fire(event.type, event);
45666         });
45667     };
45668     Observer.prototype.stopEmit = function () {
45669         if (!this.started) {
45670             return;
45671         }
45672         this._started = false;
45673         this._bearingSubscription.unsubscribe();
45674         this._currentNodeSubscription.unsubscribe();
45675         this._moveSubscription.unsubscribe();
45676         this._sequenceEdgesSubscription.unsubscribe();
45677         this._spatialEdgesSubscription.unsubscribe();
45678         this._viewerMouseEventSubscription.unsubscribe();
45679         this._bearingSubscription = null;
45680         this._currentNodeSubscription = null;
45681         this._moveSubscription = null;
45682         this._sequenceEdgesSubscription = null;
45683         this._spatialEdgesSubscription = null;
45684         this._viewerMouseEventSubscription = null;
45685     };
45686     Observer.prototype.unproject$ = function (canvasPoint) {
45687         var _this = this;
45688         return Observable_1.Observable
45689             .combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.reference$, this._navigator.stateService.currentTransform$)
45690             .first()
45691             .map(function (_a) {
45692             var render = _a[0], reference = _a[1], transform = _a[2];
45693             var unprojection = _this._projection.canvasToUnprojection(canvasPoint, _this._container.element, render, reference, transform);
45694             return unprojection.latLon;
45695         });
45696     };
45697     Observer.prototype.unprojectBasic$ = function (canvasPoint) {
45698         var _this = this;
45699         return Observable_1.Observable
45700             .combineLatest(this._container.renderService.renderCamera$, this._navigator.stateService.currentTransform$)
45701             .first()
45702             .map(function (_a) {
45703             var render = _a[0], transform = _a[1];
45704             return _this._projection.canvasToBasic(canvasPoint, _this._container.element, render, transform);
45705         });
45706     };
45707     Observer.prototype._mapMouseEvent$ = function (type, mouseEvent$) {
45708         return mouseEvent$.map(function (event) {
45709             return [type, event];
45710         });
45711     };
45712     return Observer;
45713 }());
45714 exports.Observer = Observer;
45715 exports.default = Observer;
45716
45717 },{"../Viewer":302,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/combineLatest":38,"rxjs/add/operator/distinctUntilChanged":60,"rxjs/add/operator/map":67,"rxjs/add/operator/throttleTime":88}],439:[function(require,module,exports){
45718 "use strict";
45719 Object.defineProperty(exports, "__esModule", { value: true });
45720 var Observable_1 = require("rxjs/Observable");
45721 var Subject_1 = require("rxjs/Subject");
45722 require("rxjs/add/operator/timeout");
45723 var Edge_1 = require("../Edge");
45724 var Graph_1 = require("../Graph");
45725 var PlayService = /** @class */ (function () {
45726     function PlayService(graphService, stateService, graphCalculator) {
45727         this._graphService = graphService;
45728         this._stateService = stateService;
45729         this._graphCalculator = !!graphCalculator ? graphCalculator : new Graph_1.GraphCalculator();
45730         this._directionSubject$ = new Subject_1.Subject();
45731         this._direction$ = this._directionSubject$
45732             .startWith(Edge_1.EdgeDirection.Next)
45733             .publishReplay(1)
45734             .refCount();
45735         this._direction$.subscribe();
45736         this._playing = false;
45737         this._playingSubject$ = new Subject_1.Subject();
45738         this._playing$ = this._playingSubject$
45739             .startWith(this._playing)
45740             .publishReplay(1)
45741             .refCount();
45742         this._playing$.subscribe();
45743         this._speed = 0.5;
45744         this._speedSubject$ = new Subject_1.Subject();
45745         this._speed$ = this._speedSubject$
45746             .startWith(this._speed)
45747             .publishReplay(1)
45748             .refCount();
45749         this._speed$.subscribe();
45750         this._nodesAhead = this._mapNodesAhead(this._mapSpeed(this._speed));
45751         this._bridging$ = null;
45752     }
45753     Object.defineProperty(PlayService.prototype, "playing", {
45754         get: function () {
45755             return this._playing;
45756         },
45757         enumerable: true,
45758         configurable: true
45759     });
45760     Object.defineProperty(PlayService.prototype, "direction$", {
45761         get: function () {
45762             return this._direction$;
45763         },
45764         enumerable: true,
45765         configurable: true
45766     });
45767     Object.defineProperty(PlayService.prototype, "playing$", {
45768         get: function () {
45769             return this._playing$;
45770         },
45771         enumerable: true,
45772         configurable: true
45773     });
45774     Object.defineProperty(PlayService.prototype, "speed$", {
45775         get: function () {
45776             return this._speed$;
45777         },
45778         enumerable: true,
45779         configurable: true
45780     });
45781     PlayService.prototype.play = function () {
45782         var _this = this;
45783         if (this._playing) {
45784             return;
45785         }
45786         this._stateService.cutNodes();
45787         var stateSpeed = this._setSpeed(this._speed);
45788         this._stateService.setSpeed(stateSpeed);
45789         this._graphModeSubscription = this._speed$
45790             .map(function (speed) {
45791             return speed > 0.54 ? Graph_1.GraphMode.Sequence : Graph_1.GraphMode.Spatial;
45792         })
45793             .distinctUntilChanged()
45794             .subscribe(function (mode) {
45795             _this._graphService.setGraphMode(mode);
45796         });
45797         this._cacheSubscription = this._stateService.currentNode$
45798             .map(function (node) {
45799             return [node.sequenceKey, node.key];
45800         })
45801             .distinctUntilChanged(undefined, function (_a) {
45802             var sequenceKey = _a[0], nodeKey = _a[1];
45803             return sequenceKey;
45804         })
45805             .combineLatest(this._graphService.graphMode$, this._direction$)
45806             .switchMap(function (_a) {
45807             var _b = _a[0], sequenceKey = _b[0], nodeKey = _b[1], mode = _a[1], direction = _a[2];
45808             if (direction !== Edge_1.EdgeDirection.Next && direction !== Edge_1.EdgeDirection.Prev) {
45809                 return Observable_1.Observable.of([undefined, direction]);
45810             }
45811             var sequence$ = (mode === Graph_1.GraphMode.Sequence ?
45812                 _this._graphService.cacheSequenceNodes$(sequenceKey, nodeKey) :
45813                 _this._graphService.cacheSequence$(sequenceKey))
45814                 .retry(3)
45815                 .catch(function (error) {
45816                 console.error(error);
45817                 return Observable_1.Observable.of(undefined);
45818             });
45819             return Observable_1.Observable
45820                 .combineLatest(sequence$, Observable_1.Observable.of(direction));
45821         })
45822             .switchMap(function (_a) {
45823             var sequence = _a[0], direction = _a[1];
45824             if (sequence === undefined) {
45825                 return Observable_1.Observable.empty();
45826             }
45827             var sequenceKeys = sequence.keys.slice();
45828             if (direction === Edge_1.EdgeDirection.Prev) {
45829                 sequenceKeys.reverse();
45830             }
45831             return _this._stateService.currentState$
45832                 .map(function (frame) {
45833                 return [frame.state.trajectory[frame.state.trajectory.length - 1].key, frame.state.nodesAhead];
45834             })
45835                 .scan(function (_a, _b) {
45836                 var lastRequestKey = _a[0], previousRequestKeys = _a[1];
45837                 var lastTrajectoryKey = _b[0], nodesAhead = _b[1];
45838                 if (lastRequestKey === undefined) {
45839                     lastRequestKey = lastTrajectoryKey;
45840                 }
45841                 var lastIndex = sequenceKeys.length - 1;
45842                 if (nodesAhead >= _this._nodesAhead || sequenceKeys[lastIndex] === lastRequestKey) {
45843                     return [lastRequestKey, []];
45844                 }
45845                 var current = sequenceKeys.indexOf(lastTrajectoryKey);
45846                 var start = sequenceKeys.indexOf(lastRequestKey) + 1;
45847                 var end = Math.min(lastIndex, current + _this._nodesAhead - nodesAhead) + 1;
45848                 if (end <= start) {
45849                     return [lastRequestKey, []];
45850                 }
45851                 return [sequenceKeys[end - 1], sequenceKeys.slice(start, end)];
45852             }, [undefined, []])
45853                 .mergeMap(function (_a) {
45854                 var lastRequestKey = _a[0], newRequestKeys = _a[1];
45855                 return Observable_1.Observable.from(newRequestKeys);
45856             });
45857         })
45858             .mergeMap(function (key) {
45859             return _this._graphService.cacheNode$(key)
45860                 .catch(function () {
45861                 return Observable_1.Observable.empty();
45862             });
45863         }, 6)
45864             .subscribe();
45865         this._playingSubscription = this._stateService.currentState$
45866             .filter(function (frame) {
45867             return frame.state.nodesAhead < _this._nodesAhead;
45868         })
45869             .distinctUntilChanged(undefined, function (frame) {
45870             return frame.state.lastNode.key;
45871         })
45872             .map(function (frame) {
45873             var lastNode = frame.state.lastNode;
45874             var trajectory = frame.state.trajectory;
45875             var increasingTime = undefined;
45876             for (var i = trajectory.length - 2; i >= 0; i--) {
45877                 var node = trajectory[i];
45878                 if (node.sequenceKey !== lastNode.sequenceKey) {
45879                     break;
45880                 }
45881                 if (node.capturedAt !== lastNode.capturedAt) {
45882                     increasingTime = node.capturedAt < lastNode.capturedAt;
45883                     break;
45884                 }
45885             }
45886             return [frame.state.lastNode, increasingTime];
45887         })
45888             .withLatestFrom(this._direction$)
45889             .switchMap(function (_a) {
45890             var _b = _a[0], node = _b[0], increasingTime = _b[1], direction = _a[1];
45891             return ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
45892                 node.sequenceEdges$ :
45893                 node.spatialEdges$)
45894                 .first(function (status) {
45895                 return status.cached;
45896             })
45897                 .timeout(15000)
45898                 .zip(Observable_1.Observable.of(direction))
45899                 .map(function (_a) {
45900                 var s = _a[0], d = _a[1];
45901                 for (var _i = 0, _b = s.edges; _i < _b.length; _i++) {
45902                     var edge = _b[_i];
45903                     if (edge.data.direction === d) {
45904                         return edge.to;
45905                     }
45906                 }
45907                 return null;
45908             })
45909                 .switchMap(function (key) {
45910                 return key != null ?
45911                     _this._graphService.cacheNode$(key) :
45912                     _this._bridge$(node, increasingTime)
45913                         .filter(function (n) {
45914                         return !!n;
45915                     });
45916             });
45917         })
45918             .subscribe(function (node) {
45919             _this._stateService.appendNodes([node]);
45920         }, function (error) {
45921             console.error(error);
45922             _this.stop();
45923         });
45924         this._clearSubscription = this._stateService.currentNode$
45925             .bufferCount(1, 10)
45926             .subscribe(function (nodes) {
45927             _this._stateService.clearPriorNodes();
45928         });
45929         this._setPlaying(true);
45930         var currentLastNodes$ = this._stateService.currentState$
45931             .map(function (frame) {
45932             return frame.state;
45933         })
45934             .distinctUntilChanged(function (_a, _b) {
45935             var kc1 = _a[0], kl1 = _a[1];
45936             var kc2 = _b[0], kl2 = _b[1];
45937             return kc1 === kc2 && kl1 === kl2;
45938         }, function (state) {
45939             return [state.currentNode.key, state.lastNode.key];
45940         })
45941             .filter(function (state) {
45942             return state.currentNode.key === state.lastNode.key &&
45943                 state.currentIndex === state.trajectory.length - 1;
45944         })
45945             .map(function (state) {
45946             return state.currentNode;
45947         });
45948         this._stopSubscription = Observable_1.Observable
45949             .combineLatest(currentLastNodes$, this._direction$)
45950             .switchMap(function (_a) {
45951             var node = _a[0], direction = _a[1];
45952             var edgeStatus$ = ([Edge_1.EdgeDirection.Next, Edge_1.EdgeDirection.Prev].indexOf(direction) > -1 ?
45953                 node.sequenceEdges$ :
45954                 node.spatialEdges$)
45955                 .first(function (status) {
45956                 return status.cached;
45957             })
45958                 .timeout(15000)
45959                 .catch(function (error) {
45960                 console.error(error);
45961                 return Observable_1.Observable.of({ cached: false, edges: [] });
45962             });
45963             return Observable_1.Observable
45964                 .combineLatest(Observable_1.Observable.of(direction), edgeStatus$)
45965                 .map(function (_a) {
45966                 var d = _a[0], es = _a[1];
45967                 for (var _i = 0, _b = es.edges; _i < _b.length; _i++) {
45968                     var edge = _b[_i];
45969                     if (edge.data.direction === d) {
45970                         return true;
45971                     }
45972                 }
45973                 return false;
45974             });
45975         })
45976             .mergeMap(function (hasEdge) {
45977             if (hasEdge || !_this._bridging$) {
45978                 return Observable_1.Observable.of(hasEdge);
45979             }
45980             return _this._bridging$
45981                 .map(function (node) {
45982                 return node != null;
45983             })
45984                 .catch(function (error) {
45985                 console.error(error);
45986                 return Observable_1.Observable.of(false);
45987             });
45988         })
45989             .first(function (hasEdge) {
45990             return !hasEdge;
45991         })
45992             .subscribe(undefined, undefined, function () { _this.stop(); });
45993         if (this._stopSubscription.closed) {
45994             this._stopSubscription = null;
45995         }
45996     };
45997     PlayService.prototype.setDirection = function (direction) {
45998         this._directionSubject$.next(direction);
45999     };
46000     PlayService.prototype.setSpeed = function (speed) {
46001         speed = Math.max(0, Math.min(1, speed));
46002         if (speed === this._speed) {
46003             return;
46004         }
46005         var stateSpeed = this._setSpeed(speed);
46006         if (this._playing) {
46007             this._stateService.setSpeed(stateSpeed);
46008         }
46009         this._speedSubject$.next(this._speed);
46010     };
46011     PlayService.prototype.stop = function () {
46012         if (!this._playing) {
46013             return;
46014         }
46015         if (!!this._stopSubscription) {
46016             if (!this._stopSubscription.closed) {
46017                 this._stopSubscription.unsubscribe();
46018             }
46019             this._stopSubscription = null;
46020         }
46021         this._graphModeSubscription.unsubscribe();
46022         this._graphModeSubscription = null;
46023         this._cacheSubscription.unsubscribe();
46024         this._cacheSubscription = null;
46025         this._playingSubscription.unsubscribe();
46026         this._playingSubscription = null;
46027         this._clearSubscription.unsubscribe();
46028         this._clearSubscription = null;
46029         this._stateService.setSpeed(1);
46030         this._stateService.cutNodes();
46031         this._graphService.setGraphMode(Graph_1.GraphMode.Spatial);
46032         this._setPlaying(false);
46033     };
46034     PlayService.prototype._bridge$ = function (node, increasingTime) {
46035         var _this = this;
46036         if (increasingTime === undefined) {
46037             return Observable_1.Observable.of(null);
46038         }
46039         var boundingBox = this._graphCalculator.boundingBoxCorners(node.latLon, 25);
46040         this._bridging$ = this._graphService.cacheBoundingBox$(boundingBox[0], boundingBox[1])
46041             .mergeMap(function (nodes) {
46042             var nextNode = null;
46043             for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
46044                 var n = nodes_1[_i];
46045                 if (n.sequenceKey === node.sequenceKey ||
46046                     !n.cameraUuid ||
46047                     n.cameraUuid !== node.cameraUuid ||
46048                     n.capturedAt === node.capturedAt ||
46049                     n.capturedAt > node.capturedAt !== increasingTime) {
46050                     continue;
46051                 }
46052                 var delta = Math.abs(n.capturedAt - node.capturedAt);
46053                 if (delta > 15000) {
46054                     continue;
46055                 }
46056                 if (!nextNode || delta < Math.abs(nextNode.capturedAt - node.capturedAt)) {
46057                     nextNode = n;
46058                 }
46059             }
46060             return !!nextNode ?
46061                 _this._graphService.cacheNode$(nextNode.key) :
46062                 Observable_1.Observable.of(null);
46063         })
46064             .finally(function () {
46065             _this._bridging$ = null;
46066         })
46067             .publish()
46068             .refCount();
46069         return this._bridging$;
46070     };
46071     PlayService.prototype._mapSpeed = function (speed) {
46072         var x = 2 * speed - 1;
46073         return Math.pow(10, x) - 0.2 * x;
46074     };
46075     PlayService.prototype._mapNodesAhead = function (stateSpeed) {
46076         return Math.round(Math.max(10, Math.min(50, 8 + 6 * stateSpeed)));
46077     };
46078     PlayService.prototype._setPlaying = function (playing) {
46079         this._playing = playing;
46080         this._playingSubject$.next(playing);
46081     };
46082     PlayService.prototype._setSpeed = function (speed) {
46083         this._speed = speed;
46084         var stateSpeed = this._mapSpeed(this._speed);
46085         this._nodesAhead = this._mapNodesAhead(stateSpeed);
46086         return stateSpeed;
46087     };
46088     return PlayService;
46089 }());
46090 exports.PlayService = PlayService;
46091 exports.default = PlayService;
46092
46093 },{"../Edge":292,"../Graph":295,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/operator/timeout":89}],440:[function(require,module,exports){
46094 "use strict";
46095 /// <reference path="../../typings/index.d.ts" />
46096 Object.defineProperty(exports, "__esModule", { value: true });
46097 var THREE = require("three");
46098 var Geo_1 = require("../Geo");
46099 var Projection = /** @class */ (function () {
46100     function Projection(geoCoords, viewportCoords) {
46101         this._geoCoords = !!geoCoords ? geoCoords : new Geo_1.GeoCoords();
46102         this._viewportCoords = !!viewportCoords ? viewportCoords : new Geo_1.ViewportCoords();
46103     }
46104     Projection.prototype.basicToCanvas = function (basicPoint, container, render, transform) {
46105         return this._viewportCoords
46106             .basicToCanvas(basicPoint[0], basicPoint[1], container, transform, render.perspective);
46107     };
46108     Projection.prototype.canvasToBasic = function (canvasPoint, container, render, transform) {
46109         var basicPoint = this._viewportCoords
46110             .canvasToBasic(canvasPoint[0], canvasPoint[1], container, transform, render.perspective);
46111         if (basicPoint[0] < 0 || basicPoint[0] > 1 || basicPoint[1] < 0 || basicPoint[1] > 1) {
46112             basicPoint = null;
46113         }
46114         return basicPoint;
46115     };
46116     Projection.prototype.eventToUnprojection = function (event, container, render, reference, transform) {
46117         var pixelPoint = this._viewportCoords.canvasPosition(event, container);
46118         return this.canvasToUnprojection(pixelPoint, container, render, reference, transform);
46119     };
46120     Projection.prototype.canvasToUnprojection = function (canvasPoint, container, render, reference, transform) {
46121         var canvasX = canvasPoint[0];
46122         var canvasY = canvasPoint[1];
46123         var _a = this._viewportCoords.canvasToViewport(canvasX, canvasY, container), viewportX = _a[0], viewportY = _a[1];
46124         var point3d = new THREE.Vector3(viewportX, viewportY, 1)
46125             .unproject(render.perspective);
46126         var basicPoint = transform.projectBasic(point3d.toArray());
46127         if (basicPoint[0] < 0 || basicPoint[0] > 1 || basicPoint[1] < 0 || basicPoint[1] > 1) {
46128             basicPoint = null;
46129         }
46130         var direction3d = point3d.clone().sub(render.camera.position).normalize();
46131         var dist = -2 / direction3d.z;
46132         var latLon = null;
46133         if (dist > 0 && dist < 100 && !!basicPoint) {
46134             var point = direction3d.clone().multiplyScalar(dist).add(render.camera.position);
46135             var latLonArray = this._geoCoords
46136                 .enuToGeodetic(point.x, point.y, point.z, reference.lat, reference.lon, reference.alt)
46137                 .slice(0, 2);
46138             latLon = { lat: latLonArray[0], lon: latLonArray[1] };
46139         }
46140         var unprojection = {
46141             basicPoint: basicPoint,
46142             latLon: latLon,
46143             pixelPoint: [canvasX, canvasY],
46144         };
46145         return unprojection;
46146     };
46147     return Projection;
46148 }());
46149 exports.Projection = Projection;
46150 exports.default = Projection;
46151
46152 },{"../Geo":294,"three":241}],441:[function(require,module,exports){
46153 "use strict";
46154 /// <reference path="../../typings/index.d.ts" />
46155 Object.defineProperty(exports, "__esModule", { value: true });
46156 var THREE = require("three");
46157 var vd = require("virtual-dom");
46158 var Subject_1 = require("rxjs/Subject");
46159 require("rxjs/add/operator/publishReplay");
46160 require("rxjs/add/operator/scan");
46161 require("rxjs/add/operator/startWith");
46162 var Viewer_1 = require("../Viewer");
46163 var SpriteAtlas = /** @class */ (function () {
46164     function SpriteAtlas() {
46165     }
46166     Object.defineProperty(SpriteAtlas.prototype, "json", {
46167         set: function (value) {
46168             this._json = value;
46169         },
46170         enumerable: true,
46171         configurable: true
46172     });
46173     Object.defineProperty(SpriteAtlas.prototype, "image", {
46174         set: function (value) {
46175             this._image = value;
46176             this._texture = new THREE.Texture(this._image);
46177             this._texture.minFilter = THREE.NearestFilter;
46178         },
46179         enumerable: true,
46180         configurable: true
46181     });
46182     Object.defineProperty(SpriteAtlas.prototype, "loaded", {
46183         get: function () {
46184             return !!(this._image && this._json);
46185         },
46186         enumerable: true,
46187         configurable: true
46188     });
46189     SpriteAtlas.prototype.getGLSprite = function (name) {
46190         if (!this.loaded) {
46191             throw new Error("Sprites cannot be retrieved before the atlas is loaded.");
46192         }
46193         var definition = this._json[name];
46194         if (!definition) {
46195             console.warn("Sprite with key" + name + "does not exist in sprite definition.");
46196             return new THREE.Object3D();
46197         }
46198         var texture = this._texture.clone();
46199         texture.needsUpdate = true;
46200         var width = this._image.width;
46201         var height = this._image.height;
46202         texture.offset.x = definition.x / width;
46203         texture.offset.y = (height - definition.y - definition.height) / height;
46204         texture.repeat.x = definition.width / width;
46205         texture.repeat.y = definition.height / height;
46206         var material = new THREE.SpriteMaterial({ map: texture });
46207         return new THREE.Sprite(material);
46208     };
46209     SpriteAtlas.prototype.getDOMSprite = function (name, float) {
46210         if (!this.loaded) {
46211             throw new Error("Sprites cannot be retrieved before the atlas is loaded.");
46212         }
46213         if (float == null) {
46214             float = Viewer_1.Alignment.Center;
46215         }
46216         var definition = this._json[name];
46217         if (!definition) {
46218             console.warn("Sprite with key" + name + "does not exist in sprite definition.");
46219             return vd.h("div", {}, []);
46220         }
46221         var clipTop = definition.y;
46222         var clipRigth = definition.x + definition.width;
46223         var clipBottom = definition.y + definition.height;
46224         var clipLeft = definition.x;
46225         var left = -definition.x;
46226         var top = -definition.y;
46227         var height = this._image.height;
46228         var width = this._image.width;
46229         switch (float) {
46230             case Viewer_1.Alignment.Bottom:
46231             case Viewer_1.Alignment.Center:
46232             case Viewer_1.Alignment.Top:
46233                 left -= definition.width / 2;
46234                 break;
46235             case Viewer_1.Alignment.BottomLeft:
46236             case Viewer_1.Alignment.Left:
46237             case Viewer_1.Alignment.TopLeft:
46238                 left -= definition.width;
46239                 break;
46240             case Viewer_1.Alignment.BottomRight:
46241             case Viewer_1.Alignment.Right:
46242             case Viewer_1.Alignment.TopRight:
46243             default:
46244                 break;
46245         }
46246         switch (float) {
46247             case Viewer_1.Alignment.Center:
46248             case Viewer_1.Alignment.Left:
46249             case Viewer_1.Alignment.Right:
46250                 top -= definition.height / 2;
46251                 break;
46252             case Viewer_1.Alignment.Top:
46253             case Viewer_1.Alignment.TopLeft:
46254             case Viewer_1.Alignment.TopRight:
46255                 top -= definition.height;
46256                 break;
46257             case Viewer_1.Alignment.Bottom:
46258             case Viewer_1.Alignment.BottomLeft:
46259             case Viewer_1.Alignment.BottomRight:
46260             default:
46261                 break;
46262         }
46263         var pixelRatioInverse = 1 / definition.pixelRatio;
46264         clipTop *= pixelRatioInverse;
46265         clipRigth *= pixelRatioInverse;
46266         clipBottom *= pixelRatioInverse;
46267         clipLeft *= pixelRatioInverse;
46268         left *= pixelRatioInverse;
46269         top *= pixelRatioInverse;
46270         height *= pixelRatioInverse;
46271         width *= pixelRatioInverse;
46272         var properties = {
46273             src: this._image.src,
46274             style: {
46275                 clip: "rect(" + clipTop + "px, " + clipRigth + "px, " + clipBottom + "px, " + clipLeft + "px)",
46276                 height: height + "px",
46277                 left: left + "px",
46278                 position: "absolute",
46279                 top: top + "px",
46280                 width: width + "px",
46281             },
46282         };
46283         return vd.h("img", properties, []);
46284     };
46285     return SpriteAtlas;
46286 }());
46287 var SpriteService = /** @class */ (function () {
46288     function SpriteService(sprite) {
46289         var _this = this;
46290         this._retina = window.devicePixelRatio > 1;
46291         this._spriteAtlasOperation$ = new Subject_1.Subject();
46292         this._spriteAtlas$ = this._spriteAtlasOperation$
46293             .startWith(function (atlas) {
46294             return atlas;
46295         })
46296             .scan(function (atlas, operation) {
46297             return operation(atlas);
46298         }, new SpriteAtlas())
46299             .publishReplay(1)
46300             .refCount();
46301         this._spriteAtlas$.subscribe(function () { });
46302         if (sprite == null) {
46303             return;
46304         }
46305         var format = this._retina ? "@2x" : "";
46306         var imageXmlHTTP = new XMLHttpRequest();
46307         imageXmlHTTP.open("GET", sprite + format + ".png", true);
46308         imageXmlHTTP.responseType = "arraybuffer";
46309         imageXmlHTTP.onload = function () {
46310             var image = new Image();
46311             image.onload = function () {
46312                 _this._spriteAtlasOperation$.next(function (atlas) {
46313                     atlas.image = image;
46314                     return atlas;
46315                 });
46316             };
46317             var blob = new Blob([imageXmlHTTP.response]);
46318             image.src = window.URL.createObjectURL(blob);
46319         };
46320         imageXmlHTTP.onerror = function (error) {
46321             console.error(new Error("Failed to fetch sprite sheet (" + sprite + format + ".png)"));
46322         };
46323         imageXmlHTTP.send();
46324         var jsonXmlHTTP = new XMLHttpRequest();
46325         jsonXmlHTTP.open("GET", sprite + format + ".json", true);
46326         jsonXmlHTTP.responseType = "text";
46327         jsonXmlHTTP.onload = function () {
46328             var json = JSON.parse(jsonXmlHTTP.response);
46329             _this._spriteAtlasOperation$.next(function (atlas) {
46330                 atlas.json = json;
46331                 return atlas;
46332             });
46333         };
46334         jsonXmlHTTP.onerror = function (error) {
46335             console.error(new Error("Failed to fetch sheet (" + sprite + format + ".json)"));
46336         };
46337         jsonXmlHTTP.send();
46338     }
46339     Object.defineProperty(SpriteService.prototype, "spriteAtlas$", {
46340         get: function () {
46341             return this._spriteAtlas$;
46342         },
46343         enumerable: true,
46344         configurable: true
46345     });
46346     return SpriteService;
46347 }());
46348 exports.SpriteService = SpriteService;
46349 exports.default = SpriteService;
46350
46351 },{"../Viewer":302,"rxjs/Subject":34,"rxjs/add/operator/publishReplay":74,"rxjs/add/operator/scan":78,"rxjs/add/operator/startWith":83,"three":241,"virtual-dom":247}],442:[function(require,module,exports){
46352 "use strict";
46353 Object.defineProperty(exports, "__esModule", { value: true });
46354 var BehaviorSubject_1 = require("rxjs/BehaviorSubject");
46355 var Observable_1 = require("rxjs/Observable");
46356 var Subject_1 = require("rxjs/Subject");
46357 require("rxjs/add/observable/timer");
46358 require("rxjs/add/operator/bufferWhen");
46359 require("rxjs/add/operator/filter");
46360 require("rxjs/add/operator/map");
46361 require("rxjs/add/operator/merge");
46362 require("rxjs/add/operator/scan");
46363 require("rxjs/add/operator/switchMap");
46364 var TouchService = /** @class */ (function () {
46365     function TouchService(canvasContainer, domContainer) {
46366         var _this = this;
46367         this._activeSubject$ = new BehaviorSubject_1.BehaviorSubject(false);
46368         this._active$ = this._activeSubject$
46369             .distinctUntilChanged()
46370             .publishReplay(1)
46371             .refCount();
46372         Observable_1.Observable.fromEvent(domContainer, "touchmove")
46373             .subscribe(function (event) {
46374             event.preventDefault();
46375         });
46376         this._touchStart$ = Observable_1.Observable.fromEvent(canvasContainer, "touchstart");
46377         this._touchMove$ = Observable_1.Observable.fromEvent(canvasContainer, "touchmove");
46378         this._touchEnd$ = Observable_1.Observable.fromEvent(canvasContainer, "touchend");
46379         this._touchCancel$ = Observable_1.Observable.fromEvent(canvasContainer, "touchcancel");
46380         var tapStart$ = this._touchStart$
46381             .filter(function (te) {
46382             return te.touches.length === 1 && te.targetTouches.length === 1;
46383         })
46384             .share();
46385         this._doubleTap$ = tapStart$
46386             .bufferWhen(function () {
46387             return tapStart$
46388                 .first()
46389                 .switchMap(function (event) {
46390                 return Observable_1.Observable
46391                     .timer(300)
46392                     .merge(tapStart$)
46393                     .take(1);
46394             });
46395         })
46396             .filter(function (events) {
46397             return events.length === 2;
46398         })
46399             .map(function (events) {
46400             return events[events.length - 1];
46401         })
46402             .share();
46403         this._doubleTap$
46404             .subscribe(function (event) {
46405             event.preventDefault();
46406         });
46407         this._singleTouchMove$ = this._touchMove$
46408             .filter(function (te) {
46409             return te.touches.length === 1 && te.targetTouches.length === 1;
46410         })
46411             .share();
46412         var singleTouchStart$ = Observable_1.Observable
46413             .merge(this._touchStart$, this._touchEnd$, this._touchCancel$)
46414             .filter(function (te) {
46415             return te.touches.length === 1 && te.targetTouches.length === 1;
46416         });
46417         var multipleTouchStart$ = Observable_1.Observable
46418             .merge(this._touchStart$, this._touchEnd$, this._touchCancel$)
46419             .filter(function (te) {
46420             return te.touches.length >= 1;
46421         });
46422         var touchStop$ = Observable_1.Observable
46423             .merge(this._touchEnd$, this._touchCancel$)
46424             .filter(function (te) {
46425             return te.touches.length === 0;
46426         });
46427         this._singleTouchDragStart$ = singleTouchStart$
46428             .mergeMap(function (e) {
46429             return _this._singleTouchMove$
46430                 .takeUntil(Observable_1.Observable.merge(touchStop$, multipleTouchStart$))
46431                 .take(1);
46432         });
46433         this._singleTouchDragEnd$ = singleTouchStart$
46434             .mergeMap(function (e) {
46435             return Observable_1.Observable
46436                 .merge(touchStop$, multipleTouchStart$)
46437                 .first();
46438         });
46439         this._singleTouchDrag$ = singleTouchStart$
46440             .switchMap(function (te) {
46441             return _this._singleTouchMove$
46442                 .skip(1)
46443                 .takeUntil(Observable_1.Observable
46444                 .merge(multipleTouchStart$, touchStop$));
46445         });
46446         var touchesChanged$ = Observable_1.Observable
46447             .merge(this._touchStart$, this._touchEnd$, this._touchCancel$);
46448         this._pinchStart$ = touchesChanged$
46449             .filter(function (te) {
46450             return te.touches.length === 2 && te.targetTouches.length === 2;
46451         });
46452         this._pinchEnd$ = touchesChanged$
46453             .filter(function (te) {
46454             return te.touches.length !== 2 || te.targetTouches.length !== 2;
46455         });
46456         this._pinchOperation$ = new Subject_1.Subject();
46457         this._pinch$ = this._pinchOperation$
46458             .scan(function (pinch, operation) {
46459             return operation(pinch);
46460         }, {
46461             changeX: 0,
46462             changeY: 0,
46463             clientX: 0,
46464             clientY: 0,
46465             distance: 0,
46466             distanceChange: 0,
46467             distanceX: 0,
46468             distanceY: 0,
46469             originalEvent: null,
46470             pageX: 0,
46471             pageY: 0,
46472             screenX: 0,
46473             screenY: 0,
46474             touch1: null,
46475             touch2: null,
46476         });
46477         this._touchMove$
46478             .filter(function (te) {
46479             return te.touches.length === 2 && te.targetTouches.length === 2;
46480         })
46481             .map(function (te) {
46482             return function (previous) {
46483                 var touch1 = te.touches[0];
46484                 var touch2 = te.touches[1];
46485                 var minX = Math.min(touch1.clientX, touch2.clientX);
46486                 var maxX = Math.max(touch1.clientX, touch2.clientX);
46487                 var minY = Math.min(touch1.clientY, touch2.clientY);
46488                 var maxY = Math.max(touch1.clientY, touch2.clientY);
46489                 var centerClientX = minX + (maxX - minX) / 2;
46490                 var centerClientY = minY + (maxY - minY) / 2;
46491                 var centerPageX = centerClientX + touch1.pageX - touch1.clientX;
46492                 var centerPageY = centerClientY + touch1.pageY - touch1.clientY;
46493                 var centerScreenX = centerClientX + touch1.screenX - touch1.clientX;
46494                 var centerScreenY = centerClientY + touch1.screenY - touch1.clientY;
46495                 var distanceX = Math.abs(touch1.clientX - touch2.clientX);
46496                 var distanceY = Math.abs(touch1.clientY - touch2.clientY);
46497                 var distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
46498                 var distanceChange = distance - previous.distance;
46499                 var changeX = distanceX - previous.distanceX;
46500                 var changeY = distanceY - previous.distanceY;
46501                 var current = {
46502                     changeX: changeX,
46503                     changeY: changeY,
46504                     clientX: centerClientX,
46505                     clientY: centerClientY,
46506                     distance: distance,
46507                     distanceChange: distanceChange,
46508                     distanceX: distanceX,
46509                     distanceY: distanceY,
46510                     originalEvent: te,
46511                     pageX: centerPageX,
46512                     pageY: centerPageY,
46513                     screenX: centerScreenX,
46514                     screenY: centerScreenY,
46515                     touch1: touch1,
46516                     touch2: touch2,
46517                 };
46518                 return current;
46519             };
46520         })
46521             .subscribe(this._pinchOperation$);
46522         this._pinchChange$ = this._pinchStart$
46523             .switchMap(function (te) {
46524             return _this._pinch$
46525                 .skip(1)
46526                 .takeUntil(_this._pinchEnd$);
46527         });
46528     }
46529     Object.defineProperty(TouchService.prototype, "active$", {
46530         get: function () {
46531             return this._active$;
46532         },
46533         enumerable: true,
46534         configurable: true
46535     });
46536     Object.defineProperty(TouchService.prototype, "activate$", {
46537         get: function () {
46538             return this._activeSubject$;
46539         },
46540         enumerable: true,
46541         configurable: true
46542     });
46543     Object.defineProperty(TouchService.prototype, "doubleTap$", {
46544         get: function () {
46545             return this._doubleTap$;
46546         },
46547         enumerable: true,
46548         configurable: true
46549     });
46550     Object.defineProperty(TouchService.prototype, "touchStart$", {
46551         get: function () {
46552             return this._touchStart$;
46553         },
46554         enumerable: true,
46555         configurable: true
46556     });
46557     Object.defineProperty(TouchService.prototype, "touchMove$", {
46558         get: function () {
46559             return this._touchMove$;
46560         },
46561         enumerable: true,
46562         configurable: true
46563     });
46564     Object.defineProperty(TouchService.prototype, "touchEnd$", {
46565         get: function () {
46566             return this._touchEnd$;
46567         },
46568         enumerable: true,
46569         configurable: true
46570     });
46571     Object.defineProperty(TouchService.prototype, "touchCancel$", {
46572         get: function () {
46573             return this._touchCancel$;
46574         },
46575         enumerable: true,
46576         configurable: true
46577     });
46578     Object.defineProperty(TouchService.prototype, "singleTouchDragStart$", {
46579         get: function () {
46580             return this._singleTouchDragStart$;
46581         },
46582         enumerable: true,
46583         configurable: true
46584     });
46585     Object.defineProperty(TouchService.prototype, "singleTouchDrag$", {
46586         get: function () {
46587             return this._singleTouchDrag$;
46588         },
46589         enumerable: true,
46590         configurable: true
46591     });
46592     Object.defineProperty(TouchService.prototype, "singleTouchDragEnd$", {
46593         get: function () {
46594             return this._singleTouchDragEnd$;
46595         },
46596         enumerable: true,
46597         configurable: true
46598     });
46599     Object.defineProperty(TouchService.prototype, "pinch$", {
46600         get: function () {
46601             return this._pinchChange$;
46602         },
46603         enumerable: true,
46604         configurable: true
46605     });
46606     Object.defineProperty(TouchService.prototype, "pinchStart$", {
46607         get: function () {
46608             return this._pinchStart$;
46609         },
46610         enumerable: true,
46611         configurable: true
46612     });
46613     Object.defineProperty(TouchService.prototype, "pinchEnd$", {
46614         get: function () {
46615             return this._pinchEnd$;
46616         },
46617         enumerable: true,
46618         configurable: true
46619     });
46620     return TouchService;
46621 }());
46622 exports.TouchService = TouchService;
46623
46624 },{"rxjs/BehaviorSubject":26,"rxjs/Observable":29,"rxjs/Subject":34,"rxjs/add/observable/timer":48,"rxjs/add/operator/bufferWhen":53,"rxjs/add/operator/filter":63,"rxjs/add/operator/map":67,"rxjs/add/operator/merge":68,"rxjs/add/operator/scan":78,"rxjs/add/operator/switchMap":84}],443:[function(require,module,exports){
46625 "use strict";
46626 /// <reference path="../../typings/index.d.ts" />
46627 var __extends = (this && this.__extends) || (function () {
46628     var extendStatics = Object.setPrototypeOf ||
46629         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
46630         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
46631     return function (d, b) {
46632         extendStatics(d, b);
46633         function __() { this.constructor = d; }
46634         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
46635     };
46636 })();
46637 Object.defineProperty(exports, "__esModule", { value: true });
46638 var when = require("when");
46639 var Observable_1 = require("rxjs/Observable");
46640 var Viewer_1 = require("../Viewer");
46641 var Utils_1 = require("../Utils");
46642 /**
46643  * @class Viewer
46644  *
46645  * @classdesc The Viewer object represents the navigable image viewer.
46646  * Create a Viewer by specifying a container, client ID, image key and
46647  * other options. The viewer exposes methods and events for programmatic
46648  * interaction.
46649  *
46650  * The viewer works with a few different coordinate systems.
46651  *
46652  * Container pixel coordinates
46653  *
46654  * Pixel coordinates are coordinates on the viewer container. The origin is
46655  * in the top left corner of the container. The axes are
46656  * directed according to the following for a viewer container with a width
46657  * of 640 pixels and height of 480 pixels.
46658  *
46659  * ```
46660  * (0,0)                          (640, 0)
46661  *      +------------------------>
46662  *      |
46663  *      |
46664  *      |
46665  *      v                        +
46666  * (0, 480)                       (640, 480)
46667  * ```
46668  *
46669  * Basic image coordinates
46670  *
46671  * Basic image coordinates represents points in the original image adjusted for
46672  * orientation. They range from 0 to 1 on both axes. The origin is in the top left
46673  * corner of the image and the axes are directed
46674  * according to the following for all image types.
46675  *
46676  * ```
46677  * (0,0)                          (1, 0)
46678  *      +------------------------>
46679  *      |
46680  *      |
46681  *      |
46682  *      v                        +
46683  * (0, 1)                         (1, 1)
46684  * ```
46685  *
46686  * For every camera viewing direction it is possible to convert between these
46687  * two coordinate systems for the current node. The image can be panned and
46688  * zoomed independently of the size of the viewer container resulting in
46689  * different conversion results for different viewing directions.
46690  */
46691 var Viewer = /** @class */ (function (_super) {
46692     __extends(Viewer, _super);
46693     /**
46694      * Create a new viewer instance.
46695      *
46696      * @description It is possible to initialize the viewer with or
46697      * without a key.
46698      *
46699      * When you want to show a specific image in the viewer from
46700      * the start you should initialize it with a key.
46701      *
46702      * When you do not know the first image key at implementation
46703      * time, e.g. in a map-viewer application you should initialize
46704      * the viewer without a key and call `moveToKey` instead.
46705      *
46706      * When initializing with a key the viewer is bound to that key
46707      * until the node for that key has been successfully loaded.
46708      * Also, a cover with the image of the key will be shown.
46709      * If the data for that key can not be loaded because the key is
46710      * faulty or other errors occur it is not possible to navigate
46711      * to another key because the viewer is not navigable. The viewer
46712      * becomes navigable when the data for the key has been loaded and
46713      * the image is shown in the viewer. This way of initializing
46714      * the viewer is mostly for embedding in blog posts and similar
46715      * where one wants to show a specific image initially.
46716      *
46717      * If the viewer is initialized without a key (with null or
46718      * undefined) it is not bound to any particular key and it is
46719      * possible to move to any key with `viewer.moveToKey("<my-image-key>")`.
46720      * If the first move to a key fails it is possible to move to another
46721      * key. The viewer will show a black background until a move
46722      * succeeds. This way of intitializing is suited for a map-viewer
46723      * application when the initial key is not known at implementation
46724      * time.
46725      *
46726      * @param {string} id - Required `id` of a DOM element which will
46727      * be transformed into the viewer.
46728      * @param {string} clientId - Required `Mapillary API ClientID`. Can
46729      * be obtained from https://www.mapillary.com/app/settings/developers.
46730      * @param {string} key - Optional `image-key` to start from. The key
46731      * can be any Mapillary image. If a key is provided the viewer is
46732      * bound to that key until it has been fully loaded. If null is provided
46733      * no image is loaded at viewer initialization and the viewer is not
46734      * bound to any particular key. Any image can then be navigated to
46735      * with e.g. `viewer.moveToKey("<my-image-key>")`.
46736      * @param {IViewerOptions} options - Optional configuration object
46737      * specifing Viewer's and the components' initial setup.
46738      * @param {string} token - Optional bearer token for API requests of
46739      * protected resources.
46740      *
46741      * @example
46742      * ```
46743      * var viewer = new Mapillary.Viewer("<element-id>", "<client-id>", "<image-key>");
46744      * ```
46745      */
46746     function Viewer(id, clientId, key, options, token) {
46747         var _this = _super.call(this) || this;
46748         options = options != null ? options : {};
46749         Utils_1.Settings.setOptions(options);
46750         Utils_1.Urls.setOptions(options.url);
46751         _this._navigator = new Viewer_1.Navigator(clientId, options, token);
46752         _this._container = new Viewer_1.Container(id, _this._navigator.stateService, options);
46753         _this._observer = new Viewer_1.Observer(_this, _this._navigator, _this._container);
46754         _this._componentController = new Viewer_1.ComponentController(_this._container, _this._navigator, _this._observer, key, options.component);
46755         return _this;
46756     }
46757     Object.defineProperty(Viewer.prototype, "isNavigable", {
46758         /**
46759          * Return a boolean indicating if the viewer is in a navigable state.
46760          *
46761          * @description The navigable state indicates if the viewer supports
46762          * moving, i.e. calling the {@link moveToKey}, {@link moveDir`}
46763          * and {@link moveCloseTo} methods or changing the authentication state,
46764          * i.e. calling {@link setAuthToken}. The viewer will not be in a navigable
46765          * state if the cover is activated and the viewer has been supplied a key.
46766          * When the cover is deactivated or the viewer is activated without being
46767          * supplied a key it will be navigable.
46768          *
46769          * @returns {boolean} Boolean indicating whether the viewer is navigable.
46770          */
46771         get: function () {
46772             return this._componentController.navigable;
46773         },
46774         enumerable: true,
46775         configurable: true
46776     });
46777     /**
46778      * Activate a component.
46779      *
46780      * @param {string} name - Name of the component which will become active.
46781      *
46782      * @example
46783      * ```
46784      * viewer.activateComponent("marker");
46785      * ```
46786      */
46787     Viewer.prototype.activateComponent = function (name) {
46788         this._componentController.activate(name);
46789     };
46790     /**
46791      * Activate the cover (deactivates all other components).
46792      */
46793     Viewer.prototype.activateCover = function () {
46794         this._componentController.activateCover();
46795     };
46796     /**
46797      * Deactivate a component.
46798      *
46799      * @param {string} name - Name of component which become inactive.
46800      *
46801      * @example
46802      * ```
46803      * viewer.deactivateComponent("mouse");
46804      * ```
46805      */
46806     Viewer.prototype.deactivateComponent = function (name) {
46807         this._componentController.deactivate(name);
46808     };
46809     /**
46810      * Deactivate the cover (activates all components marked as active).
46811      */
46812     Viewer.prototype.deactivateCover = function () {
46813         this._componentController.deactivateCover();
46814     };
46815     /**
46816      * Get the bearing of the current viewer camera.
46817      *
46818      * @description The bearing depends on how the camera
46819      * is currently rotated and does not correspond
46820      * to the compass angle of the current node if the view
46821      * has been panned.
46822      *
46823      * Bearing is measured in degrees clockwise with respect to
46824      * north.
46825      *
46826      * @returns {Promise<number>} Promise to the bearing
46827      * of the current viewer camera.
46828      *
46829      * @example
46830      * ```
46831      * viewer.getBearing().then((b) => { console.log(b); });
46832      * ```
46833      */
46834     Viewer.prototype.getBearing = function () {
46835         var _this = this;
46836         return when.promise(function (resolve, reject) {
46837             _this._container.renderService.bearing$
46838                 .first()
46839                 .subscribe(function (bearing) {
46840                 resolve(bearing);
46841             }, function (error) {
46842                 reject(error);
46843             });
46844         });
46845     };
46846     /**
46847      * Get the basic coordinates of the current image that is
46848      * at the center of the viewport.
46849      *
46850      * @description Basic coordinates are 2D coordinates on the [0, 1] interval
46851      * and have the origin point, (0, 0), at the top left corner and the
46852      * maximum value, (1, 1), at the bottom right corner of the original
46853      * image.
46854      *
46855      * @returns {Promise<number[]>} Promise to the basic coordinates
46856      * of the current image at the center for the viewport.
46857      *
46858      * @example
46859      * ```
46860      * viewer.getCenter().then((c) => { console.log(c); });
46861      * ```
46862      */
46863     Viewer.prototype.getCenter = function () {
46864         var _this = this;
46865         return when.promise(function (resolve, reject) {
46866             _this._navigator.stateService.getCenter()
46867                 .subscribe(function (center) {
46868                 resolve(center);
46869             }, function (error) {
46870                 reject(error);
46871             });
46872         });
46873     };
46874     /**
46875      * Get a component.
46876      *
46877      * @param {string} name - Name of component.
46878      * @returns {Component} The requested component.
46879      *
46880      * @example
46881      * ```
46882      * var mouseComponent = viewer.getComponent("mouse");
46883      * ```
46884      */
46885     Viewer.prototype.getComponent = function (name) {
46886         return this._componentController.get(name);
46887     };
46888     /**
46889      * Returns the viewer's containing HTML element.
46890      *
46891      * @returns {HTMLElement} The viewer's container.
46892      */
46893     Viewer.prototype.getContainer = function () {
46894         return this._container.element;
46895     };
46896     /**
46897      * Get the image's current zoom level.
46898      *
46899      * @returns {Promise<number>} Promise to the viewers's current
46900      * zoom level.
46901      *
46902      * @example
46903      * ```
46904      * viewer.getZoom().then((z) => { console.log(z); });
46905      * ```
46906      */
46907     Viewer.prototype.getZoom = function () {
46908         var _this = this;
46909         return when.promise(function (resolve, reject) {
46910             _this._navigator.stateService.getZoom()
46911                 .subscribe(function (zoom) {
46912                 resolve(zoom);
46913             }, function (error) {
46914                 reject(error);
46915             });
46916         });
46917     };
46918     /**
46919      * Move close to given latitude and longitude.
46920      *
46921      * @description Because the method propagates IO errors, these potential errors
46922      * need to be handled by the method caller (see example).
46923      *
46924      * @param {Number} lat - Latitude, in degrees.
46925      * @param {Number} lon - Longitude, in degrees.
46926      * @returns {Promise<Node>} Promise to the node that was navigated to.
46927      * @throws {Error} If no nodes exist close to provided latitude
46928      * longitude.
46929      * @throws {Error} Propagates any IO errors to the caller.
46930      * @throws {Error} When viewer is not navigable.
46931      *
46932      * @example
46933      * ```
46934      * viewer.moveCloseTo(0, 0).then(
46935      *     (n) => { console.log(n); },
46936      *     (e) => { console.error(e); });
46937      * ```
46938      */
46939     Viewer.prototype.moveCloseTo = function (lat, lon) {
46940         var moveCloseTo$ = this.isNavigable ?
46941             this._navigator.moveCloseTo$(lat, lon) :
46942             Observable_1.Observable.throw(new Error("Calling moveCloseTo is not supported when viewer is not navigable."));
46943         return when.promise(function (resolve, reject) {
46944             moveCloseTo$.subscribe(function (node) {
46945                 resolve(node);
46946             }, function (error) {
46947                 reject(error);
46948             });
46949         });
46950     };
46951     /**
46952      * Navigate in a given direction.
46953      *
46954      * @description This method has to be called through EdgeDirection enumeration as in the example.
46955      *
46956      * @param {EdgeDirection} dir - Direction in which which to move.
46957      * @returns {Promise<Node>} Promise to the node that was navigated to.
46958      * @throws {Error} If the current node does not have the edge direction
46959      * or the edges has not yet been cached.
46960      * @throws {Error} Propagates any IO errors to the caller.
46961      * @throws {Error} When viewer is not navigable.
46962      *
46963      * @example
46964      * ```
46965      * viewer.moveDir(Mapillary.EdgeDirection.Next).then(
46966      *     (n) => { console.log(n); },
46967      *     (e) => { console.error(e); });
46968      * ```
46969      */
46970     Viewer.prototype.moveDir = function (dir) {
46971         var moveDir$ = this.isNavigable ?
46972             this._navigator.moveDir$(dir) :
46973             Observable_1.Observable.throw(new Error("Calling moveDir is not supported when viewer is not navigable."));
46974         return when.promise(function (resolve, reject) {
46975             moveDir$.subscribe(function (node) {
46976                 resolve(node);
46977             }, function (error) {
46978                 reject(error);
46979             });
46980         });
46981     };
46982     /**
46983      * Navigate to a given image key.
46984      *
46985      * @param {string} key - A valid Mapillary image key.
46986      * @returns {Promise<Node>} Promise to the node that was navigated to.
46987      * @throws {Error} Propagates any IO errors to the caller.
46988      * @throws {Error} When viewer is not navigable.
46989      *
46990      * @example
46991      * ```
46992      * viewer.moveToKey("<my key>").then(
46993      *     (n) => { console.log(n); },
46994      *     (e) => { console.error(e); });
46995      * ```
46996      */
46997     Viewer.prototype.moveToKey = function (key) {
46998         var moveToKey$ = this.isNavigable ?
46999             this._navigator.moveToKey$(key) :
47000             Observable_1.Observable.throw(new Error("Calling moveToKey is not supported when viewer is not navigable."));
47001         return when.promise(function (resolve, reject) {
47002             moveToKey$.subscribe(function (node) {
47003                 resolve(node);
47004             }, function (error) {
47005                 reject(error);
47006             });
47007         });
47008     };
47009     /**
47010      * Project basic image coordinates for the current node to canvas pixel
47011      * coordinates.
47012      *
47013      * @description The basic image coordinates may not always correspond to a
47014      * pixel point that lies in the visible area of the viewer container.
47015      *
47016      * @param {Array<number>} basicPoint - Basic images coordinates to project.
47017      * @returns {Promise<Array<number>>} Promise to the pixel coordinates corresponding
47018      * to the basic image point.
47019      *
47020      * @example
47021      * ```
47022      * viewer.projectFromBasic([0.3, 0.7])
47023      *     .then((pixelPoint) => { console.log(pixelPoint); });
47024      * ```
47025      */
47026     Viewer.prototype.projectFromBasic = function (basicPoint) {
47027         var _this = this;
47028         return when.promise(function (resolve, reject) {
47029             _this._observer.projectBasic$(basicPoint)
47030                 .subscribe(function (pixelPoint) {
47031                 resolve(pixelPoint);
47032             }, function (error) {
47033                 reject(error);
47034             });
47035         });
47036     };
47037     /**
47038      * Detect the viewer's new width and height and resize it.
47039      *
47040      * @description The components will also detect the viewer's
47041      * new size and resize their rendered elements if needed.
47042      *
47043      * @example
47044      * ```
47045      * viewer.resize();
47046      * ```
47047      */
47048     Viewer.prototype.resize = function () {
47049         this._container.renderService.resize$.next(null);
47050         this._componentController.resize();
47051     };
47052     /**
47053      * Set a bearer token for authenticated API requests of
47054      * protected resources.
47055      *
47056      * @description When the supplied token is null or undefined,
47057      * any previously set bearer token will be cleared and the
47058      * viewer will make unauthenticated requests.
47059      *
47060      * Calling setAuthToken aborts all outstanding move requests.
47061      * The promises of those move requests will be rejected and
47062      * the rejections need to be caught.
47063      *
47064      * Calling setAuthToken also resets the complete viewer cache
47065      * so it should not be called repeatedly.
47066      *
47067      * @param {string} [token] token - Bearer token.
47068      * @returns {Promise<void>} Promise that resolves after token
47069      * is set.
47070      *
47071      * @throws {Error} When viewer is not navigable.
47072      *
47073      * @example
47074      * ```
47075      * viewer.setAuthToken("<my token>")
47076      *     .then(() => { console.log("token set"); });
47077      * ```
47078      */
47079     Viewer.prototype.setAuthToken = function (token) {
47080         var setToken$ = this.isNavigable ?
47081             this._navigator.setToken$(token) :
47082             Observable_1.Observable.throw(new Error("Calling setAuthToken is not supported when viewer is not navigable."));
47083         return when.promise(function (resolve, reject) {
47084             setToken$
47085                 .subscribe(function () {
47086                 resolve(undefined);
47087             }, function (error) {
47088                 reject(error);
47089             });
47090         });
47091     };
47092     /**
47093      * Set the basic coordinates of the current image to be in the
47094      * center of the viewport.
47095      *
47096      * @description Basic coordinates are 2D coordinates on the [0, 1] interval
47097      * and has the origin point, (0, 0), at the top left corner and the
47098      * maximum value, (1, 1), at the bottom right corner of the original
47099      * image.
47100      *
47101      * @param {number[]} The basic coordinates of the current
47102      * image to be at the center for the viewport.
47103      *
47104      * @example
47105      * ```
47106      * viewer.setCenter([0.5, 0.5]);
47107      * ```
47108      */
47109     Viewer.prototype.setCenter = function (center) {
47110         this._navigator.stateService.setCenter(center);
47111     };
47112     /**
47113      * Set the filter selecting nodes to use when calculating
47114      * the spatial edges.
47115      *
47116      * @description The following filter types are supported:
47117      *
47118      * Comparison
47119      *
47120      * `["==", key, value]` equality: `node[key] = value`
47121      *
47122      * `["!=", key, value]` inequality: `node[key] ≠ value`
47123      *
47124      * `["<", key, value]` less than: `node[key] < value`
47125      *
47126      * `["<=", key, value]` less than or equal: `node[key] ≤ value`
47127      *
47128      * `[">", key, value]` greater than: `node[key] > value`
47129      *
47130      * `[">=", key, value]` greater than or equal: `node[key] ≥ value`
47131      *
47132      * Set membership
47133      *
47134      * `["in", key, v0, ..., vn]` set inclusion: `node[key] ∈ {v0, ..., vn}`
47135      *
47136      * `["!in", key, v0, ..., vn]` set exclusion: `node[key] ∉ {v0, ..., vn}`
47137      *
47138      * Combining
47139      *
47140      * `["all", f0, ..., fn]` logical `AND`: `f0 ∧ ... ∧ fn`
47141      *
47142      * A key must be a string that identifies a property name of a
47143      * simple {@link Node} property. A value must be a string, number, or
47144      * boolean. Strictly-typed comparisons are used. The values
47145      * `f0, ..., fn` of the combining filter must be filter expressions.
47146      *
47147      * Clear the filter by setting it to null or empty array.
47148      *
47149      * @param {FilterExpression} filter - The filter expression.
47150      * @returns {Promise<void>} Promise that resolves after filter is applied.
47151      *
47152      * @example
47153      * ```
47154      * viewer.setFilter(["==", "sequenceKey", "<my sequence key>"]);
47155      * ```
47156      */
47157     Viewer.prototype.setFilter = function (filter) {
47158         var _this = this;
47159         return when.promise(function (resolve, reject) {
47160             _this._navigator.setFilter$(filter)
47161                 .subscribe(function () {
47162                 resolve(undefined);
47163             }, function (error) {
47164                 reject(error);
47165             });
47166         });
47167     };
47168     /**
47169      * Set the viewer's render mode.
47170      *
47171      * @param {RenderMode} renderMode - Render mode.
47172      *
47173      * @example
47174      * ```
47175      * viewer.setRenderMode(Mapillary.RenderMode.Letterbox);
47176      * ```
47177      */
47178     Viewer.prototype.setRenderMode = function (renderMode) {
47179         this._container.renderService.renderMode$.next(renderMode);
47180     };
47181     /**
47182      * Set the viewer's transition mode.
47183      *
47184      * @param {TransitionMode} transitionMode - Transition mode.
47185      *
47186      * @example
47187      * ```
47188      * viewer.setTransitionMode(Mapillary.TransitionMode.Instantaneous);
47189      * ```
47190      */
47191     Viewer.prototype.setTransitionMode = function (transitionMode) {
47192         this._navigator.stateService.setTransitionMode(transitionMode);
47193     };
47194     /**
47195      * Set the image's current zoom level.
47196      *
47197      * @description Possible zoom level values are on the [0, 3] interval.
47198      * Zero means zooming out to fit the image to the view whereas three
47199      * shows the highest level of detail.
47200      *
47201      * @param {number} The image's current zoom level.
47202      *
47203      * @example
47204      * ```
47205      * viewer.setZoom(2);
47206      * ```
47207      */
47208     Viewer.prototype.setZoom = function (zoom) {
47209         this._navigator.stateService.setZoom(zoom);
47210     };
47211     /**
47212      * Unproject canvas pixel coordinates to an ILatLon representing geographical
47213      * coordinates.
47214      *
47215      * @description The pixel point may not always correspond to geographical
47216      * coordinates. In the case of no correspondence the returned value will
47217      * be `null`.
47218      *
47219      * @param {Array<number>} pixelPoint - Pixel coordinates to unproject.
47220      * @returns {Promise<ILatLon>} Promise to the latLon corresponding to the pixel point.
47221      *
47222      * @example
47223      * ```
47224      * viewer.unproject([100, 100])
47225      *     .then((latLon) => { console.log(latLon); });
47226      * ```
47227      */
47228     Viewer.prototype.unproject = function (pixelPoint) {
47229         var _this = this;
47230         return when.promise(function (resolve, reject) {
47231             _this._observer.unproject$(pixelPoint)
47232                 .subscribe(function (latLon) {
47233                 resolve(latLon);
47234             }, function (error) {
47235                 reject(error);
47236             });
47237         });
47238     };
47239     /**
47240      * Unproject canvas pixel coordinates to basic image coordinates for the
47241      * current node.
47242      *
47243      * @description The pixel point may not always correspond to basic image
47244      * coordinates. In the case of no correspondence the returned value will
47245      * be `null`.
47246      *
47247      * @param {Array<number>} pixelPoint - Pixel coordinates to unproject.
47248      * @returns {Promise<ILatLon>} Promise to the basic coordinates corresponding
47249      * to the pixel point.
47250      *
47251      * @example
47252      * ```
47253      * viewer.unprojectToBasic([100, 100])
47254      *     .then((basicPoint) => { console.log(basicPoint); });
47255      * ```
47256      */
47257     Viewer.prototype.unprojectToBasic = function (pixelPoint) {
47258         var _this = this;
47259         return when.promise(function (resolve, reject) {
47260             _this._observer.unprojectBasic$(pixelPoint)
47261                 .subscribe(function (basicPoint) {
47262                 resolve(basicPoint);
47263             }, function (error) {
47264                 reject(error);
47265             });
47266         });
47267     };
47268     /**
47269      * Fired when the viewing direction of the camera changes.
47270      * @event
47271      * @type {number} bearing - Value indicating the current bearing
47272      * measured in degrees clockwise with respect to north.
47273      */
47274     Viewer.bearingchanged = "bearingchanged";
47275     /**
47276      * Fired when a pointing device (usually a mouse) is pressed and released at
47277      * the same point in the viewer.
47278      * @event
47279      * @type {IViewerMouseEvent} event - Viewer mouse event data.
47280      */
47281     Viewer.click = "click";
47282     /**
47283      * Fired when the right button of the mouse is clicked within the viewer.
47284      * @event
47285      * @type {IViewerMouseEvent} event - Viewer mouse event data.
47286      */
47287     Viewer.contextmenu = "contextmenu";
47288     /**
47289      * Fired when a pointing device (usually a mouse) is clicked twice at
47290      * the same point in the viewer.
47291      * @event
47292      * @type {IViewerMouseEvent} event - Viewer mouse event data.
47293      */
47294     Viewer.dblclick = "dblclick";
47295     /**
47296      * Fired when the viewer is loading more data.
47297      * @event
47298      * @type {boolean} loading - Boolean indicating whether the viewer is loading.
47299      */
47300     Viewer.loadingchanged = "loadingchanged";
47301     /**
47302      * Fired when a pointing device (usually a mouse) is pressed within the viewer.
47303      * @event
47304      * @type {IViewerMouseEvent} event - Viewer mouse event data.
47305      */
47306     Viewer.mousedown = "mousedown";
47307     /**
47308      * Fired when a pointing device (usually a mouse) is moved within the viewer.
47309      * @description Will not fire when the mouse is actively used, e.g. for drag pan.
47310      * @event
47311      * @type {IViewerMouseEvent} event - Viewer mouse event data.
47312      */
47313     Viewer.mousemove = "mousemove";
47314     /**
47315      * Fired when a pointing device (usually a mouse) leaves the viewer's canvas.
47316      * @event
47317      * @type {IViewerMouseEvent} event - Viewer mouse event data.
47318      */
47319     Viewer.mouseout = "mouseout";
47320     /**
47321      * Fired when a pointing device (usually a mouse) is moved onto the viewer's canvas.
47322      * @event
47323      * @type {IViewerMouseEvent} event - Viewer mouse event data.
47324      */
47325     Viewer.mouseover = "mouseover";
47326     /**
47327      * Fired when a pointing device (usually a mouse) is released within the viewer.
47328      * @event
47329      * @type {IViewerMouseEvent} event - Viewer mouse event data.
47330      */
47331     Viewer.mouseup = "mouseup";
47332     /**
47333      * Fired when the viewer motion stops and it is in a fixed
47334      * position with a fixed point of view.
47335      * @event
47336      */
47337     Viewer.moveend = "moveend";
47338     /**
47339      * Fired when the motion from one view to another start,
47340      * either by changing the position (e.g. when changing node) or
47341      * when changing point of view (e.g. by interaction such as pan and zoom).
47342      * @event
47343      */
47344     Viewer.movestart = "movestart";
47345     /**
47346      * Fired when the navigable state of the viewer changes.
47347      *
47348      * @description The navigable state indicates if the viewer supports
47349      * moving, i.e. calling the `moveToKey`, `moveDir` and `moveCloseTo`
47350      * methods. The viewer will not be in a navigable state if the cover
47351      * is activated and the viewer has been supplied a key. When the cover
47352      * is deactivated or activated without being supplied a key it will
47353      * be navigable.
47354      *
47355      * @event
47356      * @type {boolean} navigable - Boolean indicating whether the viewer is navigable.
47357      */
47358     Viewer.navigablechanged = "navigablechanged";
47359     /**
47360      * Fired every time the viewer navigates to a new node.
47361      * @event
47362      * @type {Node} node - Current node.
47363      */
47364     Viewer.nodechanged = "nodechanged";
47365     /**
47366      * Fired every time the sequence edges of the current node changes.
47367      * @event
47368      * @type {IEdgeStatus} status - The edge status object.
47369      */
47370     Viewer.sequenceedgeschanged = "sequenceedgeschanged";
47371     /**
47372      * Fired every time the spatial edges of the current node changes.
47373      * @event
47374      * @type {IEdgeStatus} status - The edge status object.
47375      */
47376     Viewer.spatialedgeschanged = "spatialedgeschanged";
47377     return Viewer;
47378 }(Utils_1.EventEmitter));
47379 exports.Viewer = Viewer;
47380
47381 },{"../Utils":301,"../Viewer":302,"rxjs/Observable":29,"when":288}]},{},[296])(296)
47382 });
47383 //# sourceMappingURL=mapillary.js.map